pax_global_header00006660000000000000000000000064141763150130014513gustar00rootroot0000000000000052 comment=2b0377fd28542a2b45f70e2490d773a4bcfd630a THELI-3.1.3/000077500000000000000000000000001417631501300123645ustar00rootroot00000000000000THELI-3.1.3/.gitignore000066400000000000000000000000701417631501300143510ustar00rootroot00000000000000build-THELI-Desktop-Release/ build-THELI-Desktop-Debug/ THELI-3.1.3/.gitignore~000066400000000000000000000000721417631501300145510ustar00rootroot00000000000000build-THELI-Desktop-Release/* build-THELI-Desktop-Debug/* THELI-3.1.3/COPYING000066400000000000000000000014411417631501300134170ustar00rootroot00000000000000THELI - A Pipeline To Process Astronomical Images Copyright (C) 2019 Mischa Schirmer 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . Mischa Schirmer (schirmer@mpia.de) MPI für Astronomie Königstuhl 17 62117 Heidelberg, Germany THELI-3.1.3/INSTALL000066400000000000000000000114451417631501300134220ustar00rootroot00000000000000Dependencies for building THELI =============================== You need the 'devel' versions of the following packages (either these version numbers, or more recent ones). Older versions might work but have not been tested: Qt5.9.6 https://www.qt.io/ cfitsio https://heasarc.gsfc.nasa.gov/fitsio/ (MUST BE configured with --enable-reentrant, otherwise you can use only one CPU !) fftw3 http://fftw.org/ GSL v2.5 https://www.gnu.org/software/gsl/ wcslib v7.2 https://www.atnf.csiro.au/people/mcalabre/WCS/ libraw v0.19.5 https://www.libraw.org/ libtiff https://gitlab.com/libtiff/libtiff Starting from Ubuntu 20.10, you can install THELI and all its dependencies from the repository: sudo apt install theli On a fresh Ubuntu 18.04 LTS installation, the following command resolves all dependencies (apart from libraw) and enable the compilation of 'scamp': sudo apt install g++ build-essential autotools-dev python3-requests python3-astropy libfftw3-dev libtiff-dev curl libcurl4 libcurl4-gnutls-dev qt5-default qt5-qmake libgsl-dev libatlas-base-dev libblas-dev libplplot-dev libcfitsio-dev wcslib-dev locales libcairo2-dev libnetpbm10-dev netpbm libpng-dev libjpeg-dev libpython3-dev python3-dev zlib1g-dev libbz2-dev swig Dependencies for running THELI ============================== THELI uses a few external packages. The respective binaries and scripts must be present in your $PATH variable. THELI will check for their presence upon launch and report any misconfigurations. Astrometry.net is also searched for in its default installation path, /usr/local/Astrometry/bin/ . swarp v2.38 https://github.com/astromatic/swarp scamp v2.7 https://github.com/astromatic/scamp Source Extractor v2.19 https://github.com/astromatic/sextractor python/astropy v4.0 https://www.astropy.org/ astrometry.net v0.79 https://github.com/dstndstn/astrometry.net/releases (OPTIONAL) Anaconda / AstroConda users BEWARE ================================== THELI will likely crash if compiled and linked against libraries provided by Anaconda / AstroConda, because the linker mixed native system libraries with those provided by Anaconda / AstroConda (which were probably built on a different system). To avoid this, deactivate your Anaconda environment. Solve the THELI dependencies using your native system's repository and / or compile the libraries from their sources. Then follow the installation instructions below. Whether the THELI executable will then run with Anaconda activated will depend on your local machine. Compilation =========== Parallelization in THELI is based on openMP. Your C++ compiler must support at least openMP 4.5. For GNU gcc/g++, this is the case for version 6 and later. Create the 'Makefile' and build it: > cd $HOME/software/THELI-master/src > qmake -o Makefile THELI.pro > make > make install (copies the binary to /usr/bin/theli and the config files to /usr/share/theli/) > make clean To speed up, replace 'make' by 'make -j x", where 'x' is the number of your CPUs The 'qmake' executable is part of the Qt5 dependence you have installed in the beginning. THELIDIR Environment variable (optional) ======================================== There are two cases in which you must set a THELIDIR environment variable: (1) You did not use 'make install' for a system-wide installation, e.g. if you don't have write permission in /usr (2) You want to install a newer version locally, next to a system-wide installation. Let's assume that the master branch of the THELI source package was unpacked in a 'software' folder in your home directory: $HOME/software/THELI-master/ Then you must set the THELIDIR environment variable to this path. For 'bash' you would do > export THELIDIR=$HOME/software/THELI-master/ Include the line above in your ~/.bashrc to make it permament. When launching THELI, Make sure you invoke $HOME/software/THELI-master/src/theli instead of /usr/bin/theli MacOS C++ compiler and openMP ============================= THELI has been successfully installed and run on MacOS Mojave. If you use the native Mac clang compiler, you must at least install 'libomp'. THELI has not been tested with the native compiler. Alternatively, try the LLVM clang version from http://releases.llvm.org/download.html. This was used to compile THELI on Mojave. However, it turned out that openMP parallelized tasks cause THELI to crash when more than one CPU was used. No trouble-shooting attempt was made. What should work without problems is if you use the GNU g++ compiler, which must be installed separately. You might have to edit the compiler flags near the end of src/THELI.pro accordingly. Or, after running the 'qmake -o Makefile THELI.pro' call, edit the Makefile, replace all references to clang++ to the GNU version (or the LLVM clang++ version). THELI-3.1.3/LICENSE000066400000000000000000001045151417631501300133770ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . THELI-3.1.3/README.md000066400000000000000000000025441417631501300136500ustar00rootroot00000000000000# THELI v3 THELI is a data processing pipeline for optical, near-infrared and mid-infrared astronomical images. Version 3 is a complete rewrite in C++ / Qt5 (compared to version 2 in Qt3), eliminating a large number of dependencies and overcoming installation issues. Using a hybrid memory/drive data model and full parallelization, v3 offers a vast gain in processing speed. Depending on the hardware and data set, processing speed may increase by factors 2 to 20. THELI v3 also fully scales with the amount of available RAM and CPUs on your machine, and there is still potential for further improvement. With its own integrated 'iView' FITS browser, advanced processing of astronomical imaging data has never been easier. THELI v3 also runs on MacOS. Even though the current release includes all instruments that were supported in THELI v2, not all of them have been tested. Please contact the author if you encounter data that do not run through the first processing step correctly. Mid-infrared cameras are currently not supported, but will be implemented on particular request and as soon as THELI v3 has been running stable for a while. If you need mid-IR support, please contact the author with a test data set. THELI v3 is not yet documented; a set of video tutorials is being made available at this URL: https://www.youtube.com/channel/UCg-9wvqQ5XpT1ph22feth9w/ THELI-3.1.3/config/000077500000000000000000000000001417631501300136315ustar00rootroot00000000000000THELI-3.1.3/config/default.conv000066400000000000000000000001301417631501300161360ustar00rootroot00000000000000CONV NORM # 3x3 ``all-ground'' convolution mask with FWHM = 2 pixels. 1 2 1 2 4 2 1 2 1 THELI-3.1.3/config/default.nnw000066400000000000000000000042131417631501300160010ustar00rootroot00000000000000NNW # Neural Network Weights for the SExtractor star/galaxy classifier (V1.3) # inputs: 9 for profile parameters + 1 for seeing. # outputs: ``Stellarity index'' (0.0 to 1.0) # Seeing FWHM range: from 0.025 to 5.5'' (images must have 1.5 < FWHM < 5 pixels) # Optimized for Moffat profiles with 2<= beta <= 4. 3 10 10 1 -1.56604e+00 -2.48265e+00 -1.44564e+00 -1.24675e+00 -9.44913e-01 -5.22453e-01 4.61342e-02 8.31957e-01 2.15505e+00 2.64769e-01 3.03477e+00 2.69561e+00 3.16188e+00 3.34497e+00 3.51885e+00 3.65570e+00 3.74856e+00 3.84541e+00 4.22811e+00 3.27734e+00 -3.22480e-01 -2.12804e+00 6.50750e-01 -1.11242e+00 -1.40683e+00 -1.55944e+00 -1.84558e+00 -1.18946e-01 5.52395e-01 -4.36564e-01 -5.30052e+00 4.62594e-01 -3.29127e+00 1.10950e+00 -6.01857e-01 1.29492e-01 1.42290e+00 2.90741e+00 2.44058e+00 -9.19118e-01 8.42851e-01 -4.69824e+00 -2.57424e+00 8.96469e-01 8.34775e-01 2.18845e+00 2.46526e+00 8.60878e-02 -6.88080e-01 -1.33623e-02 9.30403e-02 1.64942e+00 -1.01231e+00 4.81041e+00 1.53747e+00 -1.12216e+00 -3.16008e+00 -1.67404e+00 -1.75767e+00 -1.29310e+00 5.59549e-01 8.08468e-01 -1.01592e-02 -7.54052e+00 1.01933e+01 -2.09484e+01 -1.07426e+00 9.87912e-01 6.05210e-01 -6.04535e-02 -5.87826e-01 -7.94117e-01 -4.89190e-01 -8.12710e-02 -2.07067e+01 -5.31793e+00 7.94240e+00 -4.64165e+00 -4.37436e+00 -1.55417e+00 7.54368e-01 1.09608e+00 1.45967e+00 1.62946e+00 -1.01301e+00 1.13514e-01 2.20336e-01 1.70056e+00 -5.20105e-01 -4.28330e-01 1.57258e-03 -3.36502e-01 -8.18568e-02 -7.16163e+00 8.23195e+00 -1.71561e-02 -1.13749e+01 3.75075e+00 7.25399e+00 -1.75325e+00 -2.68814e+00 -3.71128e+00 -4.62933e+00 -2.13747e+00 -1.89186e-01 1.29122e+00 -7.49380e-01 6.71712e-01 -8.41923e-01 4.64997e+00 5.65808e-01 -3.08277e-01 -1.01687e+00 1.73127e-01 -8.92130e-01 1.89044e+00 -2.75543e-01 -7.72828e-01 5.36745e-01 -3.65598e+00 7.56997e+00 -3.76373e+00 -1.74542e+00 -1.37540e-01 -5.55400e-01 -1.59195e-01 1.27910e-01 1.91906e+00 1.42119e+00 -4.35502e+00 -1.70059e+00 -3.65695e+00 1.22367e+00 -5.74367e-01 -3.29571e+00 2.46316e+00 5.22353e+00 2.42038e+00 1.22919e+00 -9.22250e-01 -2.32028e+00 0.00000e+00 1.00000e+00 THELI-3.1.3/config/default.param000066400000000000000000000007111417631501300162760ustar00rootroot00000000000000NUMBER FLUX_AUTO FLUXERR_AUTO FLUX_MAX FLUX_APER(1) FLUXERR_APER(1) # VIGNET(20,20) MAG_AUTO MAGERR_AUTO ISOAREA_IMAGE XWIN_IMAGE YWIN_IMAGE ALPHA_J2000 DELTA_J2000 XWIN_WORLD YWIN_WORLD AWIN_IMAGE BWIN_IMAGE AWIN_WORLD BWIN_WORLD THETAWIN_IMAGE THETAWIN_J2000 ELONGATION ELLIPTICITY ERRAWIN_IMAGE ERRBWIN_IMAGE ERRTHETAWIN_IMAGE FWHM_IMAGE FWHM_WORLD FLAGS #IMAFLAGS_ISO #NIMAFLAGS_ISO FLUX_RADIUS ERRAWIN_WORLD ERRBWIN_WORLD ERRTHETAWIN_WORLD THELI-3.1.3/config/instruments/000077500000000000000000000000001417631501300162245ustar00rootroot00000000000000THELI-3.1.3/config/instruments/ACAM@WHT.ini000066400000000000000000000013511417631501300201110ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ACAM@WHT INSTSHORT=ACAM # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.25 GAIN=0.92 # Overscan regions. OVSCANX1=([1]=7) OVSCANX2=([1]=47) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=52) CUTY=([1]=150) SIZEX=([1]=2044) SIZEY=([1]=2044) # Reference pixels for each chip. REFPIXX=([1]=1000) REFPIXY=([1]=1000) TYPE=OPT THELI-3.1.3/config/instruments/ACAM@WHT.reg000066400000000000000000000004061417631501300201070ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: r1685832.fit[extension1] global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 physical circle(1035,1123,944.67829) THELI-3.1.3/config/instruments/ACS@HST.ini000066400000000000000000000013541417631501300200150ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ACS@HST INSTSHORT=ACS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT= OBSLONG=0.0 # Pixel scale in arcsec PIXSCALE=0.05 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=5350) SIZEY=([1]=5350) # Reference pixels for each chip. REFPIXX=([1]=2675) REFPIXY=([1]=2675) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/ALFOSC@NOT.ini000066400000000000000000000013621417631501300203570ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ALFOSC@NOT INSTSHORT=ALFOSC # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.189 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=4) OVSCANX2=([1]=49) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=79) CUTY=([1]=6) SIZEX=([1]=2019) SIZEY=([1]=2010) # Reference pixels for each chip. REFPIXX=([1]=1100) REFPIXY=([1]=1020) TYPE=OPT THELI-3.1.3/config/instruments/ALTAU16M@VYSOS06.ini000066400000000000000000000013671417631501300212000ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ALTAU16M@VYSOS06 INSTSHORT=ALTA # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=19.54 OBSLONG=-155.576 # Pixel scale in arcsec PIXSCALE=2.37 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=15) CUTY=([1]=29) SIZEX=([1]=4070) SIZEY=([1]=4058) # Reference pixels for each chip. REFPIXX=([1]=2048) REFPIXY=([1]=2048) TYPE=OPT THELI-3.1.3/config/instruments/AltaU42_HIGHRES@ASV.ini000066400000000000000000000013611417631501300217250ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=AltaU42_HIGHRES@ASV INSTSHORT=ALTA # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=43.14 OBSLONG=21.5 # Pixel scale in arcsec PIXSCALE=0.46 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) TYPE=OPT THELI-3.1.3/config/instruments/AltaU42_LOWRES@ASV.ini000066400000000000000000000013451417631501300216510ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=AltaU42_LOWRES@ASV INSTSHORT=ALTA # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=43.14 OBSLONG=21.5 # Pixel scale in arcsec PIXSCALE=0.93 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) TYPE=OPT THELI-3.1.3/config/instruments/ApogeeAlta@PROMPT4.ini000066400000000000000000000013751417631501300220630ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ApogeeAlta@PROMPT4 INSTSHORT=Alta # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.58 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/ApogeeAlta@PROMPT5.ini000066400000000000000000000013751417631501300220640ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ApogeeAlta@PROMPT5 INSTSHORT=ALTA # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.60 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/CFH12K@CFHT.ini000066400000000000000000000027121417631501300203520ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=CFH12K@CFHT INSTSHORT=CFH12K # Number of chips NCHIPS=12 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.204 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=5 [2]=5 [3]=5 [4]=5 [5]=5 [6]=5 [7]=2 [8]=5 [9]=2066 [10]=2055 [11]=5 [12]=5) OVSCANX2=([1]=25 [2]=25 [3]=25 [4]=25 [5]=25 [6]=25 [7]=16 [8]=25 [9]=2078 [10]=2075 [11]=25 [12]=25) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=35 [2]=35 [3]=35 [4]=35 [5]=35 [6]=35 [7]=35 [8]=35 [9]=10 [10]=10 [11]=35 [12]=35) CUTY=([1]=10 [2]=10 [3]=10 [4]=10 [5]=10 [6]=10 [7]=35 [8]=35 [9]=35 [10]=35 [11]=35 [12]=35) SIZEX=([1]=2038 [2]=2038 [3]=2038 [4]=2038 [5]=2038 [6]=2038 [7]=2038 [8]=2038 [9]=2038 [10]=2038 [11]=2038 [12]=2038) SIZEY=([1]=4086 [2]=4086 [3]=4086 [4]=4086 [5]=4086 [6]=4086 [7]=4086 [8]=4086 [9]=4086 [10]=4086 [11]=4086 [12]=4086) # Reference pixels for each chip. REFPIXX=([1]=6290 [2]=4210 [3]=-60 [4]=0 [5]=-2083 [6]=-4170 [7]=6268 [8]=4202 [9]=2112 [10]=0 [11]=-2100 [12]=-4184) REFPIXY=([1]=4433 [2]=4442 [3]=4442 [4]=4440 [5]=4423 [6]=4478 [7]=3808 [8]=3804 [9]=3792 [10]=3792 [11]=3770 [12]=3752) TYPE=OPT THELI-3.1.3/config/instruments/CFH12K@CFHT99.ahead000066400000000000000000000133541417631501300210230ustar00rootroot00000000000000CRPIX1 = -5.723310877E+01 / Reference pixel on this axis CRPIX2 = -1.056130078E+02 / Reference pixel on this axis CD1_1 = -5.710005961E-05 / Linear projection matrix CD1_2 = -1.125328839E-07 / Linear projection matrix CD2_1 = -1.269114724E-07 / Linear projection matrix CD2_2 = 5.703348636E-05 / Linear projection matrix END CRPIX1 = 2.030070892E+03 / Reference pixel on this axis CRPIX2 = -1.093281647E+02 / Reference pixel on this axis CD1_1 = -5.711497417E-05 / Linear projection matrix CD1_2 = -3.916967561E-07 / Linear projection matrix CD2_1 = -1.906297669E-07 / Linear projection matrix CD2_2 = 5.697245819E-05 / Linear projection matrix END CRPIX1 = 2.033208430E+03 / Reference pixel on this axis CRPIX2 = 4.018993500E+03 / Reference pixel on this axis CD1_1 = -5.697342336E-05 / Linear projection matrix CD1_2 = 1.515178290E-08 / Linear projection matrix CD2_1 = -1.239473510E-07 / Linear projection matrix CD2_2 = 5.691505381E-05 / Linear projection matrix END CRPIX1 = -5.427959228E+01 / Reference pixel on this axis CRPIX2 = 4.021581236E+03 / Reference pixel on this axis CD1_1 = -5.702109844E-05 / Linear projection matrix CD1_2 = -6.965472525E-08 / Linear projection matrix CD2_1 = 7.816048845E-09 / Linear projection matrix CD2_2 = 5.690266588E-05 / Linear projection matrix END CRPIX1 = -2.154166924E+03 / Reference pixel on this axis CRPIX2 = 4.044507233E+03 / Reference pixel on this axis CD1_1 = -5.673926114E-05 / Linear projection matrix CD1_2 = -2.299386572E-07 / Linear projection matrix CD2_1 = 2.476264532E-07 / Linear projection matrix CD2_2 = 5.670954568E-05 / Linear projection matrix END CRPIX1 = -2.147173901E+03 / Reference pixel on this axis CRPIX2 = -1.139261149E+02 / Reference pixel on this axis CD1_1 = -5.687176147E-05 / Linear projection matrix CD1_2 = -9.026914637E-08 / Linear projection matrix CD2_1 = -2.446624882E-07 / Linear projection matrix CD2_2 = 5.690492254E-05 / Linear projection matrix END CRPIX1 = 4.129148988E+03 / Reference pixel on this axis CRPIX2 = -1.217724595E+02 / Reference pixel on this axis CD1_1 = -5.672951912E-05 / Linear projection matrix CD1_2 = -3.038302114E-07 / Linear projection matrix CD2_1 = -4.893986568E-08 / Linear projection matrix CD2_2 = 5.687828722E-05 / Linear projection matrix END CRPIX1 = 4.125929333E+03 / Reference pixel on this axis CRPIX2 = 4.018050661E+03 / Reference pixel on this axis CD1_1 = -5.672811261E-05 / Linear projection matrix CD1_2 = 8.650039904E-08 / Linear projection matrix CD2_1 = -1.724033667E-07 / Linear projection matrix CD2_2 = 5.681233431E-05 / Linear projection matrix END CRPIX1 = -4.284560876E+03 / Reference pixel on this axis CRPIX2 = 4.063132130E+03 / Reference pixel on this axis CD1_1 = -5.609008382E-05 / Linear projection matrix CD1_2 = -2.870534468E-07 / Linear projection matrix CD2_1 = 2.401824008E-07 / Linear projection matrix CD2_2 = 5.637405702E-05 / Linear projection matrix END CRPIX1 = -4.282280710E+03 / Reference pixel on this axis CRPIX2 = -1.287840654E+02 / Reference pixel on this axis CD1_1 = -5.621988548E-05 / Linear projection matrix CD1_2 = 1.704010685E-08 / Linear projection matrix CD2_1 = -2.817792649E-07 / Linear projection matrix CD2_2 = 5.677792084E-05 / Linear projection matrix END CRPIX1 = 6.266448667E+03 / Reference pixel on this axis CRPIX2 = -1.516609320E+02 / Reference pixel on this axis CD1_1 = -5.607492819E-05 / Linear projection matrix CD1_2 = -3.678726499E-07 / Linear projection matrix CD2_1 = 1.725584583E-07 / Linear projection matrix CD2_2 = 5.663077512E-05 / Linear projection matrix END CRPIX1 = 6.257650943E+03 / Reference pixel on this axis CRPIX2 = 4.014035061E+03 / Reference pixel on this axis CD1_1 = -5.610448351E-05 / Linear projection matrix CD1_2 = 2.207675738E-07 / Linear projection matrix CD2_1 = -1.737050460E-07 / Linear projection matrix CD2_2 = 5.671743145E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/CFH12K@CFHT99.ini000066400000000000000000000027041417631501300205350ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=CFH12K@CFHT99 INSTSHORT=CFH12K # Number of chips NCHIPS=12 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.206 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=3 [2]=2 [3]=3 [4]=3 [5]=3 [6]=2 [7]=2 [8]=2 [9]=2075 [10]=2 [11]=2 [12]=2) OVSCANX2=([1]=22 [2]=16 [3]=22 [4]=22 [5]=22 [6]=16 [7]=16 [8]=16 [9]=2080 [10]=18 [11]=18 [12]=20) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=35 [2]=35 [3]=35 [4]=35 [5]=35 [6]=35 [7]=35 [8]=35 [9]=11 [10]=35 [11]=35 [12]=35) CUTY=([1]=35 [2]=35 [3]=9 [4]=9 [5]=9 [6]=35 [7]=38 [8]=7 [9]=11 [10]=38 [11]=38 [12]=7) SIZEX=([1]=2036 [2]=2036 [3]=2036 [4]=2036 [5]=2036 [6]=2036 [7]=2036 [8]=2036 [9]=2036 [10]=2036 [11]=2036 [12]=2036) SIZEY=([1]=4086 [2]=4086 [3]=4086 [4]=4086 [5]=4086 [6]=4086 [7]=4086 [8]=4086 [9]=4086 [10]=4086 [11]=4086 [12]=4086) # Reference pixels for each chip. REFPIXX=([1]=2084 [2]=-2 [3]=-6 [4]=2079 [5]=4173 [6]=4179 [7]=-2102 [8]=-2100 [9]=-4241 [10]=6313 [11]=-4238 [12]=-4227) REFPIXY=([1]=4057 [2]=4058 [3]=4173 [4]=4178 [5]=4188 [6]=4062 [7]=4066 [8]=4179 [9]=4213 [10]=4083 [11]=4097 [12]=4178) TYPE=OPT THELI-3.1.3/config/instruments/DECam@CTIO.ahead000066400000000000000000000712341417631501300207070ustar00rootroot00000000000000CRPIX1 = 1.338399343250E+04 / Reference pixel on this axis CRPIX2 = 6.239982143962E+03 / Reference pixel on this axis CD1_1 = -1.208412491725E-07 / Linear projection matrix CD1_2 = 7.307594903418E-05 / Linear projection matrix CD2_1 = -7.287874521230E-05 / Linear projection matrix CD2_2 = -4.150236807912E-08 / Linear projection matrix END CRPIX1 = -1.143428096601E+04 / Reference pixel on this axis CRPIX2 = -2.280308729406E+03 / Reference pixel on this axis CD1_1 = -1.705527090801E-07 / Linear projection matrix CD1_2 = 7.305738204746E-05 / Linear projection matrix CD2_1 = -7.286319201003E-05 / Linear projection matrix CD2_2 = -6.482887827435E-08 / Linear projection matrix END CRPIX1 = 1.338675274429E+04 / Reference pixel on this axis CRPIX2 = -2.277013798052E+03 / Reference pixel on this axis CD1_1 = -3.460567988724E-08 / Linear projection matrix CD1_2 = 7.304968759860E-05 / Linear projection matrix CD2_1 = -7.287101337715E-05 / Linear projection matrix CD2_2 = -1.702623947796E-07 / Linear projection matrix END CRPIX1 = 1.113401404314E+04 / Reference pixel on this axis CRPIX2 = 8.380255285371E+03 / Reference pixel on this axis CD1_1 = -2.029032662720E-07 / Linear projection matrix CD1_2 = 7.303772640997E-05 / Linear projection matrix CD2_1 = -7.289901218823E-05 / Linear projection matrix CD2_2 = -6.452750557738E-09 / Linear projection matrix END CRPIX1 = 1.113412710576E+04 / Reference pixel on this axis CRPIX2 = 4.110162447406E+03 / Reference pixel on this axis CD1_1 = -9.768118349022E-08 / Linear projection matrix CD1_2 = 7.311560925344E-05 / Linear projection matrix CD2_1 = -7.290013155364E-05 / Linear projection matrix CD2_2 = -2.957052532135E-08 / Linear projection matrix END CRPIX1 = 1.113707826395E+04 / Reference pixel on this axis CRPIX2 = -1.460851787643E+02 / Reference pixel on this axis CD1_1 = -5.594943977936E-08 / Linear projection matrix CD1_2 = 7.311363888641E-05 / Linear projection matrix CD2_1 = -7.287433966824E-05 / Linear projection matrix CD2_2 = -1.837416040290E-07 / Linear projection matrix END CRPIX1 = 1.113322960158E+04 / Reference pixel on this axis CRPIX2 = -4.414551749958E+03 / Reference pixel on this axis CD1_1 = 4.827191551682E-08 / Linear projection matrix CD1_2 = 7.303381954179E-05 / Linear projection matrix CD2_1 = -7.291252445094E-05 / Linear projection matrix CD2_2 = -2.080633965891E-07 / Linear projection matrix END CRPIX1 = 8.878606409607E+03 / Reference pixel on this axis CRPIX2 = 1.050797290941E+04 / Reference pixel on this axis CD1_1 = -1.790741631416E-07 / Linear projection matrix CD1_2 = 7.297986117762E-05 / Linear projection matrix CD2_1 = -7.298010134725E-05 / Linear projection matrix CD2_2 = 4.846157987859E-08 / Linear projection matrix END CRPIX1 = 8.870560551041E+03 / Reference pixel on this axis CRPIX2 = 6.252815656399E+03 / Reference pixel on this axis CD1_1 = -2.332284319155E-07 / Linear projection matrix CD1_2 = 7.311427240679E-05 / Linear projection matrix CD2_1 = -7.299119584335E-05 / Linear projection matrix CD2_2 = -6.122210489899E-08 / Linear projection matrix END CRPIX1 = 8.870273401137E+03 / Reference pixel on this axis CRPIX2 = 1.983434648820E+03 / Reference pixel on this axis CD1_1 = -8.138610288114E-08 / Linear projection matrix CD1_2 = 7.318333106851E-05 / Linear projection matrix CD2_1 = -7.298300970145E-05 / Linear projection matrix CD2_2 = -1.045794607181E-07 / Linear projection matrix END CRPIX1 = 8.873811284814E+03 / Reference pixel on this axis CRPIX2 = -2.274793328829E+03 / Reference pixel on this axis CD1_1 = -2.238344124094E-08 / Linear projection matrix CD1_2 = 7.311679625222E-05 / Linear projection matrix CD2_1 = -7.299059150590E-05 / Linear projection matrix CD2_2 = -2.022214293671E-07 / Linear projection matrix END CRPIX1 = 8.879172028222E+03 / Reference pixel on this axis CRPIX2 = -6.539597396408E+03 / Reference pixel on this axis CD1_1 = -3.416963134706E-09 / Linear projection matrix CD1_2 = 7.297763707022E-05 / Linear projection matrix CD2_1 = -7.298420255186E-05 / Linear projection matrix CD2_2 = -2.598953393665E-07 / Linear projection matrix END CRPIX1 = 6.616578285786E+03 / Reference pixel on this axis CRPIX2 = 1.264332617257E+04 / Reference pixel on this axis CD1_1 = -2.037611158221E-07 / Linear projection matrix CD1_2 = 7.291998395079E-05 / Linear projection matrix CD2_1 = -7.302309619388E-05 / Linear projection matrix CD2_2 = -7.210923412329E-09 / Linear projection matrix END CRPIX1 = 6.614757969305E+03 / Reference pixel on this axis CRPIX2 = 8.379804900502E+03 / Reference pixel on this axis CD1_1 = -2.147495862481E-07 / Linear projection matrix CD1_2 = 7.307249970818E-05 / Linear projection matrix CD2_1 = -7.307986185704E-05 / Linear projection matrix CD2_2 = -1.278865347139E-08 / Linear projection matrix END CRPIX1 = 6.607917729797E+03 / Reference pixel on this axis CRPIX2 = 4.111633328817E+03 / Reference pixel on this axis CD1_1 = -1.138235463178E-07 / Linear projection matrix CD1_2 = 7.322600406388E-05 / Linear projection matrix CD2_1 = -7.315445334229E-05 / Linear projection matrix CD2_2 = -5.095307590109E-08 / Linear projection matrix END CRPIX1 = 6.605805052701E+03 / Reference pixel on this axis CRPIX2 = -1.438280830353E+02 / Reference pixel on this axis CD1_1 = -4.418447865088E-08 / Linear projection matrix CD1_2 = 7.321609274068E-05 / Linear projection matrix CD2_1 = -7.312987219694E-05 / Linear projection matrix CD2_2 = -1.212832620569E-07 / Linear projection matrix END CRPIX1 = 6.617307727890E+03 / Reference pixel on this axis CRPIX2 = -4.408245922916E+03 / Reference pixel on this axis CD1_1 = 2.656930109751E-08 / Linear projection matrix CD1_2 = 7.307317586262E-05 / Linear projection matrix CD2_1 = -7.308656593356E-05 / Linear projection matrix CD2_2 = -2.206574432443E-07 / Linear projection matrix END CRPIX1 = 6.615299810730E+03 / Reference pixel on this axis CRPIX2 = -8.680865088410E+03 / Reference pixel on this axis CD1_1 = 1.376871924635E-08 / Linear projection matrix CD1_2 = 7.289504242823E-05 / Linear projection matrix CD2_1 = -7.303317150384E-05 / Linear projection matrix CD2_2 = -1.835364513230E-07 / Linear projection matrix END CRPIX1 = 4.365030947524E+03 / Reference pixel on this axis CRPIX2 = 1.264027011794E+04 / Reference pixel on this axis CD1_1 = -1.489241828289E-07 / Linear projection matrix CD1_2 = 7.291042284047E-05 / Linear projection matrix CD2_1 = -7.310856580939E-05 / Linear projection matrix CD2_2 = -9.078629054928E-09 / Linear projection matrix END CRPIX1 = 4.354294563976E+03 / Reference pixel on this axis CRPIX2 = 8.373294606318E+03 / Reference pixel on this axis CD1_1 = -1.543367390151E-07 / Linear projection matrix CD1_2 = 7.309164881694E-05 / Linear projection matrix CD2_1 = -7.316591321191E-05 / Linear projection matrix CD2_2 = -5.681433624987E-08 / Linear projection matrix END CRPIX1 = 4.353384563473E+03 / Reference pixel on this axis CRPIX2 = 4.111555281571E+03 / Reference pixel on this axis CD1_1 = -1.130062684960E-07 / Linear projection matrix CD1_2 = 7.326107030851E-05 / Linear projection matrix CD2_1 = -7.322220613530E-05 / Linear projection matrix CD2_2 = -8.151895527630E-08 / Linear projection matrix END CRPIX1 = 4.354554258025E+03 / Reference pixel on this axis CRPIX2 = -1.387990070287E+02 / Reference pixel on this axis CD1_1 = -1.173260374554E-07 / Linear projection matrix CD1_2 = 7.325092747570E-05 / Linear projection matrix CD2_1 = -7.322904086768E-05 / Linear projection matrix CD2_2 = -1.531062682947E-07 / Linear projection matrix END CRPIX1 = 4.359759186611E+03 / Reference pixel on this axis CRPIX2 = -4.404024548098E+03 / Reference pixel on this axis CD1_1 = -4.118006087792E-08 / Linear projection matrix CD1_2 = 7.310471152730E-05 / Linear projection matrix CD2_1 = -7.315406234086E-05 / Linear projection matrix CD2_2 = -1.820487135063E-07 / Linear projection matrix END CRPIX1 = 4.363457814101E+03 / Reference pixel on this axis CRPIX2 = -8.678151786464E+03 / Reference pixel on this axis CD1_1 = -4.906863537188E-09 / Linear projection matrix CD1_2 = 7.289629834902E-05 / Linear projection matrix CD2_1 = -7.307816493409E-05 / Linear projection matrix CD2_2 = -1.834290960404E-07 / Linear projection matrix END CRPIX1 = 2.104882174632E+03 / Reference pixel on this axis CRPIX2 = 1.477379921779E+04 / Reference pixel on this axis CD1_1 = -7.914869335496E-08 / Linear projection matrix CD1_2 = 7.286324133634E-05 / Linear projection matrix CD2_1 = -7.307298306419E-05 / Linear projection matrix CD2_2 = -6.826660102155E-08 / Linear projection matrix END CRPIX1 = 2.102121414604E+03 / Reference pixel on this axis CRPIX2 = 1.050562789084E+04 / Reference pixel on this axis CD1_1 = -9.683511349522E-08 / Linear projection matrix CD1_2 = 7.300044827594E-05 / Linear projection matrix CD2_1 = -7.314580265130E-05 / Linear projection matrix CD2_2 = -9.959658184495E-08 / Linear projection matrix END CRPIX1 = 2.099303159048E+03 / Reference pixel on this axis CRPIX2 = 6.238501670324E+03 / Reference pixel on this axis CD1_1 = -1.202398423749E-07 / Linear projection matrix CD1_2 = 7.318363988332E-05 / Linear projection matrix CD2_1 = -7.322320333323E-05 / Linear projection matrix CD2_2 = -1.040111717021E-07 / Linear projection matrix END CRPIX1 = 2.101520164450E+03 / Reference pixel on this axis CRPIX2 = 1.980111354073E+03 / Reference pixel on this axis CD1_1 = -3.621822167647E-08 / Linear projection matrix CD1_2 = 7.329012489143E-05 / Linear projection matrix CD2_1 = -7.326794641850E-05 / Linear projection matrix CD2_2 = -7.751241046070E-08 / Linear projection matrix END CRPIX1 = 2.099086322802E+03 / Reference pixel on this axis CRPIX2 = -2.268759677406E+03 / Reference pixel on this axis CD1_1 = -8.562950053656E-08 / Linear projection matrix CD1_2 = 7.320573861081E-05 / Linear projection matrix CD2_1 = -7.324064006245E-05 / Linear projection matrix CD2_2 = -1.017611095166E-07 / Linear projection matrix END CRPIX1 = 2.101507229823E+03 / Reference pixel on this axis CRPIX2 = -6.540668070706E+03 / Reference pixel on this axis CD1_1 = -2.921822192642E-08 / Linear projection matrix CD1_2 = 7.299754253888E-05 / Linear projection matrix CD2_1 = -7.316754941155E-05 / Linear projection matrix CD2_2 = -1.215707902547E-07 / Linear projection matrix END CRPIX1 = 2.100197556706E+03 / Reference pixel on this axis CRPIX2 = -1.080682500083E+04 / Reference pixel on this axis CD1_1 = -3.765498022037E-08 / Linear projection matrix CD1_2 = 7.286459468480E-05 / Linear projection matrix CD2_1 = -7.308211175282E-05 / Linear projection matrix CD2_2 = -9.329522666110E-08 / Linear projection matrix END CRPIX1 = -1.597270644612E+02 / Reference pixel on this axis CRPIX2 = 1.477353622042E+04 / Reference pixel on this axis CD1_1 = -7.057640725602E-08 / Linear projection matrix CD1_2 = 7.287905621247E-05 / Linear projection matrix CD2_1 = -7.308097413654E-05 / Linear projection matrix CD2_2 = -1.571255810535E-07 / Linear projection matrix END CRPIX1 = -1.560870105635E+02 / Reference pixel on this axis CRPIX2 = 1.050718050220E+04 / Reference pixel on this axis CD1_1 = -7.143469060140E-08 / Linear projection matrix CD1_2 = 7.299920497819E-05 / Linear projection matrix CD2_1 = -7.316556044473E-05 / Linear projection matrix CD2_2 = -1.580012162248E-07 / Linear projection matrix END CRPIX1 = -1.495703281008E+02 / Reference pixel on this axis CRPIX2 = 6.239953497307E+03 / Reference pixel on this axis CD1_1 = -3.995164477299E-08 / Linear projection matrix CD1_2 = 7.319696101773E-05 / Linear projection matrix CD2_1 = -7.323024123530E-05 / Linear projection matrix CD2_2 = -9.487767012543E-08 / Linear projection matrix END CRPIX1 = -1.492109221998E+02 / Reference pixel on this axis CRPIX2 = 1.986106684130E+03 / Reference pixel on this axis CD1_1 = -7.605174128415E-08 / Linear projection matrix CD1_2 = 7.327144844395E-05 / Linear projection matrix CD2_1 = -7.326730116174E-05 / Linear projection matrix CD2_2 = -8.908009222973E-08 / Linear projection matrix END CRPIX1 = -1.534020049820E+02 / Reference pixel on this axis CRPIX2 = -2.264761885576E+03 / Reference pixel on this axis CD1_1 = -6.538575900085E-08 / Linear projection matrix CD1_2 = 7.319252674647E-05 / Linear projection matrix CD2_1 = -7.325006595243E-05 / Linear projection matrix CD2_2 = -5.039822277777E-08 / Linear projection matrix END CRPIX1 = -1.531024149980E+02 / Reference pixel on this axis CRPIX2 = -6.535660320825E+03 / Reference pixel on this axis CD1_1 = -8.444213807910E-08 / Linear projection matrix CD1_2 = 7.298730654772E-05 / Linear projection matrix CD2_1 = -7.316922782884E-05 / Linear projection matrix CD2_2 = -6.523391301714E-08 / Linear projection matrix END CRPIX1 = -1.482576965185E+02 / Reference pixel on this axis CRPIX2 = -1.080385806151E+04 / Reference pixel on this axis CD1_1 = -1.481377376253E-07 / Linear projection matrix CD1_2 = 7.286950665587E-05 / Linear projection matrix CD2_1 = -7.304987017431E-05 / Linear projection matrix CD2_2 = -1.143950853914E-07 / Linear projection matrix END CRPIX1 = -2.409191982946E+03 / Reference pixel on this axis CRPIX2 = 1.264913781302E+04 / Reference pixel on this axis CD1_1 = 1.655213486890E-08 / Linear projection matrix CD1_2 = 7.289305055235E-05 / Linear projection matrix CD2_1 = -7.306504168067E-05 / Linear projection matrix CD2_2 = -1.530581070642E-07 / Linear projection matrix END CRPIX1 = -2.405116204391E+03 / Reference pixel on this axis CRPIX2 = 8.378136535416E+03 / Reference pixel on this axis CD1_1 = 2.571193750547E-08 / Linear projection matrix CD1_2 = 7.309181733978E-05 / Linear projection matrix CD2_1 = -7.315294519967E-05 / Linear projection matrix CD2_2 = -1.461445314879E-07 / Linear projection matrix END CRPIX1 = -2.399178299719E+03 / Reference pixel on this axis CRPIX2 = 4.113436931650E+03 / Reference pixel on this axis CD1_1 = -3.734436946334E-08 / Linear projection matrix CD1_2 = 7.324016524124E-05 / Linear projection matrix CD2_1 = -7.320596430691E-05 / Linear projection matrix CD2_2 = -9.789808353283E-08 / Linear projection matrix END CRPIX1 = -2.401459739329E+03 / Reference pixel on this axis CRPIX2 = -1.432597208528E+02 / Reference pixel on this axis CD1_1 = -1.159518252986E-07 / Linear projection matrix CD1_2 = 7.320432813886E-05 / Linear projection matrix CD2_1 = -7.320693503463E-05 / Linear projection matrix CD2_2 = -9.110452901172E-08 / Linear projection matrix END CRPIX1 = -2.407403523722E+03 / Reference pixel on this axis CRPIX2 = -4.399792681451E+03 / Reference pixel on this axis CD1_1 = -1.029188412776E-07 / Linear projection matrix CD1_2 = 7.310376569054E-05 / Linear projection matrix CD2_1 = -7.315066201706E-05 / Linear projection matrix CD2_2 = -3.399406117116E-08 / Linear projection matrix END CRPIX1 = -2.415845512559E+03 / Reference pixel on this axis CRPIX2 = -8.673845926900E+03 / Reference pixel on this axis CD1_1 = -1.552959215578E-07 / Linear projection matrix CD1_2 = 7.290527261571E-05 / Linear projection matrix CD2_1 = -7.306392944246E-05 / Linear projection matrix CD2_2 = -4.128708519143E-09 / Linear projection matrix END CRPIX1 = -4.661495666063E+03 / Reference pixel on this axis CRPIX2 = 1.264841284813E+04 / Reference pixel on this axis CD1_1 = 3.397688186562E-08 / Linear projection matrix CD1_2 = 7.291531873400E-05 / Linear projection matrix CD2_1 = -7.302415085687E-05 / Linear projection matrix CD2_2 = -1.677482219766E-07 / Linear projection matrix END CRPIX1 = -4.660738562795E+03 / Reference pixel on this axis CRPIX2 = 8.385056777895E+03 / Reference pixel on this axis CD1_1 = 3.490516245508E-08 / Linear projection matrix CD1_2 = 7.306823729417E-05 / Linear projection matrix CD2_1 = -7.306983954010E-05 / Linear projection matrix CD2_2 = -1.684887530705E-07 / Linear projection matrix END CRPIX1 = -4.660081480107E+03 / Reference pixel on this axis CRPIX2 = 4.114315613560E+03 / Reference pixel on this axis CD1_1 = -5.670485098296E-08 / Linear projection matrix CD1_2 = 7.320107467203E-05 / Linear projection matrix CD2_1 = -7.308531583519E-05 / Linear projection matrix CD2_2 = -1.700978968061E-07 / Linear projection matrix END CRPIX1 = -4.659411438843E+03 / Reference pixel on this axis CRPIX2 = -1.362639522859E+02 / Reference pixel on this axis CD1_1 = -8.588155711280E-08 / Linear projection matrix CD1_2 = 7.322431515431E-05 / Linear projection matrix CD2_1 = -7.309953292799E-05 / Linear projection matrix CD2_2 = -4.727754011278E-08 / Linear projection matrix END CRPIX1 = -4.663341931037E+03 / Reference pixel on this axis CRPIX2 = -4.407700789306E+03 / Reference pixel on this axis CD1_1 = -2.040661854105E-07 / Linear projection matrix CD1_2 = 7.308170724249E-05 / Linear projection matrix CD2_1 = -7.307152483768E-05 / Linear projection matrix CD2_2 = -9.506043547997E-09 / Linear projection matrix END CRPIX1 = -4.665768271006E+03 / Reference pixel on this axis CRPIX2 = -8.675989310984E+03 / Reference pixel on this axis CD1_1 = -1.621651155990E-07 / Linear projection matrix CD1_2 = 7.289309809424E-05 / Linear projection matrix CD2_1 = -7.305112462071E-05 / Linear projection matrix CD2_2 = 6.566454771803E-09 / Linear projection matrix END CRPIX1 = -6.929837718410E+03 / Reference pixel on this axis CRPIX2 = 1.051285216083E+04 / Reference pixel on this axis CD1_1 = 2.189863029509E-08 / Linear projection matrix CD1_2 = 7.297427923639E-05 / Linear projection matrix CD2_1 = -7.296158607050E-05 / Linear projection matrix CD2_2 = -2.494747786052E-07 / Linear projection matrix END CRPIX1 = -6.916322640214E+03 / Reference pixel on this axis CRPIX2 = 6.246827134032E+03 / Reference pixel on this axis CD1_1 = -1.305373195432E-08 / Linear projection matrix CD1_2 = 7.312048178053E-05 / Linear projection matrix CD2_1 = -7.301686808367E-05 / Linear projection matrix CD2_2 = -1.841565954408E-07 / Linear projection matrix END CRPIX1 = -6.912169174698E+03 / Reference pixel on this axis CRPIX2 = 1.986368925165E+03 / Reference pixel on this axis CD1_1 = -7.015654086367E-08 / Linear projection matrix CD1_2 = 7.317953767535E-05 / Linear projection matrix CD2_1 = -7.302401636541E-05 / Linear projection matrix CD2_2 = -1.071456518427E-07 / Linear projection matrix END CRPIX1 = -6.920252479385E+03 / Reference pixel on this axis CRPIX2 = -2.276469997191E+03 / Reference pixel on this axis CD1_1 = -1.722793083096E-07 / Linear projection matrix CD1_2 = 7.310966358332E-05 / Linear projection matrix CD2_1 = -7.299366665196E-05 / Linear projection matrix CD2_2 = -3.989985369867E-08 / Linear projection matrix END CRPIX1 = -6.928598986438E+03 / Reference pixel on this axis CRPIX2 = -6.545814717134E+03 / Reference pixel on this axis CD1_1 = -2.291299334150E-07 / Linear projection matrix CD1_2 = 7.296590262275E-05 / Linear projection matrix CD2_1 = -7.295279900916E-05 / Linear projection matrix CD2_2 = 3.167361096143E-08 / Linear projection matrix END CRPIX1 = -9.184439401364E+03 / Reference pixel on this axis CRPIX2 = 8.382635383980E+03 / Reference pixel on this axis CD1_1 = 2.442609656425E-08 / Linear projection matrix CD1_2 = 7.302493497048E-05 / Linear projection matrix CD2_1 = -7.289611931884E-05 / Linear projection matrix CD2_2 = -2.241864090979E-07 / Linear projection matrix END CRPIX1 = -9.176396100729E+03 / Reference pixel on this axis CRPIX2 = 4.121612913751E+03 / Reference pixel on this axis CD1_1 = -2.871945481120E-08 / Linear projection matrix CD1_2 = 7.312188452363E-05 / Linear projection matrix CD2_1 = -7.291711264322E-05 / Linear projection matrix CD2_2 = -1.571938543529E-07 / Linear projection matrix END CRPIX1 = -9.177621797606E+03 / Reference pixel on this axis CRPIX2 = -1.410872948763E+02 / Reference pixel on this axis CD1_1 = -1.025913181476E-07 / Linear projection matrix CD1_2 = 7.312550377861E-05 / Linear projection matrix CD2_1 = -7.291817367277E-05 / Linear projection matrix CD2_2 = -3.047619778174E-08 / Linear projection matrix END CRPIX1 = -9.183453008050E+03 / Reference pixel on this axis CRPIX2 = -4.404482765845E+03 / Reference pixel on this axis CD1_1 = -1.682109241475E-07 / Linear projection matrix CD1_2 = 7.303096022896E-05 / Linear projection matrix CD2_1 = -7.289781845476E-05 / Linear projection matrix CD2_2 = 2.232139926722E-08 / Linear projection matrix END CRPIX1 = -1.143522247866E+04 / Reference pixel on this axis CRPIX2 = 6.237138581440E+03 / Reference pixel on this axis CD1_1 = -8.409552767120E-08 / Linear projection matrix CD1_2 = 7.306749729628E-05 / Linear projection matrix CD2_1 = -7.287532715999E-05 / Linear projection matrix CD2_2 = -2.004283416637E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/DECam@CTIO.ini000066400000000000000000000114701417631501300204200ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=DECam@CTIO INSTSHORT=DECam # Number of chips NCHIPS=60 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.2632 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0 [37]=0 [38]=0 [39]=0 [40]=0 [41]=0 [42]=0 [43]=0 [44]=0 [45]=0 [46]=0 [47]=0 [48]=0 [49]=0 [50]=0 [51]=0 [52]=0 [53]=0 [54]=0 [55]=0 [56]=0 [57]=0 [58]=0 [59]=0 [60]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0 [37]=0 [38]=0 [39]=0 [40]=0 [41]=0 [42]=0 [43]=0 [44]=0 [45]=0 [46]=0 [47]=0 [48]=0 [49]=0 [50]=0 [51]=0 [52]=0 [53]=0 [54]=0 [55]=0 [56]=0 [57]=0 [58]=0 [59]=0 [60]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=36 [2]=36 [3]=36 [4]=36 [5]=36 [6]=36 [7]=36 [8]=36 [9]=36 [10]=36 [11]=36 [12]=36 [13]=36 [14]=36 [15]=36 [16]=36 [17]=36 [18]=36 [19]=36 [20]=36 [21]=36 [22]=36 [23]=36 [24]=36 [25]=36 [26]=36 [27]=36 [28]=36 [29]=36 [30]=36 [31]=36 [32]=36 [33]=36 [34]=36 [35]=36 [36]=36 [37]=36 [38]=36 [39]=36 [40]=36 [41]=36 [42]=36 [43]=36 [44]=36 [45]=36 [46]=36 [47]=36 [48]=36 [49]=36 [50]=36 [51]=36 [52]=36 [53]=36 [54]=36 [55]=36 [56]=36 [57]=36 [58]=36 [59]=36 [60]=36) CUTY=([1]=22 [2]=22 [3]=22 [4]=22 [5]=22 [6]=22 [7]=22 [8]=22 [9]=22 [10]=22 [11]=22 [12]=22 [13]=22 [14]=22 [15]=22 [16]=22 [17]=22 [18]=22 [19]=22 [20]=22 [21]=22 [22]=22 [23]=22 [24]=22 [25]=22 [26]=22 [27]=22 [28]=22 [29]=22 [30]=22 [31]=22 [32]=22 [33]=22 [34]=22 [35]=22 [36]=22 [37]=22 [38]=22 [39]=22 [40]=22 [41]=22 [42]=22 [43]=22 [44]=22 [45]=22 [46]=22 [47]=22 [48]=22 [49]=22 [50]=22 [51]=22 [52]=22 [53]=22 [54]=22 [55]=22 [56]=22 [57]=22 [58]=22 [59]=22 [60]=22) SIZEX=([1]=1972 [2]=1972 [3]=1972 [4]=1972 [5]=1972 [6]=1972 [7]=1972 [8]=1972 [9]=1972 [10]=1972 [11]=1972 [12]=1972 [13]=1972 [14]=1972 [15]=1972 [16]=1972 [17]=1972 [18]=1972 [19]=1972 [20]=1972 [21]=1972 [22]=1972 [23]=1972 [24]=1972 [25]=1972 [26]=1972 [27]=1972 [28]=1972 [29]=1972 [30]=1972 [31]=1972 [32]=1972 [33]=1972 [34]=1972 [35]=1972 [36]=1972 [37]=1972 [38]=1972 [39]=1972 [40]=1972 [41]=1972 [42]=1972 [43]=1972 [44]=1972 [45]=1972 [46]=1972 [47]=1972 [48]=1972 [49]=1972 [50]=1972 [51]=1972 [52]=1972 [53]=1972 [54]=1972 [55]=1972 [56]=1972 [57]=1972 [58]=1972 [59]=1972 [60]=1972) SIZEY=([1]=4054 [2]=4054 [3]=4054 [4]=4054 [5]=4054 [6]=4054 [7]=4054 [8]=4054 [9]=4054 [10]=4054 [11]=4054 [12]=4054 [13]=4054 [14]=4054 [15]=4054 [16]=4054 [17]=4054 [18]=4054 [19]=4054 [20]=4054 [21]=4054 [22]=4054 [23]=4054 [24]=4054 [25]=4054 [26]=4054 [27]=4054 [28]=4054 [29]=4054 [30]=4054 [31]=4054 [32]=4054 [33]=4054 [34]=4054 [35]=4054 [36]=4054 [37]=4054 [38]=4054 [39]=4054 [40]=4054 [41]=4054 [42]=4054 [43]=4054 [44]=4054 [45]=4054 [46]=4054 [47]=4054 [48]=4054 [49]=4054 [50]=4054 [51]=4054 [52]=4054 [53]=4054 [54]=4054 [55]=4054 [56]=4054 [57]=4054 [58]=4054 [59]=4054 [60]=4054) # Reference pixels for each chip. REFPIXX=([1]=2151 [2]=2151 [3]=2151 [4]=-103 [5]=-103 [6]=-103 [7]=4405 [8]=4405 [9]=6660 [10]=6660 [11]=8914 [12]=11168 [13]=-2357 [14]=-2357 [15]=-4612 [16]=-4612 [17]=-6866 [18]=-9120 [19]=4405 [20]=4405 [21]=4405 [22]=4405 [23]=6660 [24]=6660 [25]=6660 [26]=6660 [27]=8914 [28]=8914 [29]=8914 [30]=8914 [31]=11168 [32]=11168 [33]=11168 [34]=13423 [35]=13423 [36]=13423 [37]=-103 [38]=-103 [39]=-103 [40]=-103 [41]=2151 [42]=2151 [43]=2151 [44]=2151 [45]=-2357 [46]=-2357 [47]=-2357 [48]=-2357 [49]=-4612 [50]=-4612 [51]=-4612 [52]=-4612 [53]=-6866 [54]=-6866 [55]=-6866 [56]=-6866 [57]=-9120 [58]=-9120 [59]=-9120 [60]=-11375 [61]=-11375 [62]=-11375) REFPIXY=([1]=14826 [2]=10566 [3]=6307 [4]=14826 [5]=10566 [6]=6307 [7]=12696 [8]=8437 [9]=12696 [10]=8437 [11]=10566 [12]=8437 [13]=12696 [14]=8437 [15]=12696 [16]=8437 [17]=10566 [18]=8437 [19]=4177 [20]=-81 [21]=-4341 [22]=-8600 [23]=-4341 [24]=-8600 [25]=4177 [26]=-81 [27]=6307 [28]=2048 [29]=-2211 [30]=-6470 [31]=4177 [32]=-81 [33]=-4341 [34]=6307 [35]=2048 [36]=-2211 [37]=2048 [38]=-2211 [39]=-6470 [40]=-10730 [41]=2048 [42]=-2211 [43]=-6470 [44]=-10730 [45]=4177 [46]=-81 [47]=-4341 [48]=-8600 [49]=-4341 [50]=-8600 [51]=4177 [52]=-81 [53]=6307 [54]=2048 [55]=-2211 [56]=-6470 [57]=4177 [58]=-81 [59]=-4341 [60]=6307 [61]=2048 [62]=-2211) TYPE=OPT THELI-3.1.3/config/instruments/DECam@CTIO_31.reg000066400000000000000000000002371417631501300207200ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: S20120226S0032_1.fits # Sense: in # Combine: and physical polygon(0.5,4054.5,989.5,4054.5,989.5,0.5,0.5,0.5) THELI-3.1.3/config/instruments/DEIMOS_1AMP@KECK.ahead000066400000000000000000000036201417631501300215050ustar00rootroot00000000000000CRPIX1 = 4.252805475353E+03 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962825E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END CRPIX1 = 2.096805475353E+03 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962825E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END CRPIX1 = -5.319452464737E+01 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962826E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END CRPIX1 = -2.200194524647E+03 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962825E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/DEIMOS_1AMP@KECK.ini000066400000000000000000000012571417631501300212260ustar00rootroot00000000000000INSTRUMENT=DEIMOS_1AMP@KECK INSTSHORT=DEIMOS NCHIPS=4 # Geographic location OBSLAT=19.82 OBSLONG=-155.47 # Plate scale PIXSCALE=0.1185 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=2070 [2]=2070 [3]=2070 [4]=2070) OVSCANX2=([1]=2130 [2]=2130 [3]=2130 [4]=2130) OVSCANY1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANY2=([1]=0 [2]=0 [3]=0 [4]=0) CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2601 [2]=2601 [3]=2601 [4]=2601) REFPIXX=([1]=4253 [2]=2097 [3]=-53 [4]=-2200) REFPIXY=([1]=1301 [2]=1301 [3]=1301 [4]=1301) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/DEIMOS_1AMP@KECK_1.reg000066400000000000000000000002361417631501300214400ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(49.934348,2501.2712,2069.7633,2498.4781,2071.8344,209.61941,849.2902,224.46813,49.934348,989.17697) THELI-3.1.3/config/instruments/DEIMOS_1AMP@KECK_2.reg000066400000000000000000000004261417631501300214420ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(20.011505,2507.9837,2069.7633,2508.1743,2069.7633,767.71016,1524.3532,709.53308,1284.3728,629.53961,970.1371,542.89453,673.37872,520.45062,453.92713,478.05657,351.68265,403.24353,266.89453,263.59252,22.505273,266.08629) THELI-3.1.3/config/instruments/DEIMOS_1AMP@KECK_3.reg000066400000000000000000000007301417631501300214410ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(17.517737,2520.4525,44.134902,2518.5808,45.952936,2462.2218,113.22018,2464.6459,116.25023,2522.2169,540.01631,2538.5979,1426.3453,2541.212,1430.5874,2458.1885,1520.883,2458.1885,1518.459,2540.606,2084.3075,2536.6568,2069.7633,107.76398,1769.9106,127.95147,1740.7114,156.3605,1611.5243,375.43007,1502.5368,519.85158,1303.7651,582.87675,1321.9743,580.8373,856.71456,667.4548,364.23216,754.07231,17.517737,774.81496) THELI-3.1.3/config/instruments/DEIMOS_1AMP@KECK_4.reg000066400000000000000000000003051417631501300214400ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(17.517737,2560.3528,1946.137,2551.8071,1946.137,1383.4175,1778.8779,1225.8546,1810.3905,1133.7409,768.05126,113.21808,17.517737,116.46021) THELI-3.1.3/config/instruments/DEIMOS_2AMP@KECK.ahead000066400000000000000000000036201417631501300215060ustar00rootroot00000000000000CRPIX1 = 4.252805475353E+03 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962825E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END CRPIX1 = 2.096805475353E+03 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962825E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END CRPIX1 = -5.319452464737E+01 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962826E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END CRPIX1 = -2.200194524647E+03 / Reference pixel on this axis CRPIX2 = 1.301000018679E+03 / Reference pixel on this axis CD1_1 = -2.495992962825E-07 / Linear projection matrix CD1_2 = 3.271529545341E-05 / Linear projection matrix CD2_1 = 3.269541583457E-05 / Linear projection matrix CD2_2 = 2.499016768902E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/DEIMOS_2AMP@KECK.ini000066400000000000000000000012271417631501300212240ustar00rootroot00000000000000INSTRUMENT=DEIMOS_2AMP@KECK INSTSHORT=DEIMOS NCHIPS=4 # Geographic location OBSLAT=19.82 OBSLONG=-155.47 # Plate scale PIXSCALE=0.1185 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANY1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANY2=([1]=0 [2]=0 [3]=0 [4]=0) CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2601 [2]=2601 [3]=2601 [4]=2601) REFPIXX=([1]=4253 [2]=2097 [3]=-53 [4]=-2200) REFPIXY=([1]=1301 [2]=1301 [3]=1301 [4]=1301) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/DEIMOS_2AMP@KECK_1.reg000066400000000000000000000002361417631501300214410ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(49.934348,2501.2712,2069.7633,2498.4781,2071.8344,209.61941,849.2902,224.46813,49.934348,989.17697) THELI-3.1.3/config/instruments/DEIMOS_2AMP@KECK_2.reg000066400000000000000000000004261417631501300214430ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(20.011505,2507.9837,2069.7633,2508.1743,2069.7633,767.71016,1524.3532,709.53308,1284.3728,629.53961,970.1371,542.89453,673.37872,520.45062,453.92713,478.05657,351.68265,403.24353,266.89453,263.59252,22.505273,266.08629) THELI-3.1.3/config/instruments/DEIMOS_2AMP@KECK_3.reg000066400000000000000000000007301417631501300214420ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(17.517737,2520.4525,44.134902,2518.5808,45.952936,2462.2218,113.22018,2464.6459,116.25023,2522.2169,540.01631,2538.5979,1426.3453,2541.212,1430.5874,2458.1885,1520.883,2458.1885,1518.459,2540.606,2084.3075,2536.6568,2069.7633,107.76398,1769.9106,127.95147,1740.7114,156.3605,1611.5243,375.43007,1502.5368,519.85158,1303.7651,582.87675,1321.9743,580.8373,856.71456,667.4548,364.23216,754.07231,17.517737,774.81496) THELI-3.1.3/config/instruments/DEIMOS_2AMP@KECK_4.reg000066400000000000000000000003051417631501300214410ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(17.517737,2560.3528,1946.137,2551.8071,1946.137,1383.4175,1778.8779,1225.8546,1810.3905,1133.7409,768.05126,113.21808,17.517737,116.46021) THELI-3.1.3/config/instruments/Direct_2k_DUPONT@LCO.ini000066400000000000000000000014071417631501300222640ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=Direct_2k_DUPONT@LCO INSTSHORT=Direct # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.0 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.2602 GAIN=1.54 # Overscan regions. OVSCANX1=([1]=2060) OVSCANX2=([1]=2160) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=2) CUTY=([1]=2) SIZEX=([1]=2046) SIZEY=([1]=2046) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/Direct_4k_SWOPE@LCO.ahead000066400000000000000000000036201417631501300224340ustar00rootroot00000000000000CRPIX1 = 2.020428803645E+03 / Reference pixel on this axis CRPIX2 = 2.152673858426E+03 / Reference pixel on this axis CD1_1 = 7.012123991180E-07 / Linear projection matrix CD1_2 = -1.209520915420E-04 / Linear projection matrix CD2_1 = -1.209704448451E-04 / Linear projection matrix CD2_2 = -8.442558765812E-07 / Linear projection matrix END CRPIX1 = 2.078420173968E+03 / Reference pixel on this axis CRPIX2 = 2.153311344740E+03 / Reference pixel on this axis CD1_1 = -5.940918246501E-07 / Linear projection matrix CD1_2 = -1.209743471834E-04 / Linear projection matrix CD2_1 = 1.210208065528E-04 / Linear projection matrix CD2_2 = -9.487671484817E-07 / Linear projection matrix END CRPIX1 = 2.078549503364E+03 / Reference pixel on this axis CRPIX2 = 1.961028768148E+03 / Reference pixel on this axis CD1_1 = -6.886008675937E-07 / Linear projection matrix CD1_2 = 1.210376622219E-04 / Linear projection matrix CD2_1 = 1.210350154318E-04 / Linear projection matrix CD2_2 = 8.526479849956E-07 / Linear projection matrix END CRPIX1 = 2.020041032965E+03 / Reference pixel on this axis CRPIX2 = 1.960462135460E+03 / Reference pixel on this axis CD1_1 = 6.493824519902E-07 / Linear projection matrix CD1_2 = 1.210944536310E-04 / Linear projection matrix CD2_1 = -1.210122745093E-04 / Linear projection matrix CD2_2 = 9.077182419293E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/Direct_4k_SWOPE@LCO.ini000066400000000000000000000017151417631501300221540ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=Direct_4k_SWOPE@LCO INSTSHORT=Direct # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-29.0 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.435 GAIN=1.04 # Overscan regions. OVSCANX1=([1]=2049 [2]=2049 [3]=2049 [4]=2049) OVSCANX2=([1]=2176 [2]=2176 [3]=2176 [4]=2176) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=2 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2055 [2]=2048 [3]=2048 [4]=2048) # Reference pixels for each chip. REFPIXX=([1]=2045 [2]=2053 [3]=2055 [4]=2045) REFPIXY=([1]=2059 [2]=2057 [3]=2056 [4]=2056) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/EFOSC2@ESO3.6m.ini000066400000000000000000000013571417631501300207270ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=EFOSC2@ESO3.6m INSTSHORT=EFOSC2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.157 GAIN=1.1 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2060) SIZEY=([1]=2060) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) TYPE=OPT THELI-3.1.3/config/instruments/EFOSC2@ESO3.6m_1.reg000066400000000000000000000020711417631501300211370ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(48,1976,110,2026,155.,2030,155.,1908,159.,1909.,159.,2027.,257.,2029.,261.,2012,267.,2012,267.,2029.,361.,2030,361.,229.,365.,229.,365.,2031.,971.,2030,971.,1131.,598,1130,610,1110,626,1111.,627.,1123.5,709.,1123.5,719.,1120.5,731.,1123.,811.5,1123.,821.,1118.5,832.5,1123.,915.5,1122,919.5,1118,928,1119.,935.5,1123.,971.,1123.,971.,833.,973.,833.,973.,1123.,1014,1124,1021.,1117.5,1029.5,1118.5,1032,1123.,1116,1123.,1120.5,1119.5,1131.5,1119.5,1135.,1123.,1215.,1126,1215.5,1121.,1228.5,1121.,1236.5,1129.5,1219.,1129.,1215.,1126,1135.,1123.,1134,1129.5,1040,1131.,973.,1131.,973.,2030,1291.,2026,1291.,339.,1293.,339.,1293.,2026,1485.,2026,1485.,1637.,1487.,1637.,1487.,2026,1732,2024,1870,1999.,1871.,1688,1869.,1652,1867.,1593.,1867.,1557.,1856,1555.,1853.,1526,1863.5,1520,1875.,1519.,1876.5,1524.5,1872,1530,1871.,1642,1871.,1683.,1870,1999.,1882,2000,1952,1952,1988,1900,2014,1806,1996,1758,1996,1688,2016,1632,2018,8,18.1714,4.17136,10,500,63.,499.,62,531.,12,533.,10,1276,20,1306,28,1610,28,1864) THELI-3.1.3/config/instruments/EFOSC2@NTT.ini000066400000000000000000000013531417631501300203360ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=EFOSC2@NTT INSTSHORT=EFOSC2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.120 GAIN=1.1 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2060) SIZEY=([1]=2060) # Reference pixels for each chip. REFPIXX=([1]=1030) REFPIXY=([1]=1030) TYPE=OPT THELI-3.1.3/config/instruments/EFOSC2@NTT_1.reg000066400000000000000000000020711417631501300205520ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(48,1976,110,2026,155.,2030,155.,1908,159.,1909.,159.,2027.,257.,2029.,261.,2012,267.,2012,267.,2029.,361.,2030,361.,229.,365.,229.,365.,2031.,971.,2030,971.,1131.,598,1130,610,1110,626,1111.,627.,1123.5,709.,1123.5,719.,1120.5,731.,1123.,811.5,1123.,821.,1118.5,832.5,1123.,915.5,1122,919.5,1118,928,1119.,935.5,1123.,971.,1123.,971.,833.,973.,833.,973.,1123.,1014,1124,1021.,1117.5,1029.5,1118.5,1032,1123.,1116,1123.,1120.5,1119.5,1131.5,1119.5,1135.,1123.,1215.,1126,1215.5,1121.,1228.5,1121.,1236.5,1129.5,1219.,1129.,1215.,1126,1135.,1123.,1134,1129.5,1040,1131.,973.,1131.,973.,2030,1291.,2026,1291.,339.,1293.,339.,1293.,2026,1485.,2026,1485.,1637.,1487.,1637.,1487.,2026,1732,2024,1870,1999.,1871.,1688,1869.,1652,1867.,1593.,1867.,1557.,1856,1555.,1853.,1526,1863.5,1520,1875.,1519.,1876.5,1524.5,1872,1530,1871.,1642,1871.,1683.,1870,1999.,1882,2000,1952,1952,1988,1900,2014,1806,1996,1758,1996,1688,2016,1632,2018,8,18.1714,4.17136,10,500,63.,499.,62,531.,12,533.,10,1276,20,1306,28,1610,28,1864) THELI-3.1.3/config/instruments/EFOSC2_2x2@ESO3.6m.ini000066400000000000000000000013611417631501300214150ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=EFOSC2_2x2@ESO3.6m INSTSHORT=EFOSC2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.314 GAIN=1.1 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1030) SIZEY=([1]=1030) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=OPT THELI-3.1.3/config/instruments/EFOSC2_2x2@ESO3.6m_1.reg000066400000000000000000000020711417631501300216320ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(24,988,55,1013,77.5,1015,77.5,954,79.5,954.5,79.5,1013.5,128.5,1014.5,130.5,1006,133.5,1006,133.5,1014.5,180.5,1015,180.5,114.5,182.5,114.5,182.5,1015.5,485.5,1015,485.5,565.5,299,565,305,555,313,555.5,313.5,561.75,354.5,561.75,359.5,560.25,365.5,561.5,405.75,561.5,410.5,559.25,416.25,561.5,457.75,561,459.75,559,464,559.5,467.75,561.5,485.5,561.5,485.5,416.5,486.5,416.5,486.5,561.5,507,562,510.5,558.75,514.75,559.25,516,561.5,558,561.5,560.25,559.75,565.75,559.75,567.5,561.5,607.5,563,607.75,560.5,614.25,560.5,618.25,564.75,609.5,564.5,607.5,563,567.5,561.5,567,564.75,520,565.5,486.5,565.5,486.5,1015,645.5,1013,645.5,169.5,646.5,169.5,646.5,1013,742.5,1013,742.5,818.5,743.5,818.5,743.5,1013,866,1012,935,999.5,935.5,844,934.5,826,933.5,796.5,933.5,778.5,928,777.5,926.5,763,931.75,760,937.5,759.5,938.25,762.25,936,765,935.5,821,935.5,841.5,935,999.5,941,1000,976,976,994,950,1007,903,998,879,998,844,1008,816,1009,4,9.0856805,2.0856805,5,250,31.5,249.5,31,265.5,6,266.5,5,638,10,653,14,805,14,932) THELI-3.1.3/config/instruments/EFOSC2_2x2@NTT.ini000066400000000000000000000013551417631501300210330ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=EFOSC2_2x2@NTT INSTSHORT=EFOSC2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.240 GAIN=1.1 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1030) SIZEY=([1]=1030) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=OPT THELI-3.1.3/config/instruments/EFOSC2_2x2@NTT_1.reg000066400000000000000000000020711417631501300212450ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(24,988,55,1013,77.5,1015,77.5,954,79.5,954.5,79.5,1013.5,128.5,1014.5,130.5,1006,133.5,1006,133.5,1014.5,180.5,1015,180.5,114.5,182.5,114.5,182.5,1015.5,485.5,1015,485.5,565.5,299,565,305,555,313,555.5,313.5,561.75,354.5,561.75,359.5,560.25,365.5,561.5,405.75,561.5,410.5,559.25,416.25,561.5,457.75,561,459.75,559,464,559.5,467.75,561.5,485.5,561.5,485.5,416.5,486.5,416.5,486.5,561.5,507,562,510.5,558.75,514.75,559.25,516,561.5,558,561.5,560.25,559.75,565.75,559.75,567.5,561.5,607.5,563,607.75,560.5,614.25,560.5,618.25,564.75,609.5,564.5,607.5,563,567.5,561.5,567,564.75,520,565.5,486.5,565.5,486.5,1015,645.5,1013,645.5,169.5,646.5,169.5,646.5,1013,742.5,1013,742.5,818.5,743.5,818.5,743.5,1013,866,1012,935,999.5,935.5,844,934.5,826,933.5,796.5,933.5,778.5,928,777.5,926.5,763,931.75,760,937.5,759.5,938.25,762.25,936,765,935.5,821,935.5,841.5,935,999.5,941,1000,976,976,994,950,1007,903,998,879,998,844,1008,816,1009,4,9.0856805,2.0856805,5,250,31.5,249.5,31,265.5,6,266.5,5,638,10,653,14,805,14,932) THELI-3.1.3/config/instruments/EMIR@GTC.ini000066400000000000000000000013641417631501300201230ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=EMIR@GTC INSTSHORT=EMIR # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.2 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=3) CUTY=([1]=2) SIZEX=([1]=2042) SIZEY=([1]=2044) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) # Camera type TYPE=NIR THELI-3.1.3/config/instruments/EMMI_BIMG@NTT.ini000066400000000000000000000013621417631501300207420ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=EMMI_BIMG@NTT INSTSHORT=EMMI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.362 GAIN=2.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=51) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=OPT THELI-3.1.3/config/instruments/EMMI_RILD@NTT.ahead000066400000000000000000000017221417631501300212410ustar00rootroot00000000000000CRPIX1 = 9.181524650654E+02 / Reference pixel on this axis CRPIX2 = 8.932217465279E+02 / Reference pixel on this axis CD1_1 = -9.304190543169E-05 / Linear projection matrix CD1_2 = 1.161879431928E-06 / Linear projection matrix CD2_1 = 1.187323140017E-06 / Linear projection matrix CD2_2 = 9.301465684099E-05 / Linear projection matrix END CRPIX1 = -1.207872400193E+02 / Reference pixel on this axis CRPIX2 = 8.818937801206E+02 / Reference pixel on this axis CD1_1 = -9.299675894145E-05 / Linear projection matrix CD1_2 = 1.157736503334E-06 / Linear projection matrix CD2_1 = 1.197253908262E-06 / Linear projection matrix CD2_2 = 9.295409052405E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/EMMI_RILD@NTT.ini000066400000000000000000000014651417631501300207620ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=EMMI_RILD@NTT INSTSHORT=EMMI # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.3346 GAIN=2.0 # Overscan regions. OVSCANX1=([1]=3 [2]=3) OVSCANX2=([1]=7 [2]=7) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=10 [2]=10) CUTY=([1]=165 [2]=177) SIZEX=([1]=1019 [2]=574) SIZEY=([1]=1774 [2]=1774) # Reference pixels for each chip. REFPIXX=([1]=500 [2]=-540) REFPIXY=([1]=1503 [2]=1492) TYPE=OPT THELI-3.1.3/config/instruments/EMMI_RILD@NTT_1.reg000066400000000000000000000006311417631501300211720ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: EMMI.2007-01-21T00:11:23.840_1.fits # Sense: in # Combine: and global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 physical polygon(275,1940,1028.5,1954,1027.5,167,311,164,211,184,107,248,51.5,329,14.5,439,11,1596,15,1728,31,1776,81.5,1845,147,1896,208.5,1924) THELI-3.1.3/config/instruments/EMMI_RILD@NTT_2.reg000066400000000000000000000005451417631501300211770ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: /home/mischa/EMMI/RILD/FLAT_V/EMMI.2007-01-21T00:11:23.840_2.fits # Sense: in # Combine: and global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 physical polygon(10.625626,1952.8744,577.5,1961,594,184,10,176) THELI-3.1.3/config/instruments/ENZIAN_CAS@HOLI_1M.ini000066400000000000000000000013701417631501300215110ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ENZIAN_CAS@HOLI_1M INSTSHORT=ENZIAN # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=50.16 OBSLONG=6.85 # Pixel scale in arcsec PIXSCALE=0.1778 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=5) CUTY=([1]=50) SIZEX=([1]=1022) SIZEY=([1]=2045) # Reference pixels for each chip. REFPIXX=([1]=1180) REFPIXY=([1]=450) TYPE=OPT THELI-3.1.3/config/instruments/ESI@KECK.ini000066400000000000000000000006721417631501300201100ustar00rootroot00000000000000INSTRUMENT=ESI@KECK INSTSHORT=ESI NCHIPS=1 # Geographic location OBSLAT=19.82 OBSLONG=-155.47 # Plate scale PIXSCALE=0.1542 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=1130) OVSCANX2=([1]=1260) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=210) CUTY=([1]=106) SIZEX=([1]=689) SIZEY=([1]=1280) REFPIXX=([1]=340) REFPIXY=([1]=640) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/FL03_LCOGT@CTIO.ini000066400000000000000000000013651417631501300211050ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FL03_LCOGT@CTIO INSTSHORT=FL03 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.3897 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=46) CUTY=([1]=64) SIZEX=([1]=4018) SIZEY=([1]=3974) # Reference pixels for each chip. REFPIXX=([1]=2009) REFPIXY=([1]=1987) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/FL03_LCOGT@CTIO_1.reg000066400000000000000000000005651417631501300213240ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(91.188802,2929.2148,123.19661,3900.1185,256.5625,3964.1341,3302.6393,3980.138,3985.4727,3921.457,4006.8112,2950.5534,4054.8229,2742.5026,4060.1576,1366.1667,3974.8034,1067.4271,3974.8034,139.20052,2139.6888,117.86198,213.88542,101.85807,149.86979,219.22005,139.20052,1264.8086,14,1340,10,2736) THELI-3.1.3/config/instruments/FL04_LCOGT@CTIO.ini000066400000000000000000000014471417631501300211070ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FL04_LCOGT@CTIO INSTSHORT=FL04 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.387 # Already multiplied out, i.e. we have electrons/s GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=46) CUTY=([1]=64) SIZEX=([1]=4018) SIZEY=([1]=3974) # Reference pixels for each chip. REFPIXX=([1]=2009) REFPIXY=([1]=1987) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/FL04_LCOGT@CTIO_1.reg000066400000000000000000000004241417631501300213170ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(202,3592,302,3684,467,3733,1870,3760,3599,3737,3730,3644,3790,3500,3865,2988,3953,2812,4015,2741,4004,1373,3956,1253,3856,981,3788,501,3556,281,2132,213,272,213,188,365,66,1268,14,1340,10,2736) THELI-3.1.3/config/instruments/FLAMINGOS2@GEMINI.ini000066400000000000000000000013461417631501300213230ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FLAMINGOS2@GEMINI INSTSHORT=F2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.1788 GAIN=4.4 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1028) REFPIXY=([1]=1028) TYPE=NIR THELI-3.1.3/config/instruments/FLAMINGOS2@GEMINI.reg000066400000000000000000000001071417631501300213130ustar00rootroot00000000000000# Region file format: DS9 version 4.1 circle(1052.3493,1059.2536,1008) THELI-3.1.3/config/instruments/FLI-PL16801@WISE.ini000066400000000000000000000013431417631501300210410ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FLI-PL16801@WISE INSTSHORT=FLI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=30.60 OBSLONG=34.76 # Pixel scale in arcsec PIXSCALE=0.84 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=4096) SIZEY=([1]=4096) # Reference pixels for each chip. REFPIXX=([1]=2048) REFPIXY=([1]=2048) TYPE=OPT THELI-3.1.3/config/instruments/FORS1_199904-200703@VLT.ini000066400000000000000000000013701417631501300216360ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FORS1_199904-200703@VLT INSTSHORT=FORS1 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.20 GAIN=1.48 # Overscan regions. OVSCANX1=([1]=1) OVSCANX2=([1]=16) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=18) CUTY=([1]=1) SIZEX=([1]=2046) SIZEY=([1]=2047) # Reference pixels for each chip. REFPIXX=([1]=1028) REFPIXY=([1]=1014) TYPE=OPT THELI-3.1.3/config/instruments/FORS1_E2V_2x2@VLT.ahead000066400000000000000000000017221417631501300217010ustar00rootroot00000000000000CRPIX1 = 8.316765760E+02 / Reference pixel on this axis CRPIX2 = 3.995501736E+01 / Reference pixel on this axis CD1_1 = -6.979125586E-05 / Linear projection matrix CD1_2 = -1.003785146E-07 / Linear projection matrix CD2_1 = -9.820255077E-08 / Linear projection matrix CD2_2 = 6.976337894E-05 / Linear projection matrix END CRPIX1 = 8.312946884E+02 / Reference pixel on this axis CRPIX2 = 7.723696641E+02 / Reference pixel on this axis CD1_1 = -6.977758754E-05 / Linear projection matrix CD1_2 = -9.577281809E-08 / Linear projection matrix CD2_1 = -1.272560280E-07 / Linear projection matrix CD2_2 = 6.970701968E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/FORS1_E2V_2x2@VLT.ini000066400000000000000000000014661417631501300214230ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FORS1_E2V_2x2@VLT INSTSHORT=FORS1 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.252 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=190 [2]=190) CUTY=([1]=7 [2]=345) SIZEX=([1]=1660 [2]=1660) SIZEY=([1]=945 [2]=680) # Reference pixels for each chip. REFPIXX=([1]=1024 [2]=1024) REFPIXY=([1]=124 [2]=1162) TYPE=OPT THELI-3.1.3/config/instruments/FORS2_200004-200203@VLT.ini000066400000000000000000000013711417631501300216010ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FORS2_200004-200203@VLT INSTSHORT=FORS2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.201 GAIN=1.96 # Overscan regions. OVSCANX1=([1]=1) OVSCANX2=([1]=16) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=18) CUTY=([1]=1) SIZEX=([1]=2046) SIZEY=([1]=2047) # Reference pixels for each chip. REFPIXX=([1]=1028) REFPIXY=([1]=1014) TYPE=OPT THELI-3.1.3/config/instruments/FORS2_E2V_2x2@VLT.ahead000066400000000000000000000013201417631501300216740ustar00rootroot00000000000000CRPIX1 = 8.365992138238E+02 / Reference pixel on this axis CRPIX2 = 4.091828242874E+01 / Reference pixel on this axis CD1_1 = -6.978114905218E-05 / Linear projection matrix CD1_2 = 1.241192099589E-07 / Linear projection matrix CD2_1 = 1.266400324866E-07 / Linear projection matrix CD2_2 = 6.976123849142E-05 / Linear projection matrix END CRPIX1 = 8.334170952678E+02 / Reference pixel on this axis CRPIX2 = 7.779178189807E+02 / Reference pixel on this axis CD1_1 = -6.976321813495E-05 / Linear projection matrix CD1_2 = 1.264772131436E-07 / Linear projection matrix CD2_1 = 1.367099912247E-07 / Linear projection matrix CD2_2 = 6.974592668737E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/FORS2_E2V_2x2@VLT.ini000066400000000000000000000014601417631501300214160ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FORS2_E2V_2x2@VLT INSTSHORT=FORS2 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.252 GAIN=0.42 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=192 [2]=195) CUTY=([1]=7 [2]=340) SIZEX=([1]=1669 [2]=1669) SIZEY=([1]=950 [2]=685) # Reference pixels for each chip. REFPIXX=([1]=835 [2]=837) REFPIXY=([1]=53 [2]=781) TYPE=OPT THELI-3.1.3/config/instruments/FORS2_E2V_2x2@VLT_1.reg000066400000000000000000000003771417631501300216420ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and physical polygon(-15.272579,968.27258,23.272579,968.27258,23.272579,929.72742,-15.272579,929.72742) polygon(1649.7601,976.23991,1694.2399,976.23991,1694.2399,931.76009,1649.7601,931.76009) THELI-3.1.3/config/instruments/FORS2_E2V_2x2@VLT_2.reg000066400000000000000000000003771417631501300216430ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and physical polygon(-10.237832,23.237832,24.237832,23.237832,24.237832,-11.237832,-10.237832,-11.237832) polygon(1648.034,21.966031,1683.966,21.966031,1683.966,-13.966031,1648.034,-13.966031) THELI-3.1.3/config/instruments/FORS2_MIT_1x1@VLT.ini000066400000000000000000000014661417631501300214570ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FORS2_MIT_1x1@VLT INSTSHORT=FORS2 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.126 GAIN=0.8 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=390 [2]=390) CUTY=([1]=30 [2]=644) SIZEX=([1]=3320 [2]=3320) SIZEY=([1]=1884 [2]=1406) # Reference pixels for each chip. REFPIXX=([1]=1670 [2]=1675) REFPIXY=([1]=106 [2]=1561) TYPE=OPT THELI-3.1.3/config/instruments/FORS2_MIT_2x2@VLT.ahead000066400000000000000000000016301417631501300217350ustar00rootroot00000000000000CRPIX1 = 8.352153004225E+02 / Reference pixel on this axis CRPIX2 = -3.957925377653E+01 / Reference pixel on this axis CD1_1 = -7.003560930416E-05 / Linear projection matrix CD1_2 = -5.847121661044E-08 / Linear projection matrix CD2_1 = -8.370354930209E-08 / Linear projection matrix CD2_2 = 7.002180117581E-05 / Linear projection matrix END CRPIX1 = 8.374316742864E+02 / Reference pixel on this axis CRPIX2 = 1.001274426025E+03 / Reference pixel on this axis CD1_1 = -7.001621218463E-05 / Linear projection matrix CD1_2 = 2.970248108139E-08 / Linear projection matrix CD2_1 = 1.642786229325E-08 / Linear projection matrix CD2_2 = 6.995944449136E-05 / Linear projection matrix THELI-3.1.3/config/instruments/FORS2_MIT_2x2@VLT.ini000066400000000000000000000014531417631501300214550ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FORS2_MIT_2x2@VLT INSTSHORT=FORS2 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.252 GAIN=0.8 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=190 [2]=190) CUTY=([1]=7 [2]=320) SIZEX=([1]=1671 [2]=1671) SIZEY=([1]=955 [2]=710) # Reference pixels for each chip. REFPIXX=([1]=835 [2]=837) REFPIXY=([1]=57 [2]=784) TYPE=OPT THELI-3.1.3/config/instruments/FourStar@LCO.ahead000066400000000000000000000036441417631501300214220ustar00rootroot00000000000000CRPIX1 = -7.113976232215E+01 / Reference pixel on this axis CRPIX2 = -6.807405204649E+01 / Reference pixel on this axis CD1_1 = 4.457639801000E-05 / Linear projection matrix CD1_2 = 1.417245836801E-07 / Linear projection matrix CD2_1 = 2.019670000025E-08 / Linear projection matrix CD2_2 = -4.457592725997E-05 / Linear projection matrix END CRPIX1 = -7.030973688651E+01 / Reference pixel on this axis CRPIX2 = 2.122066108471E+03 / Reference pixel on this axis CD1_1 = 4.455036603995E-05 / Linear projection matrix CD1_2 = 1.282707937627E-07 / Linear projection matrix CD2_1 = 2.061400552745E-07 / Linear projection matrix CD2_2 = -4.449656759997E-05 / Linear projection matrix END CRPIX1 = 2.115010149085E+03 / Reference pixel on this axis CRPIX2 = 2.121066095909E+03 / Reference pixel on this axis CD1_1 = 4.449995418997E-05 / Linear projection matrix CD1_2 = 2.128944256620E-07 / Linear projection matrix CD2_1 = 1.306023924635E-07 / Linear projection matrix CD2_2 = -4.449307031995E-05 / Linear projection matrix END CRPIX1 = 2.123010387020E+03 / Reference pixel on this axis CRPIX2 = -7.186400794208E+01 / Reference pixel on this axis CD1_1 = 4.453221014997E-05 / Linear projection matrix CD1_2 = 4.770697959835E-08 / Linear projection matrix CD2_1 = 1.570097283706E-07 / Linear projection matrix CD2_2 = -4.456771567999E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/FourStar@LCO.ini000066400000000000000000000016451417631501300211360ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=FourStar@LCO INSTSHORT=FourStar # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.159 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048) # Reference pixels for each chip. REFPIXX=([1]=-71 [2]=-70 [3]=2115 [4]=2123) REFPIXY=([1]=-68 [2]=2122 [3]=2121 [4]=-71) TYPE=NIR THELI-3.1.3/config/instruments/FourStar@LCO_1.reg000066400000000000000000000007631417631501300213540ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(7.8893401,2017.8911,1882.0437,2011.0162,1996.4548,1888.2843,2002.3964,836.49346,1904.4968,836.62348,1902.5213,849.22627,1893.7345,862.36599,1872.4124,870.6868,1851.6104,863.40609,1844.8497,848.32462,1842.2495,837.40355,1846.4099,824.40228,1852.6505,813.48122,1864.0916,807.76066,1880.2132,807.24061,1894.2546,811.92107,1903.0954,823.36218,1904.4968,836.49346,2002.3964,836.36345,2008.7576,7.9591907,7.9591907,7.9591907) THELI-3.1.3/config/instruments/FourStar@LCO_2.reg000066400000000000000000000002631417631501300213500ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(8.0510152,2040.3348,2012.6708,2041.8949,2006.8558,165.87614,1884.1239,38.983756,8.1725888,38.26802) THELI-3.1.3/config/instruments/FourStar@LCO_3.reg000066400000000000000000000002631417631501300213510ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(31.176396,2042.4487,2043.0797,2042.0396,2042.7459,38.11269,228.28223,47.304569,41.063959,234.52284) THELI-3.1.3/config/instruments/FourStar@LCO_4.reg000066400000000000000000000006621417631501300213550ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(330.37563,1999.3914,2035.3437,2019.4449,2035.8637,1772.9409,1999.9802,1750.0586,1999.9802,1723.016,2017.6619,1728.2165,2037.4239,1749.0185,2036.8102,1601.6746,2006.6472,1497.6645,1932.8,1398.8548,1906.7975,1333.3284,1938.0005,1209.5563,1999.3665,1123.2279,2020.5391,867.30305,2034.8236,11.556345,107.41447,16.425888,110.91421,1649.9173,173.3203,1872.499) THELI-3.1.3/config/instruments/GMOS-N-EEV-3ports@GEMINI.ahead000066400000000000000000000026731417631501300230160ustar00rootroot00000000000000CRPIX1 = 1.581953468963E+03 / Reference pixel on this axis CRPIX2 = 1.140831725219E+03 / Reference pixel on this axis CD1_1 = 4.035307293253E-05 / Linear projection matrix CD1_2 = -4.642062404799E-08 / Linear projection matrix CD2_1 = 1.737724509903E-07 / Linear projection matrix CD2_2 = 4.046284590482E-05 / Linear projection matrix END CRPIX1 = 5.368663987294E+02 / Reference pixel on this axis CRPIX2 = 1.142668287911E+03 / Reference pixel on this axis CD1_1 = 4.044719131630E-05 / Linear projection matrix CD1_2 = -5.152092930366E-08 / Linear projection matrix CD2_1 = 1.558634980210E-08 / Linear projection matrix CD2_2 = 4.047793088441E-05 / Linear projection matrix END CRPIX1 = -5.543743758976E+02 / Reference pixel on this axis CRPIX2 = 1.136115034502E+03 / Reference pixel on this axis CD1_1 = 3.978428606258E-05 / Linear projection matrix CD1_2 = -6.519145514865E-09 / Linear projection matrix CD2_1 = -2.794039557355E-07 / Linear projection matrix CD2_2 = 4.049334855478E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/GMOS-N-EEV-3ports@GEMINI.ini000066400000000000000000000015731417631501300225310ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-N-EEV-3ports@GEMINI INSTSHORT=GMOSN # Number of chips NCHIPS=3 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.1454 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=5 [2]=5 [3]=1035) OVSCANX2=([1]=25 [2]=25 [3]=1055) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=1056 [2]=1056 [3]=1056) SIZEY=([1]=2304 [2]=2304 [3]=2304) # Reference pixels for each chip. REFPIXX=([1]=1589 [2]=566 [3]=-534) REFPIXY=([1]=1152 [2]=1152 [3]=1152) TYPE=OPT THELI-3.1.3/config/instruments/GMOS-N-EEV-3ports@GEMINI_1.reg000066400000000000000000000003241417631501300227400ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: /home/mischa/daniela/flat/N20091004S0154_1.fits # Sense: in # Combine: and physical polygon(435,2046,691,2290,1053.5326,2296.5139,1053,12,1027,12,705,14,439,270) THELI-3.1.3/config/instruments/GMOS-N-EEV-3ports@GEMINI_2.reg000066400000000000000000000004061417631501300227420ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: /home/mischa/daniela/flat/N20091004S0154_2.fits # Sense: in # Combine: and physical polygon(31.529742,2277.0194,1056.5276,2276.0193,1054.5342,31.028997,540.49108,31.990087,467.51696,31.99903,33.518298,25.019424) THELI-3.1.3/config/instruments/GMOS-N-EEV-3ports@GEMINI_3.reg000066400000000000000000000004311417631501300227410ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: /home/mischa/daniela/flat/N20091004S0154_3.fits # Sense: in # Combine: and physical polygon(4.9385067,1203.9834,1.9666801,2284.9947,340.00964,2284.9861,612.02943,2024.9863,608.0217,289.0142,363.98311,49.012979,2.0305837,32.972063) THELI-3.1.3/config/instruments/GMOS-N-EEV-6ports@GEMINI.ahead000066400000000000000000000026731417631501300230210ustar00rootroot00000000000000CRPIX1 = 1.557212432002E+03 / Reference pixel on this axis CRPIX2 = 1.148967078145E+03 / Reference pixel on this axis CD1_1 = 4.041118494664E-05 / Linear projection matrix CD1_2 = -5.644219495033E-09 / Linear projection matrix CD2_1 = 1.520279488787E-08 / Linear projection matrix CD2_2 = 4.048438034899E-05 / Linear projection matrix END CRPIX1 = 5.117615202459E+02 / Reference pixel on this axis CRPIX2 = 1.148853178798E+03 / Reference pixel on this axis CD1_1 = 4.055136805886E-05 / Linear projection matrix CD1_2 = -1.065522211154E-08 / Linear projection matrix CD2_1 = -2.769058672112E-09 / Linear projection matrix CD2_2 = 4.051363861521E-05 / Linear projection matrix END CRPIX1 = -5.336368450035E+02 / Reference pixel on this axis CRPIX2 = 1.147888295605E+03 / Reference pixel on this axis CD1_1 = 4.043127392569E-05 / Linear projection matrix CD1_2 = -7.568253196180E-09 / Linear projection matrix CD2_1 = 5.677470836821E-09 / Linear projection matrix CD2_2 = 4.048127674381E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/GMOS-N-EEV-6ports@GEMINI.ini000066400000000000000000000015631417631501300225330ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-N-EEV-6ports@GEMINI INSTSHORT=GMOSN # Number of chips NCHIPS=3 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.1454 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0) OVSCANX2=([1]=0 [2]=0 [3]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=1024 [2]=1024 [3]=1024) SIZEY=([1]=2304 [2]=2304 [3]=2304) # Reference pixels for each chip. REFPIXX=([1]=1589 [2]=566 [3]=-534) REFPIXY=([1]=1152 [2]=1152 [3]=1152) TYPE=OPT THELI-3.1.3/config/instruments/GMOS-N-EEV-6ports@GEMINI_1.reg000066400000000000000000000002041417631501300227400ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(418,2068,632,2296,1020,2300,1017,7,649,9,421,241) THELI-3.1.3/config/instruments/GMOS-N-EEV-6ports@GEMINI_2.reg000066400000000000000000000001611417631501300227430ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(6,2274,1020,2274,1019,25,5,25) THELI-3.1.3/config/instruments/GMOS-N-EEV-6ports@GEMINI_3.reg000066400000000000000000000002671417631501300227530ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(4.9385067,1203.9834,1.9666801,2284.9947,340.00964,2284.9861,612.02943,2024.9863,613,263,365,21,3,17) THELI-3.1.3/config/instruments/GMOS-N-HAM@GEMINI.ahead000066400000000000000000000026731417631501300215540ustar00rootroot00000000000000CRPIX1 = 1.571423231870E+03 / Reference pixel on this axis CRPIX2 = 1.057110657960E+03 / Reference pixel on this axis CD1_1 = -4.482886376208E-05 / Linear projection matrix CD1_2 = -1.657254343634E-08 / Linear projection matrix CD2_1 = 4.666745163270E-08 / Linear projection matrix CD2_2 = -4.489061476770E-05 / Linear projection matrix END CRPIX1 = 5.120873496097E+02 / Reference pixel on this axis CRPIX2 = 1.056445308302E+03 / Reference pixel on this axis CD1_1 = -4.491296727417E-05 / Linear projection matrix CD1_2 = -1.489485161232E-08 / Linear projection matrix CD2_1 = 1.480005185242E-08 / Linear projection matrix CD2_2 = -4.490073862015E-05 / Linear projection matrix END CRPIX1 = -5.470744794196E+02 / Reference pixel on this axis CRPIX2 = 1.055232753759E+03 / Reference pixel on this axis CD1_1 = -4.478378495645E-05 / Linear projection matrix CD1_2 = -1.956169877253E-08 / Linear projection matrix CD2_1 = 9.172287830989E-08 / Linear projection matrix CD2_2 = -4.489046136138E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/GMOS-N-HAM@GEMINI.ini000066400000000000000000000015541417631501300212660ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-N-HAM@GEMINI INSTSHORT=GMOSN # Number of chips NCHIPS=3 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.1614 GAIN=1.4 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0) OVSCANX2=([1]=0 [2]=0 [3]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=1024 [2]=1024 [3]=1024) SIZEY=([1]=2112 [2]=2112 [3]=2112) # Reference pixels for each chip. REFPIXX=([1]=1589 [2]=544 [3]=-502) REFPIXY=([1]=1152 [2]=1152 [3]=1152) TYPE=OPT THELI-3.1.3/config/instruments/GMOS-N-HAM@GEMINI_1.reg000066400000000000000000000003041417631501300214740ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(767.11979,2076.924,1013.6365,2076.924,1013.0438,30.502083,795.14062,39.30625,555.22708,266.01354,549.21667,1867.825) THELI-3.1.3/config/instruments/GMOS-N-HAM@GEMINI_2.reg000066400000000000000000000001561417631501300215020ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(8,2105,1017,2105,1015,68,8,68) THELI-3.1.3/config/instruments/GMOS-N-HAM@GEMINI_3.reg000066400000000000000000000003331417631501300215000ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(3.5645833,2091.0802,225.86979,2095.4823,484.77813,1833.2167,491.83542,443.9375,353.16979,223.83333,159.47813,38.945833,9.8072917,32.342708) THELI-3.1.3/config/instruments/GMOS-N-HAM_1x1@GEMINI.ahead000066400000000000000000000026731417631501300222450ustar00rootroot00000000000000CRPIX1 = 3.143777545197E+03 / Reference pixel on this axis CRPIX2 = 2.113004120476E+03 / Reference pixel on this axis CD1_1 = -2.239947777345E-05 / Linear projection matrix CD1_2 = 1.299309986852E-09 / Linear projection matrix CD2_1 = 4.830702902871E-09 / Linear projection matrix CD2_2 = -2.244012856388E-05 / Linear projection matrix END CRPIX1 = 1.024500380434E+03 / Reference pixel on this axis CRPIX2 = 2.112527676147E+03 / Reference pixel on this axis CD1_1 = -2.247148116453E-05 / Linear projection matrix CD1_2 = 2.251292619909E-09 / Linear projection matrix CD2_1 = 5.717536252284E-09 / Linear projection matrix CD2_2 = -2.246214028661E-05 / Linear projection matrix END CRPIX1 = -1.093911852643E+03 / Reference pixel on this axis CRPIX2 = 2.112239622415E+03 / Reference pixel on this axis CD1_1 = -2.240863529353E-05 / Linear projection matrix CD1_2 = 1.949475851215E-09 / Linear projection matrix CD2_1 = 1.949137667719E-09 / Linear projection matrix CD2_2 = -2.244615728468E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/GMOS-N-HAM_1x1@GEMINI.ini000066400000000000000000000015611417631501300217550ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-N-HAM_1x1@GEMINI INSTSHORT=GMOSN # Number of chips NCHIPS=3 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.0807 GAIN=1.4 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0) OVSCANX2=([1]=0 [2]=0 [3]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048) SIZEY=([1]=4224 [2]=4224 [3]=4224) # Reference pixels for each chip. REFPIXX=([1]=3180 [2]=1088 [3]=-1004) REFPIXY=([1]=2304 [2]=2304 [3]=2304) TYPE=OPT THELI-3.1.3/config/instruments/GMOS-N-HAM_1x1@GEMINI_1.reg000066400000000000000000000002071417631501300221670ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(1103,474,1109,3762,1581,4210,2035,4208,2035,58,1523,58) THELI-3.1.3/config/instruments/GMOS-N-HAM_1x1@GEMINI_2.reg000066400000000000000000000001761417631501300221750ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(15.5,4211,2033.5,4209.5,2029,37,1033,29,21,33) THELI-3.1.3/config/instruments/GMOS-N-HAM_1x1@GEMINI_3.reg000066400000000000000000000002111417631501300221640ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(15,4210,474,4201,1006,3701,1003,934,683,474,275,58,15,54) THELI-3.1.3/config/instruments/GMOS-S-EEV@GEMINI.ahead000066400000000000000000000026731417631501300215730ustar00rootroot00000000000000CRPIX1 = 1.554880524324E+03 / Reference pixel on this axis CRPIX2 = 1.146395554423E+03 / Reference pixel on this axis CD1_1 = 2.839994842323E-09 / Linear projection matrix CD1_2 = 4.050496822426E-05 / Linear projection matrix CD2_1 = -4.047477102422E-05 / Linear projection matrix CD2_2 = 5.081737433250E-09 / Linear projection matrix END CRPIX1 = 5.110441404265E+02 / Reference pixel on this axis CRPIX2 = 1.146522834292E+03 / Reference pixel on this axis CD1_1 = -1.647397406879E-08 / Linear projection matrix CD1_2 = 4.053202977281E-05 / Linear projection matrix CD2_1 = -4.056039187998E-05 / Linear projection matrix CD2_2 = -1.287886134556E-08 / Linear projection matrix END CRPIX1 = -5.052861903962E+02 / Reference pixel on this axis CRPIX2 = 1.145025664243E+03 / Reference pixel on this axis CD1_1 = -3.345690092834E-08 / Linear projection matrix CD1_2 = 4.050897083095E-05 / Linear projection matrix CD2_1 = -4.032599617332E-05 / Linear projection matrix CD2_2 = 5.072091454745E-09 / Linear projection matrix END THELI-3.1.3/config/instruments/GMOS-S-EEV@GEMINI.ahead_nocd000066400000000000000000000007731417631501300225750ustar00rootroot00000000000000CRPIX1 = 1.245212681010E+03 / Reference pixel on this axis CRPIX2 = 1.159309719904E+03 / Reference pixel on this axis END CRPIX1 = 6.348696286973E+02 / Reference pixel on this axis CRPIX2 = 1.151922917841E+03 / Reference pixel on this axis END CRPIX1 = -4.173287662244E+02 / Reference pixel on this axis CRPIX2 = 1.154639809303E+03 / Reference pixel on this axis END THELI-3.1.3/config/instruments/GMOS-S-EEV@GEMINI.ini000066400000000000000000000016651417631501300213100ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-S-EEV@GEMINI INSTSHORT=GMOSS # Number of chips NCHIPS=3 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.1454 GAIN=2.19 # Overscan regions. OVSCANX1=([1]=1040 [2]=1040 [3]=3) OVSCANX2=([1]=1050 [2]=1050 [3]=15) #OVSCANX1=([1]=0 [2]=0 [3]=0) #OVSCANX2=([1]=0 [2]=0 [3]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=1025 [2]=1025 [3]=1056) SIZEY=([1]=2304 [2]=2304 [3]=2304) # Reference pixels for each chip. REFPIXX=([1]=1589 [2]=544 [3]=-502) REFPIXY=([1]=1152 [2]=1152 [3]=1152) TYPE=OPT THELI-3.1.3/config/instruments/GMOS-S-EEV@GEMINI_1.reg000066400000000000000000000002621417631501300215160ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: S20120226S0032_1.fits # Sense: in # Combine: and physical polygon(441,2070,680.5,2303.5,1024.5,2304.5,1024.5,61,679,61,431,315) THELI-3.1.3/config/instruments/GMOS-S-EEV@GEMINI_2.reg000066400000000000000000000002631417631501300215200ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: S20120226S0032_2.fits # Sense: in # Combine: and physical polygon(1.25,2304.5,1024.5,2304.5,1024.5,76.5,519,102,437,62,1.5,61.5) THELI-3.1.3/config/instruments/GMOS-S-EEV@GEMINI_3.reg000066400000000000000000000004251417631501300215210ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Filename: S20120205S0030_3.fits # Sense: in # Combine: and physical polygon(35.892864,1206.0048,32.967671,2295.0003,32.971722,2304.0078,415.98066,2304.0405,651.93811,2060.0255,647.88995,312.98771,371.89788,57.023685,33.979755,58.956831) THELI-3.1.3/config/instruments/GMOS-S-HAM@GEMINI.ahead000066400000000000000000000026731417631501300215610ustar00rootroot00000000000000CRPIX1 = 1.585813073679E+03 / Reference pixel on this axis CRPIX2 = 1.056751207756E+03 / Reference pixel on this axis CD1_1 = -4.211095327008E-05 / Linear projection matrix CD1_2 = -1.092314780300E-05 / Linear projection matrix CD2_1 = 1.053909734492E-05 / Linear projection matrix CD2_2 = -4.311016922294E-05 / Linear projection matrix END CRPIX1 = 5.128946367927E+02 / Reference pixel on this axis CRPIX2 = 1.057193218936E+03 / Reference pixel on this axis CD1_1 = -4.311515647276E-05 / Linear projection matrix CD1_2 = -1.079182099276E-05 / Linear projection matrix CD2_1 = 1.080961101350E-05 / Linear projection matrix CD2_2 = -4.319760755877E-05 / Linear projection matrix END CRPIX1 = -5.632786223382E+02 / Reference pixel on this axis CRPIX2 = 1.059245413212E+03 / Reference pixel on this axis CD1_1 = -4.207693383011E-05 / Linear projection matrix CD1_2 = -1.062995831038E-05 / Linear projection matrix CD2_1 = 1.034943417388E-05 / Linear projection matrix CD2_2 = -4.317330890080E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/GMOS-S-HAM@GEMINI.ini000066400000000000000000000015521417631501300212710ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-S-HAM@GEMINI INSTSHORT=GMOSS # Number of chips NCHIPS=3 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.160 GAIN=1.4 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0) OVSCANX2=([1]=0 [2]=0 [3]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=1024 [2]=1024 [3]=1024) SIZEY=([1]=2112 [2]=2112 [3]=2112) # Reference pixels for each chip. REFPIXX=([1]=1589 [2]=544 [3]=-502) REFPIXY=([1]=1152 [2]=1152 [3]=1152) TYPE=OPT THELI-3.1.3/config/instruments/GMOS-S-HAM@GEMINI_1.reg000066400000000000000000000003121417631501300215000ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(737.01429,2103.9711,1015.4857,2102.478,1017.9968,64.993443,768.98725,68.019331,531.99743,309.02477,548.01378,1916.9981) THELI-3.1.3/config/instruments/GMOS-S-HAM@GEMINI_2.reg000066400000000000000000000001621417631501300215040ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(8,2105,1017,2105,1016,84,10,84) THELI-3.1.3/config/instruments/GMOS-S-HAM@GEMINI_3.reg000066400000000000000000000002001417631501300214760ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(3,2107,329,2106,505,1915,496,313,252,85,6,85) THELI-3.1.3/config/instruments/GMOS-S-HAM_1x1@GEMINI.ahead000066400000000000000000000026731417631501300222520ustar00rootroot00000000000000CRPIX1 = 3.138830235113E+03 / Reference pixel on this axis CRPIX2 = 2.099989818964E+03 / Reference pixel on this axis CD1_1 = -1.703574085504E-05 / Linear projection matrix CD1_2 = 1.421564057474E-05 / Linear projection matrix CD2_1 = -1.415971528344E-05 / Linear projection matrix CD2_2 = -1.705261865330E-05 / Linear projection matrix END CRPIX1 = 1.024538985836E+03 / Reference pixel on this axis CRPIX2 = 2.099485469469E+03 / Reference pixel on this axis CD1_1 = -1.708297605572E-05 / Linear projection matrix CD1_2 = 1.422130571903E-05 / Linear projection matrix CD2_1 = -1.423724914082E-05 / Linear projection matrix CD2_2 = -1.707036142634E-05 / Linear projection matrix END CRPIX1 = -1.090786089701E+03 / Reference pixel on this axis CRPIX2 = 2.102205754186E+03 / Reference pixel on this axis CD1_1 = -1.697675031367E-05 / Linear projection matrix CD1_2 = 1.420206393520E-05 / Linear projection matrix CD2_1 = -1.418655326657E-05 / Linear projection matrix CD2_2 = -1.704946977655E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/GMOS-S-HAM_1x1@GEMINI.ini000066400000000000000000000015571417631501300217670ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-S-HAM_1x1@GEMINI INSTSHORT=GMOSS # Number of chips NCHIPS=3 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.08 GAIN=1.4 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0) OVSCANX2=([1]=0 [2]=0 [3]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048) SIZEY=([1]=4224 [2]=4224 [3]=4224) # Reference pixels for each chip. REFPIXX=([1]=3180 [2]=1088 [3]=-1004) REFPIXY=([1]=2304 [2]=2304 [3]=2304) TYPE=OPT THELI-3.1.3/config/instruments/GMOS-S-HAM_1x1@GEMINI_1.reg000066400000000000000000000002141417631501300221720ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(1106,637,1111,3832,1491,4210,2035,4208,2030,139,1570,139) THELI-3.1.3/config/instruments/GMOS-S-HAM_1x1@GEMINI_2.reg000066400000000000000000000002061417631501300221740ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(15.5,4211,2033.5,4209.5,2031,179.5,1047,178,19,180) THELI-3.1.3/config/instruments/GMOS-S-HAM_1x1@GEMINI_3.reg000066400000000000000000000002051417631501300221740ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(15,4210,629,4209,1007,3810,997,640,499,166,19,167) THELI-3.1.3/config/instruments/GMOS-S-HAM_4x4@GEMINI.ini000066400000000000000000000010671417631501300217710ustar00rootroot00000000000000INSTRUMENT=GMOS-S-HAM_4x4@GEMINI NCHIPS=3 # Geographic location OBSLAT=-30.24 OBSLONG=-70.74 # Plate scale PIXSCALE=0.32 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0 [2]=0 [3]=0) OVSCANX2=([1]=0 [2]=0 [3]=0) OVSCANY1=([1]=0 [2]=0 [3]=0) OVSCANY2=([1]=0 [2]=0 [3]=0) CUTX=([1]=1 [2]=1 [3]=1) CUTY=([1]=1 [2]=1 [3]=1) SIZEX=([1]=512 [2]=512 [3]=512) SIZEY=([1]=1056 [2]=1056 [3]=1056) REFPIXX=([1]=794 [2]=272 [3]=-251) REFPIXY=([1]=576 [2]=576 [3]=576) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/GMOS-S-HAM_4x4@GEMINI_1.reg000066400000000000000000000002031417631501300221760ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(283,945,385,1060,520,1059,517,50,382,50,281,153) THELI-3.1.3/config/instruments/GMOS-S-HAM_4x4@GEMINI_2.reg000066400000000000000000000002071417631501300222030ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(1.0442835,1056.9557,512.95572,1056.9557,518,69,0,69) THELI-3.1.3/config/instruments/GMOS-S-HAM_4x4@GEMINI_3.reg000066400000000000000000000002021417631501300221770ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(248,948,145,1062,-9,1061,-12,52,131,51,246,156) THELI-3.1.3/config/instruments/GMOS-S_EEV_GeMS@GEMINI.ini000066400000000000000000000014071417631501300222370ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GMOS-S_EEV_GeMS@GEMINI INSTSHORT=GMOSS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0718 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=3108) SIZEY=([1]=2304) # Reference pixels for each chip. REFPIXX=([1]=1550) REFPIXY=([1]=1152) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/GMOS-S_EEV_GeMS@GEMINI_1.reg000066400000000000000000000002101417631501300224440ustar00rootroot00000000000000# Sense: in # Combine: and physical polygon(654,2301,2458,2298,2617,2148,2511,2049,2519,909,2679,732,2201,354,927,357,426,811,427,2059) THELI-3.1.3/config/instruments/GOODMAN_1x1@SOAR.ini000066400000000000000000000013651417631501300212740ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GOODMAN_1x1@SOAR INSTSHORT=GOODMAN # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.154 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=44) CUTY=([1]=4) SIZEX=([1]=2908) SIZEY=([1]=2964) # Reference pixels for each chip. REFPIXX=([1]=1460) REFPIXY=([1]=1460) TYPE=OPT THELI-3.1.3/config/instruments/GOODMAN_2x2@SOAR.ini000066400000000000000000000013631417631501300212740ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GOODMAN_2x2@SOAR INSTSHORT=GOODMAN # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.308 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=22) CUTY=([1]=2) SIZEX=([1]=1454) SIZEY=([1]=1482) # Reference pixels for each chip. REFPIXX=([1]=730) REFPIXY=([1]=730) TYPE=OPT THELI-3.1.3/config/instruments/GPC1@PS1.ahead000066400000000000000000000712341417631501300203350ustar00rootroot00000000000000CRPIX1 = -1.009840516E+04 / Reference pixel on this axis CRPIX2 = -1.568770680E+04 / Reference pixel on this axis CD1_1 = -2.967827814E-05 / Linear projection matrix CD1_2 = 6.442055280E-05 / Linear projection matrix CD2_1 = -6.445879728E-05 / Linear projection matrix CD2_2 = -2.927648118E-05 / Linear projection matrix END CRPIX1 = -5.071468039E+03 / Reference pixel on this axis CRPIX2 = -1.570462085E+04 / Reference pixel on this axis CD1_1 = -2.977307730E-05 / Linear projection matrix CD1_2 = 6.438173849E-05 / Linear projection matrix CD2_1 = -6.454281194E-05 / Linear projection matrix CD2_2 = -2.941543254E-05 / Linear projection matrix END CRPIX1 = -9.202192543E+01 / Reference pixel on this axis CRPIX2 = -1.567816015E+04 / Reference pixel on this axis CD1_1 = -2.963704706E-05 / Linear projection matrix CD1_2 = 6.442210260E-05 / Linear projection matrix CD2_1 = -6.471031881E-05 / Linear projection matrix CD2_2 = -2.941282532E-05 / Linear projection matrix END CRPIX1 = -5.825623141E+01 / Reference pixel on this axis CRPIX2 = 2.054925015E+04 / Reference pixel on this axis CD1_1 = 2.961195085E-05 / Linear projection matrix CD1_2 = -6.433156547E-05 / Linear projection matrix CD2_1 = 6.474537871E-05 / Linear projection matrix CD2_2 = 2.955503882E-05 / Linear projection matrix END CRPIX1 = -5.057438085E+03 / Reference pixel on this axis CRPIX2 = 2.056738931E+04 / Reference pixel on this axis CD1_1 = 2.945338410E-05 / Linear projection matrix CD1_2 = -6.429437231E-05 / Linear projection matrix CD2_1 = 6.470033833E-05 / Linear projection matrix CD2_2 = 2.960469128E-05 / Linear projection matrix END CRPIX1 = -1.005469429E+04 / Reference pixel on this axis CRPIX2 = 2.060599807E+04 / Reference pixel on this axis CD1_1 = 2.927717846E-05 / Linear projection matrix CD1_2 = -6.426820416E-05 / Linear projection matrix CD2_1 = 6.465036390E-05 / Linear projection matrix CD2_2 = 2.963268672E-05 / Linear projection matrix END CRPIX1 = -1.508117521E+04 / Reference pixel on this axis CRPIX2 = -1.053281346E+04 / Reference pixel on this axis CD1_1 = -2.979373908E-05 / Linear projection matrix CD1_2 = 6.455672173E-05 / Linear projection matrix CD2_1 = -6.424979651E-05 / Linear projection matrix CD2_2 = -2.943850330E-05 / Linear projection matrix END CRPIX1 = -1.005681722E+04 / Reference pixel on this axis CRPIX2 = -1.053139373E+04 / Reference pixel on this axis CD1_1 = -2.986276927E-05 / Linear projection matrix CD1_2 = 6.453488840E-05 / Linear projection matrix CD2_1 = -6.443486906E-05 / Linear projection matrix CD2_2 = -2.946852962E-05 / Linear projection matrix END CRPIX1 = -5.069841745E+03 / Reference pixel on this axis CRPIX2 = -1.048541518E+04 / Reference pixel on this axis CD1_1 = -2.976333563E-05 / Linear projection matrix CD1_2 = 6.462116965E-05 / Linear projection matrix CD2_1 = -6.468297832E-05 / Linear projection matrix CD2_2 = -2.948112874E-05 / Linear projection matrix END CRPIX1 = -7.429541522E+01 / Reference pixel on this axis CRPIX2 = -1.047634994E+04 / Reference pixel on this axis CD1_1 = -2.973164048E-05 / Linear projection matrix CD1_2 = 6.462629165E-05 / Linear projection matrix CD2_1 = -6.481149031E-05 / Linear projection matrix CD2_2 = -2.953854266E-05 / Linear projection matrix END CRPIX1 = -7.883798324E+01 / Reference pixel on this axis CRPIX2 = 1.534450366E+04 / Reference pixel on this axis CD1_1 = 2.976113910E-05 / Linear projection matrix CD1_2 = -6.452702520E-05 / Linear projection matrix CD2_1 = 6.479475374E-05 / Linear projection matrix CD2_2 = 2.976329223E-05 / Linear projection matrix END CRPIX1 = -5.055961870E+03 / Reference pixel on this axis CRPIX2 = 1.535593570E+04 / Reference pixel on this axis CD1_1 = 2.957140950E-05 / Linear projection matrix CD1_2 = -6.452150048E-05 / Linear projection matrix CD2_1 = 6.477153694E-05 / Linear projection matrix CD2_2 = 2.973651130E-05 / Linear projection matrix END CRPIX1 = -1.005017791E+04 / Reference pixel on this axis CRPIX2 = 1.539757723E+04 / Reference pixel on this axis CD1_1 = 2.935338196E-05 / Linear projection matrix CD1_2 = -6.448557096E-05 / Linear projection matrix CD2_1 = 6.466857393E-05 / Linear projection matrix CD2_2 = 2.967547649E-05 / Linear projection matrix END CRPIX1 = -1.509569531E+04 / Reference pixel on this axis CRPIX2 = 1.541438372E+04 / Reference pixel on this axis CD1_1 = 2.927987509E-05 / Linear projection matrix CD1_2 = -6.432437527E-05 / Linear projection matrix CD2_1 = 6.450721376E-05 / Linear projection matrix CD2_2 = 2.983959185E-05 / Linear projection matrix END CRPIX1 = -1.505154175E+04 / Reference pixel on this axis CRPIX2 = -5.383702645E+03 / Reference pixel on this axis CD1_1 = -2.990468815E-05 / Linear projection matrix CD1_2 = 6.461238145E-05 / Linear projection matrix CD2_1 = -6.423403763E-05 / Linear projection matrix CD2_2 = -2.970125895E-05 / Linear projection matrix END CRPIX1 = -1.005074484E+04 / Reference pixel on this axis CRPIX2 = -5.331363483E+03 / Reference pixel on this axis CD1_1 = -2.979416914E-05 / Linear projection matrix CD1_2 = 6.472648534E-05 / Linear projection matrix CD2_1 = -6.452214359E-05 / Linear projection matrix CD2_2 = -2.961253870E-05 / Linear projection matrix END CRPIX1 = -5.062776498E+03 / Reference pixel on this axis CRPIX2 = -5.300812619E+03 / Reference pixel on this axis CD1_1 = -2.971036530E-05 / Linear projection matrix CD1_2 = 6.483402969E-05 / Linear projection matrix CD2_1 = -6.478278982E-05 / Linear projection matrix CD2_2 = -2.953170407E-05 / Linear projection matrix END CRPIX1 = -4.739564053E+01 / Reference pixel on this axis CRPIX2 = -5.321037689E+03 / Reference pixel on this axis CD1_1 = -2.991609822E-05 / Linear projection matrix CD1_2 = 6.474062826E-05 / Linear projection matrix CD2_1 = -6.482840152E-05 / Linear projection matrix CD2_2 = -2.981154017E-05 / Linear projection matrix END CRPIX1 = -5.165497175E+01 / Reference pixel on this axis CRPIX2 = 1.017303710E+04 / Reference pixel on this axis CD1_1 = 2.967369024E-05 / Linear projection matrix CD1_2 = -6.481324432E-05 / Linear projection matrix CD2_1 = 6.494122866E-05 / Linear projection matrix CD2_2 = 2.969860594E-05 / Linear projection matrix END CRPIX1 = -5.052595439E+03 / Reference pixel on this axis CRPIX2 = 1.018089363E+04 / Reference pixel on this axis CD1_1 = 2.963820501E-05 / Linear projection matrix CD1_2 = -6.469809654E-05 / Linear projection matrix CD2_1 = 6.478982440E-05 / Linear projection matrix CD2_2 = 2.981102517E-05 / Linear projection matrix END CRPIX1 = -1.004119782E+04 / Reference pixel on this axis CRPIX2 = 1.021803786E+04 / Reference pixel on this axis CD1_1 = 2.938827031E-05 / Linear projection matrix CD1_2 = -6.469589042E-05 / Linear projection matrix CD2_1 = 6.468427785E-05 / Linear projection matrix CD2_2 = 2.968696110E-05 / Linear projection matrix END CRPIX1 = -1.508656842E+04 / Reference pixel on this axis CRPIX2 = 1.016660270E+04 / Reference pixel on this axis CD1_1 = 2.953268026E-05 / Linear projection matrix CD1_2 = -6.449965829E-05 / Linear projection matrix CD2_1 = 6.436667697E-05 / Linear projection matrix CD2_2 = 2.990758239E-05 / Linear projection matrix END CRPIX1 = -1.506418468E+04 / Reference pixel on this axis CRPIX2 = -1.539959782E+02 / Reference pixel on this axis CD1_1 = -2.961720067E-05 / Linear projection matrix CD1_2 = 6.472662262E-05 / Linear projection matrix CD2_1 = -6.437294724E-05 / Linear projection matrix CD2_2 = -2.968169087E-05 / Linear projection matrix END CRPIX1 = -1.002826539E+04 / Reference pixel on this axis CRPIX2 = -1.806748782E+02 / Reference pixel on this axis CD1_1 = -2.982435311E-05 / Linear projection matrix CD1_2 = 6.476411897E-05 / Linear projection matrix CD2_1 = -6.454471015E-05 / Linear projection matrix CD2_2 = -2.982576150E-05 / Linear projection matrix END CRPIX1 = -5.047806192E+03 / Reference pixel on this axis CRPIX2 = -1.511953423E+02 / Reference pixel on this axis CD1_1 = -2.984735008E-05 / Linear projection matrix CD1_2 = 6.484911091E-05 / Linear projection matrix CD2_1 = -6.474790932E-05 / Linear projection matrix CD2_2 = -2.982421847E-05 / Linear projection matrix END CRPIX1 = -5.440884252E+01 / Reference pixel on this axis CRPIX2 = -1.429678922E+02 / Reference pixel on this axis CD1_1 = -2.984655433E-05 / Linear projection matrix CD1_2 = 6.490206900E-05 / Linear projection matrix CD2_1 = -6.491598345E-05 / Linear projection matrix CD2_2 = -2.982588655E-05 / Linear projection matrix END CRPIX1 = -5.741109873E+01 / Reference pixel on this axis CRPIX2 = 5.010700984E+03 / Reference pixel on this axis CD1_1 = 2.975316276E-05 / Linear projection matrix CD1_2 = -6.494424244E-05 / Linear projection matrix CD2_1 = 6.495435446E-05 / Linear projection matrix CD2_2 = 2.976408143E-05 / Linear projection matrix END CRPIX1 = -5.039955606E+03 / Reference pixel on this axis CRPIX2 = 5.009838072E+03 / Reference pixel on this axis CD1_1 = 2.975335448E-05 / Linear projection matrix CD1_2 = -6.485111572E-05 / Linear projection matrix CD2_1 = 6.480794757E-05 / Linear projection matrix CD2_2 = 2.984383698E-05 / Linear projection matrix END CRPIX1 = -1.004966081E+04 / Reference pixel on this axis CRPIX2 = 5.011165204E+03 / Reference pixel on this axis CD1_1 = 2.966222806E-05 / Linear projection matrix CD1_2 = -6.475501370E-05 / Linear projection matrix CD2_1 = 6.457886189E-05 / Linear projection matrix CD2_2 = 2.989169095E-05 / Linear projection matrix END CRPIX1 = -1.506454352E+04 / Reference pixel on this axis CRPIX2 = 5.050010099E+03 / Reference pixel on this axis CD1_1 = 2.944216180E-05 / Linear projection matrix CD1_2 = -6.469729791E-05 / Linear projection matrix CD2_1 = 6.443589854E-05 / Linear projection matrix CD2_2 = 2.969421180E-05 / Linear projection matrix END CRPIX1 = -1.506356603E+04 / Reference pixel on this axis CRPIX2 = 5.013537163E+03 / Reference pixel on this axis CD1_1 = -2.953702150E-05 / Linear projection matrix CD1_2 = 6.468424292E-05 / Linear projection matrix CD2_1 = -6.440901996E-05 / Linear projection matrix CD2_2 = -2.975135038E-05 / Linear projection matrix END CRPIX1 = -1.004219770E+04 / Reference pixel on this axis CRPIX2 = 5.010980115E+03 / Reference pixel on this axis CD1_1 = -2.963738048E-05 / Linear projection matrix CD1_2 = 6.477362700E-05 / Linear projection matrix CD2_1 = -6.463266174E-05 / Linear projection matrix CD2_2 = -2.979842106E-05 / Linear projection matrix END CRPIX1 = -5.046503113E+03 / Reference pixel on this axis CRPIX2 = 5.036527302E+03 / Reference pixel on this axis CD1_1 = -2.967844899E-05 / Linear projection matrix CD1_2 = 6.484439882E-05 / Linear projection matrix CD2_1 = -6.482579683E-05 / Linear projection matrix CD2_2 = -2.978301712E-05 / Linear projection matrix END CRPIX1 = -5.319027886E+01 / Reference pixel on this axis CRPIX2 = 4.995919969E+03 / Reference pixel on this axis CD1_1 = -2.985477997E-05 / Linear projection matrix CD1_2 = 6.489128896E-05 / Linear projection matrix CD2_1 = -6.490472887E-05 / Linear projection matrix CD2_2 = -2.987334999E-05 / Linear projection matrix END CRPIX1 = -5.519980514E+01 / Reference pixel on this axis CRPIX2 = -1.354710225E+02 / Reference pixel on this axis CD1_1 = 2.980379890E-05 / Linear projection matrix CD1_2 = -6.492962274E-05 / Linear projection matrix CD2_1 = 6.493608198E-05 / Linear projection matrix CD2_2 = 2.979124555E-05 / Linear projection matrix END CRPIX1 = -5.043884683E+03 / Reference pixel on this axis CRPIX2 = -1.377050822E+02 / Reference pixel on this axis CD1_1 = 2.976868470E-05 / Linear projection matrix CD1_2 = -6.489701566E-05 / Linear projection matrix CD2_1 = 6.478459842E-05 / Linear projection matrix CD2_2 = 2.974539310E-05 / Linear projection matrix END CRPIX1 = -1.004049430E+04 / Reference pixel on this axis CRPIX2 = -1.634518403E+02 / Reference pixel on this axis CD1_1 = 2.977842314E-05 / Linear projection matrix CD1_2 = -6.479980431E-05 / Linear projection matrix CD2_1 = 6.454697549E-05 / Linear projection matrix CD2_2 = 2.979006597E-05 / Linear projection matrix END CRPIX1 = -1.506740068E+04 / Reference pixel on this axis CRPIX2 = -1.562403508E+02 / Reference pixel on this axis CD1_1 = 2.961838854E-05 / Linear projection matrix CD1_2 = -6.470073788E-05 / Linear projection matrix CD2_1 = 6.431953469E-05 / Linear projection matrix CD2_2 = 2.967900708E-05 / Linear projection matrix END CRPIX1 = -1.509101216E+04 / Reference pixel on this axis CRPIX2 = 1.015303151E+04 / Reference pixel on this axis CD1_1 = -2.960299053E-05 / Linear projection matrix CD1_2 = 6.448835484E-05 / Linear projection matrix CD2_1 = -6.438273518E-05 / Linear projection matrix CD2_2 = -2.997240393E-05 / Linear projection matrix END CRPIX1 = -1.005168101E+04 / Reference pixel on this axis CRPIX2 = 1.019008907E+04 / Reference pixel on this axis CD1_1 = -2.950031747E-05 / Linear projection matrix CD1_2 = 6.467389975E-05 / Linear projection matrix CD2_1 = -6.465649966E-05 / Linear projection matrix CD2_2 = -2.976564936E-05 / Linear projection matrix END CRPIX1 = -5.059460902E+03 / Reference pixel on this axis CRPIX2 = 1.016166722E+04 / Reference pixel on this axis CD1_1 = -2.975092201E-05 / Linear projection matrix CD1_2 = 6.465970820E-05 / Linear projection matrix CD2_1 = -6.475548633E-05 / Linear projection matrix CD2_2 = -2.992327625E-05 / Linear projection matrix END CRPIX1 = -5.557029213E+01 / Reference pixel on this axis CRPIX2 = 1.016171061E+04 / Reference pixel on this axis CD1_1 = -2.972641008E-05 / Linear projection matrix CD1_2 = 6.479536697E-05 / Linear projection matrix CD2_1 = -6.490984355E-05 / Linear projection matrix CD2_2 = -2.975823920E-05 / Linear projection matrix END CRPIX1 = -6.756950565E+01 / Reference pixel on this axis CRPIX2 = -5.295089767E+03 / Reference pixel on this axis CD1_1 = 2.975288393E-05 / Linear projection matrix CD1_2 = -6.481533319E-05 / Linear projection matrix CD2_1 = 6.489870053E-05 / Linear projection matrix CD2_2 = 2.966440472E-05 / Linear projection matrix END CRPIX1 = -5.040144945E+03 / Reference pixel on this axis CRPIX2 = -5.315289322E+03 / Reference pixel on this axis CD1_1 = 2.984710659E-05 / Linear projection matrix CD1_2 = -6.476584148E-05 / Linear projection matrix CD2_1 = 6.471435881E-05 / Linear projection matrix CD2_2 = 2.967679342E-05 / Linear projection matrix END CRPIX1 = -1.006413808E+04 / Reference pixel on this axis CRPIX2 = -5.312867043E+03 / Reference pixel on this axis CD1_1 = 2.971950263E-05 / Linear projection matrix CD1_2 = -6.476772617E-05 / Linear projection matrix CD2_1 = 6.453570228E-05 / Linear projection matrix CD2_2 = 2.954837058E-05 / Linear projection matrix END CRPIX1 = -1.505871475E+04 / Reference pixel on this axis CRPIX2 = -5.335584180E+03 / Reference pixel on this axis CD1_1 = 2.974074509E-05 / Linear projection matrix CD1_2 = -6.466533226E-05 / Linear projection matrix CD2_1 = 6.431539644E-05 / Linear projection matrix CD2_2 = 2.957407179E-05 / Linear projection matrix END CRPIX1 = -1.509433102E+04 / Reference pixel on this axis CRPIX2 = 1.537819079E+04 / Reference pixel on this axis CD1_1 = -2.936824953E-05 / Linear projection matrix CD1_2 = 6.441606755E-05 / Linear projection matrix CD2_1 = -6.446001616E-05 / Linear projection matrix CD2_2 = -2.984085864E-05 / Linear projection matrix END CRPIX1 = -1.005705642E+04 / Reference pixel on this axis CRPIX2 = 1.537836109E+04 / Reference pixel on this axis CD1_1 = -2.940904901E-05 / Linear projection matrix CD1_2 = 6.449477659E-05 / Linear projection matrix CD2_1 = -6.466194041E-05 / Linear projection matrix CD2_2 = -2.974421169E-05 / Linear projection matrix END CRPIX1 = -5.070211596E+03 / Reference pixel on this axis CRPIX2 = 1.534157721E+04 / Reference pixel on this axis CD1_1 = -2.967512759E-05 / Linear projection matrix CD1_2 = 6.447558634E-05 / Linear projection matrix CD2_1 = -6.472343759E-05 / Linear projection matrix CD2_2 = -2.983953247E-05 / Linear projection matrix END CRPIX1 = -7.200823738E+01 / Reference pixel on this axis CRPIX2 = 1.534023913E+04 / Reference pixel on this axis CD1_1 = -2.973632583E-05 / Linear projection matrix CD1_2 = 6.455851658E-05 / Linear projection matrix CD2_1 = -6.481142860E-05 / Linear projection matrix CD2_2 = -2.972207326E-05 / Linear projection matrix END CRPIX1 = -7.986126300E+01 / Reference pixel on this axis CRPIX2 = -1.047140527E+04 / Reference pixel on this axis CD1_1 = 2.969200436E-05 / Linear projection matrix CD1_2 = -6.465039452E-05 / Linear projection matrix CD2_1 = 6.483188879E-05 / Linear projection matrix CD2_2 = 2.952378317E-05 / Linear projection matrix END CRPIX1 = -5.053636768E+03 / Reference pixel on this axis CRPIX2 = -1.048858804E+04 / Reference pixel on this axis CD1_1 = 2.981671401E-05 / Linear projection matrix CD1_2 = -6.460216788E-05 / Linear projection matrix CD2_1 = 6.463837469E-05 / Linear projection matrix CD2_2 = 2.954089948E-05 / Linear projection matrix END CRPIX1 = -1.008725243E+04 / Reference pixel on this axis CRPIX2 = -1.047903614E+04 / Reference pixel on this axis CD1_1 = 2.969690197E-05 / Linear projection matrix CD1_2 = -6.465552316E-05 / Linear projection matrix CD2_1 = 6.450553387E-05 / Linear projection matrix CD2_2 = 2.935750238E-05 / Linear projection matrix END CRPIX1 = -1.507558275E+04 / Reference pixel on this axis CRPIX2 = -1.050998842E+04 / Reference pixel on this axis CD1_1 = 2.973388218E-05 / Linear projection matrix CD1_2 = -6.457403398E-05 / Linear projection matrix CD2_1 = 6.430905042E-05 / Linear projection matrix CD2_2 = 2.942468151E-05 / Linear projection matrix END CRPIX1 = -1.007533887E+04 / Reference pixel on this axis CRPIX2 = 2.055428920E+04 / Reference pixel on this axis CD1_1 = -2.951324845E-05 / Linear projection matrix CD1_2 = 6.425479315E-05 / Linear projection matrix CD2_1 = -6.460730373E-05 / Linear projection matrix CD2_2 = -2.971174263E-05 / Linear projection matrix END CRPIX1 = -5.069133327E+03 / Reference pixel on this axis CRPIX2 = 2.055408401E+04 / Reference pixel on this axis CD1_1 = -2.948130327E-05 / Linear projection matrix CD1_2 = 6.433493540E-05 / Linear projection matrix CD2_1 = -6.473494520E-05 / Linear projection matrix CD2_2 = -2.965059249E-05 / Linear projection matrix END CRPIX1 = -7.726426017E+01 / Reference pixel on this axis CRPIX2 = 2.053137382E+04 / Reference pixel on this axis CD1_1 = -2.969346117E-05 / Linear projection matrix CD1_2 = 6.435959168E-05 / Linear projection matrix CD2_1 = -6.471053966E-05 / Linear projection matrix CD2_2 = -2.964472530E-05 / Linear projection matrix END CRPIX1 = -8.914730471E+01 / Reference pixel on this axis CRPIX2 = -1.566240815E+04 / Reference pixel on this axis CD1_1 = 2.967440092E-05 / Linear projection matrix CD1_2 = -6.443876848E-05 / Linear projection matrix CD2_1 = 6.473574983E-05 / Linear projection matrix CD2_2 = 2.945445968E-05 / Linear projection matrix END CRPIX1 = -5.107285196E+03 / Reference pixel on this axis CRPIX2 = -1.566678841E+04 / Reference pixel on this axis CD1_1 = 2.968790609E-05 / Linear projection matrix CD1_2 = -6.447238004E-05 / Linear projection matrix CD2_1 = 6.460159514E-05 / Linear projection matrix CD2_2 = 2.930337540E-05 / Linear projection matrix END CRPIX1 = -1.008932136E+04 / Reference pixel on this axis CRPIX2 = -1.568631889E+04 / Reference pixel on this axis CD1_1 = 2.976931929E-05 / Linear projection matrix CD1_2 = -6.446136545E-05 / Linear projection matrix CD2_1 = 6.442269820E-05 / Linear projection matrix CD2_2 = 2.933734824E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/GPC1@PS1.ini000066400000000000000000000111311417631501300200400ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GPC1@PS1 INSTSHORT=GPC1 # Number of chips NCHIPS=60 # Geographical location of the observatory OBSLAT=20.80 OBSLONG=-156.33 # Pixel scale in arcsec PIXSCALE=0.256 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0 [37]=0 [38]=0 [39]=0 [40]=0 [41]=0 [42]=0 [43]=0 [44]=0 [45]=0 [46]=0 [47]=0 [48]=0 [49]=0 [50]=0 [51]=0 [52]=0 [53]=0 [54]=0 [55]=0 [56]=0 [57]=0 [58]=0 [59]=0 [60]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0 [37]=0 [38]=0 [39]=0 [40]=0 [41]=0 [42]=0 [43]=0 [44]=0 [45]=0 [46]=0 [47]=0 [48]=0 [49]=0 [50]=0 [51]=0 [52]=0 [53]=0 [54]=0 [55]=0 [56]=0 [57]=0 [58]=0 [59]=0 [60]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1 [11]=1 [12]=1 [13]=1 [14]=1 [15]=1 [16]=1 [17]=1 [18]=1 [19]=1 [20]=1 [21]=1 [22]=1 [23]=1 [24]=1 [25]=1 [26]=1 [27]=1 [28]=1 [29]=1 [30]=1 [31]=1 [32]=1 [33]=1 [34]=1 [35]=1 [36]=1 [37]=1 [38]=1 [39]=1 [40]=1 [41]=1 [42]=1 [43]=1 [44]=1 [45]=1 [46]=1 [47]=1 [48]=1 [49]=1 [50]=1 [51]=1 [52]=1 [53]=1 [54]=1 [55]=1 [56]=1 [57]=1 [58]=1 [59]=1 [60]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1 [11]=1 [12]=1 [13]=1 [14]=1 [15]=1 [16]=1 [17]=1 [18]=1 [19]=1 [20]=1 [21]=1 [22]=1 [23]=1 [24]=1 [25]=1 [26]=1 [27]=1 [28]=1 [29]=1 [30]=1 [31]=1 [32]=1 [33]=1 [34]=1 [35]=1 [36]=1 [37]=1 [38]=1 [39]=1 [40]=1 [41]=1 [42]=1 [43]=1 [44]=1 [45]=1 [46]=1 [47]=1 [48]=1 [49]=1 [50]=1 [51]=1 [52]=1 [53]=1 [54]=1 [55]=1 [56]=1 [57]=1 [58]=1 [59]=1 [60]=1) SIZEX=([1]=4846 [2]=4846 [3]=4846 [4]=4846 [5]=4844846 [6]=4846 [7]=4846 [8]=4846 [9]=4844846 [10]=4846 [11]=4846 [12]=4846 [13]=4846 [14]=4846 [15]=4846 [16]=4846 [17]=6 [18]=4846 [19]=4846 [20]=4846 [21]=4846 [22]=4846 [23]=4846 [24]=4846 [25]=4846 [26]=4846 [27]=4846 [28]=4846 [29]=6 [30]=4846 [31]=4846 [32]=4846 [33]=4846 [34]=4846 [35]=4846 [36]=4846 [37]=4846 [38]=4846 [39]=4846 [40]=4846 [41]=4846 [42]=4846 [43]=4846 [44]=4846 [45]=4846 [46]=4846 [47]=4846 [48]=4846 [49]=4846 [50]=4846 [51]=4846 [52]=4846 [53]=4846 [54]=4846 [55]=4846 [56]=4846 [57]=4846 [58]=4846 [59]=4846 [60]=4846) SIZEY=([1]=4868 [2]=4868 [3]=4868 [4]=4868 [5]=4868 [6]=4868 [7]=4868 [8]=4868 [9]=4868 [10]=4868 [11]=4868 [12]=4868 [13]=4868 [14]=4868 [15]=4868 [16]=4868 [17]=4868 [18]=4868 [19]=4868 [20]=4868 [21]=4868 [22]=4868 [23]=4868 [24]=4868 [25]=4868 [26]=4868 [27]=4868 [28]=4868 [29]=4868 [30]=4868 [31]=4868 [32]=4868 [33]=4868 [34]=4868 [35]=4868 [36]=4868 [37]=4868 [38]=4868 [39]=4868 [40]=4868 [41]=4868 [42]=4868 [43]=4868 [44]=4868 [45]=4868 [46]=4868 [47]=4868 [48]=4868 [49]=4868 [50]=4868 [51]=4868 [52]=4868 [53]=4868 [54]=4868 [55]=4868 [56]=4868 [57]=4868 [58]=4868 [59]=4868 [60]=4868) # Reference pixels for each chip. REFPIXX=([1]=2400 [2]=2400 [3]=2400 [4]=2400 [5]=2400 [6]=2400 [7]=2400 [8]=2400 [9]=2400 [10]=2400 [11]=2400 [12]=2400 [13]=2400 [14]=2400 [15]=2400 [16]=2400 [17]=2400 [18]=2400 [19]=2400 [20]=2400 [21]=2400 [22]=2400 [23]=2400 [24]=2400 [25]=2400 [26]=2400 [27]=2400 [28]=2400 [29]=2400 [30]=2400 [31]=2400 [32]=2400 [33]=2400 [34]=2400 [35]=2400 [36]=2400 [37]=2400 [38]=2400 [39]=2400 [40]=2400 [41]=2400 [42]=2400 [43]=2400 [44]=2400 [45]=2400 [46]=2400 [47]=2400 [48]=2400 [49]=2400 [50]=2400 [51]=2400 [52]=2400 [53]=2400 [54]=2400 [55]=2400 [56]=2400 [57]=2400 [58]=2400 [59]=2400 [60]=2400) REFPIXY=([1]=2400 [2]=2400 [3]=2400 [4]=2400 [5]=2400 [6]=2400 [7]=2400 [8]=2400 [9]=2400 [10]=2400 [11]=2400 [12]=2400 [13]=2400 [14]=2400 [15]=2400 [16]=2400 [17]=2400 [18]=2400 [19]=2400 [20]=2400 [21]=2400 [22]=2400 [23]=2400 [24]=2400 [25]=2400 [26]=2400 [27]=2400 [28]=2400 [29]=2400 [30]=2400 [31]=2400 [32]=2400 [33]=2400 [34]=2400 [35]=2400 [36]=2400 [37]=2400 [38]=2400 [39]=2400 [40]=2400 [41]=2400 [42]=2400 [43]=2400 [44]=2400 [45]=2400 [46]=2400 [47]=2400 [48]=2400 [49]=2400 [50]=2400 [51]=2400 [52]=2400 [53]=2400 [54]=2400 [55]=2400 [56]=2400 [57]=2400 [58]=2400 [59]=2400 [60]=2400) TYPE=OPT THELI-3.1.3/config/instruments/GROND_NIR@MPGESO.ini000066400000000000000000000013571417631501300213270ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GROND_NIR@MPGESO INSTSHORT=GROND # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.605 GAIN=2.45 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/GROND_NIR@MPGESO_1.reg000066400000000000000000000002261417631501300215370ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(20,1010,977,1015,998,997,994,824,994,513,1000,56,972,17,560,18,29,10,27,514) THELI-3.1.3/config/instruments/GROND_OPT@MPGESO.ini000066400000000000000000000013761417631501300213420ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GROND_OPT@MPGESO INSTSHORT=GROND # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.158 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=2) SIZEX=([1]=2048) SIZEY=([1]=2050) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/GROND_OPT@MPGESO_1.reg000066400000000000000000000002051417631501300215460ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(9.1421428,1955.8579,2043,1956,2041,132,9.1421428,128.14214) THELI-3.1.3/config/instruments/GSAOI@GEMINI.ahead000066400000000000000000000036441417631501300210520ustar00rootroot00000000000000CRPIX1 = -1.031934599166E+02 / Reference pixel on this axis CRPIX2 = 2.124743157143E+03 / Reference pixel on this axis CD1_1 = 5.383267939425E-06 / Linear projection matrix CD1_2 = 6.626339117201E-08 / Linear projection matrix CD2_1 = 1.619138882948E-08 / Linear projection matrix CD2_2 = 5.463376133457E-06 / Linear projection matrix END CRPIX1 = 2.098290401651E+03 / Reference pixel on this axis CRPIX2 = 2.124709562240E+03 / Reference pixel on this axis CD1_1 = 5.504077259512E-06 / Linear projection matrix CD1_2 = 6.351897670714E-08 / Linear projection matrix CD2_1 = 6.427739640088E-09 / Linear projection matrix CD2_2 = 5.463978437433E-06 / Linear projection matrix END CRPIX1 = 2.096596017755E+03 / Reference pixel on this axis CRPIX2 = -6.921201518097E+01 / Reference pixel on this axis CD1_1 = 5.510314691096E-06 / Linear projection matrix CD1_2 = -8.270735046219E-08 / Linear projection matrix CD2_1 = 2.680574389976E-08 / Linear projection matrix CD2_2 = 5.474815756689E-06 / Linear projection matrix END CRPIX1 = -9.123603847576E+01 / Reference pixel on this axis CRPIX2 = -6.712335442478E+01 / Reference pixel on this axis CD1_1 = 5.393383947414E-06 / Linear projection matrix CD1_2 = -5.735146247941E-08 / Linear projection matrix CD2_1 = 1.066452906613E-08 / Linear projection matrix CD2_2 = 5.484252212080E-06 / Linear projection matrix END THELI-3.1.3/config/instruments/GSAOI@GEMINI.ini000066400000000000000000000016401417631501300205610ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GSAOI@GEMINI INSTSHORT=GSAOI # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0197 GAIN=2.01 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048) # Reference pixels for each chip. REFPIXX=([1]=-82 [2]=2099 [3]=2110 [4]=-83) REFPIXY=([1]=2091 [2]=2101 [3]=-67 [4]=-53) TYPE=NIR THELI-3.1.3/config/instruments/GSAOI@GEMINI.nldat000066400000000000000000000001501417631501300210770ustar00rootroot000000000000000.0 0.9947 7.4E-7 2.5E-11 0.0 0.9940 6.0E-7 3.7E-11 0.0 0.9947 7.1E-7 2.2E-11 0.0 0.9959 5.7E-7 2.7E-11 THELI-3.1.3/config/instruments/GSAOI@GEMINI_1.reg000066400000000000000000000013421417631501300207760ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 # Sense: out # image polygon(572.15808,1468.8419,607.84192,1468.8419,607.84192,1433.1581,572.15808,1433.1581) polygon(770.70911,927.29089,805.29089,927.29089,805.29089,892.70911,770.70911,892.70911) polygon(219.88704,594.11296,240.11296,594.11296,240.11296,573.88704,219.88704,573.88704) polygon(-4.9739244,2055.1213,14,2062,14,2037,9,2011,16,20,1825,15,1944,46,2002,95,2005,499,2016,994,1958,1082,1958,1190,2010,1226,2009,1592,2003,1781,2002,1913,1914,1940,1878,2032,14,2037,14,2062,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) THELI-3.1.3/config/instruments/GSAOI@GEMINI_2.reg000066400000000000000000000023341417631501300210010ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 # Sense: out # image polygon(1248.0938,1054.9062,1279,1068,1328,1064,1331,1002,1297,984,1258,983,1244,1014) polygon(984.1379,1659.8621,1027.8621,1659.8621,1027.8621,1616.1379,984.1379,1616.1379) polygon(1047.4374,824.56257,1080.5626,824.56257,1080.5626,791.43743,1047.4374,791.43743) polygon(527.01874,473.98126,574.98126,473.98126,574.98126,426.01874,527.01874,426.01874) polygon(-4.9739244,2055.1213,77,2053,77,2026,29,2026,8,2015,10,34,11,9,2040,8,2040,1986,2040,2040,77,2040,77,2052,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) polygon(857.62337,1158.3766,884.37663,1158.3766,884.37663,1131.6234,857.62337,1131.6234) polygon(1400.6962,967.30383,1427.3038,967.30383,1427.3038,940.69617,1400.6962,940.69617) polygon(1480.6769,970.32306,1497.3231,970.32306,1497.3231,953.67694,1480.6769,953.67694) polygon(540.6547,889.3453,559.3453,889.3453,559.3453,870.6547,540.6547,870.6547) polygon(1515,693,1555,740,1575,729,1591,761,1600,754,1584,730,1623,707,1609,697,1555,723,1531,699,1520,667,1523,653,1505,616,1494.2544,616.25437,1505,647) THELI-3.1.3/config/instruments/GSAOI@GEMINI_3.reg000066400000000000000000000023641417631501300210050ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out polygon(130.25782,356.39668,211.73696,355.06095,231,290,214.40841,227.49935,183.0189,221.48859,138.94003,220.82073,112.22555,296.28911) polygon(-4.9739244,2055.1213,34.5,2050.75,34.5,2036,19.441982,2012.251,13.078879,33.134941,29.775424,13.099087,2036.9417,8.2519557,2038.9166,1984.5489,2022.8879,2027.292,34.5,2036,34.5,2053.5,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) polygon(1497.929,727.66877,1562.5662,697.50473,1543.1751,684.57729,1515.1656,692.1183,1493.8277,706.33088) polygon(1904.4279,891.01685,1927.8186,887.01735,1926.7413,808.37539,1924.5868,793.29338,1932.1278,778.21136,1933.205,696.33754,1917.0457,696.33754,1920.2776,628.46845,1934.2823,616.6183,1936.4369,530.43533,1924.5868,522.89432,1931.0505,467.95268,1927.8186,448.56151,1928.8959,413.01104,1933.205,382.847,1938.5915,316.05521,1934.2823,308.5142,1940.7461,163.08044,1935.3596,157.69401,1936.4369,103.82965,1913.8139,86.59306,1906.2729,163.08044,1921.3549,173.85331,1920.2776,321.44164,1915.9685,383.92429,1905.1956,405.47003,1904.1183,433.4795,1909.5047,470.10726,1906.2729,497.03943,1918.123,527.20347,1907.3502,575.68139,1917.0457,611.23186,1914.8912,697.41483,1905.1956,758.82019,1880.418,786.82965,1904.4279,820.5352) THELI-3.1.3/config/instruments/GSAOI@GEMINI_4.reg000066400000000000000000000006141417631501300210020ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 # Sense: out # image polygon(-4.9739244,2055.1213,20,2054,20,2027,13,2018,12,15,2013,16,2031,43,2030,1970,1971,1971,1938,2027,20,2027,20,2057,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) THELI-3.1.3/config/instruments/GSAOI_1k@GEMINI.ini000066400000000000000000000016671417631501300211650ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GSAOI_1k@GEMINI INSTSHORT=GSAOI_1k # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0197 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=1024 [2]=1024 [3]=1024 [4]=1024) SIZEY=([1]=1024 [2]=1024 [3]=1024 [4]=1024) # Reference pixels for each chip. REFPIXX=([1]=-594 [2]=1587 [3]=1598 [4]=-595) REFPIXY=([1]=1579 [2]=1589 [3]=-579 [4]=-565) # Camera type TYPE=NIR THELI-3.1.3/config/instruments/GSAOI_CHIP1@GEMINI.ini000066400000000000000000000013661417631501300214520ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GSAOI_CHIP1@GEMINI INSTSHORT=GSAOI1 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0197 GAIN=2.01 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=-82) REFPIXY=([1]=2091) TYPE=NIR THELI-3.1.3/config/instruments/GSAOI_CHIP1@GEMINI_1.reg000066400000000000000000000013421417631501300216620ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 # Sense: out # image polygon(572.15808,1468.8419,607.84192,1468.8419,607.84192,1433.1581,572.15808,1433.1581) polygon(770.70911,927.29089,805.29089,927.29089,805.29089,892.70911,770.70911,892.70911) polygon(219.88704,594.11296,240.11296,594.11296,240.11296,573.88704,219.88704,573.88704) polygon(-4.9739244,2055.1213,14,2062,14,2037,9,2011,16,20,1825,15,1944,46,2002,95,2005,499,2016,994,1958,1082,1958,1190,2010,1226,2009,1592,2003,1781,2002,1913,1914,1940,1878,2032,14,2037,14,2062,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) THELI-3.1.3/config/instruments/GSAOI_CHIP2@GEMINI.ini000066400000000000000000000013701417631501300214460ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GSAOI_CHIP2@GEMINI INSTSHORT=GSAOI2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0197 GAIN=2.01 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=2099) REFPIXY=([1]=2101) TYPE=NIR THELI-3.1.3/config/instruments/GSAOI_CHIP2@GEMINI_1.reg000066400000000000000000000023341417631501300216650ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 # Sense: out # image polygon(1248.0938,1054.9062,1279,1068,1328,1064,1331,1002,1297,984,1258,983,1244,1014) polygon(984.1379,1659.8621,1027.8621,1659.8621,1027.8621,1616.1379,984.1379,1616.1379) polygon(1047.4374,824.56257,1080.5626,824.56257,1080.5626,791.43743,1047.4374,791.43743) polygon(527.01874,473.98126,574.98126,473.98126,574.98126,426.01874,527.01874,426.01874) polygon(-4.9739244,2055.1213,77,2053,77,2026,29,2026,8,2015,10,34,11,9,2040,8,2040,1986,2040,2040,77,2040,77,2052,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) polygon(857.62337,1158.3766,884.37663,1158.3766,884.37663,1131.6234,857.62337,1131.6234) polygon(1400.6962,967.30383,1427.3038,967.30383,1427.3038,940.69617,1400.6962,940.69617) polygon(1480.6769,970.32306,1497.3231,970.32306,1497.3231,953.67694,1480.6769,953.67694) polygon(540.6547,889.3453,559.3453,889.3453,559.3453,870.6547,540.6547,870.6547) polygon(1515,693,1555,740,1575,729,1591,761,1600,754,1584,730,1623,707,1609,697,1555,723,1531,699,1520,667,1523,653,1505,616,1494.2544,616.25437,1505,647) THELI-3.1.3/config/instruments/GSAOI_CHIP3@GEMINI.ini000066400000000000000000000013661417631501300214540ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GSAOI_CHIP3@GEMINI INSTSHORT=GSAOI3 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0197 GAIN=2.01 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=2110) REFPIXY=([1]=-67) TYPE=NIR THELI-3.1.3/config/instruments/GSAOI_CHIP3@GEMINI_1.reg000066400000000000000000000011311417631501300216600ustar00rootroot00000000000000# Region file format: DS9 version 4.1 #global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 # Sense: out #image polygon(130.25782,356.39668,211.73696,355.06095,231,290,214.40841,227.49935,183.0189,221.48859,138.94003,220.82073,112.22555,296.28911) polygon(-4.9739244,2055.1213,34.5,2050.75,34.5,2036,19.441982,2012.251,13.078879,33.134941,29.775424,13.099087,2036.9417,8.2519557,2038.9166,1984.5489,2022.8879,2027.292,34.5,2036,34.5,2053.5,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) THELI-3.1.3/config/instruments/GSAOI_CHIP4@GEMINI.ini000066400000000000000000000013651417631501300214540ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=GSAOI_CHIP4@GEMINI INSTSHORT=GSAOI4 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0197 GAIN=2.01 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=-83) REFPIXY=([1]=-53) TYPE=NIR THELI-3.1.3/config/instruments/GSAOI_CHIP4@GEMINI_1.reg000066400000000000000000000006141417631501300216660ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 # Sense: out # image polygon(-4.9739244,2055.1213,20,2054,20,2027,13,2018,12,15,2013,16,2031,43,2030,1970,1971,1971,1938,2027,20,2027,20,2057,2054.9452,2054.0065,2060.9847,-5.1052803,-7.6453716,-4.5645372) THELI-3.1.3/config/instruments/HAWKI@VLT.ahead000066400000000000000000000036441417631501300205500ustar00rootroot00000000000000CRPIX1 = 2.111378233E+03 / Reference pixel on this axis CRPIX2 = 2.124943954E+03 / Reference pixel on this axis CD1_1 = -2.951947429E-05 / Linear projection matrix CD1_2 = -9.903173937E-09 / Linear projection matrix CD2_1 = -1.687536425E-08 / Linear projection matrix CD2_2 = 2.960630297E-05 / Linear projection matrix END CRPIX1 = -9.370647583E+01 / Reference pixel on this axis CRPIX2 = 2.126002578E+03 / Reference pixel on this axis CD1_1 = -2.960500992E-05 / Linear projection matrix CD1_2 = -3.872429183E-08 / Linear projection matrix CD2_1 = 6.770263896E-08 / Linear projection matrix CD2_2 = 2.961527453E-05 / Linear projection matrix END CRPIX1 = 2.098618181E+03 / Reference pixel on this axis CRPIX2 = -6.424270208E+01 / Reference pixel on this axis CD1_1 = -2.966327856E-05 / Linear projection matrix CD1_2 = -7.429716187E-08 / Linear projection matrix CD2_1 = 4.191395819E-09 / Linear projection matrix CD2_2 = 2.955107441E-05 / Linear projection matrix END CRPIX1 = -9.938501417E+01 / Reference pixel on this axis CRPIX2 = -6.612750568E+01 / Reference pixel on this axis CD1_1 = -2.958627387E-05 / Linear projection matrix CD1_2 = -8.409519190E-08 / Linear projection matrix CD2_1 = -8.860875724E-08 / Linear projection matrix CD2_2 = 2.960509817E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/HAWKI@VLT.ini000066400000000000000000000016421417631501300202610ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=HAWKI@VLT INSTSHORT=HAWKI # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.1064 GAIN=1.705 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048) # Reference pixels for each chip. REFPIXX=([1]=2163 [2]=-37 [3]=2158 [4]=-42) REFPIXY=([1]=2164 [2]=2161 [3]=-25 [4]=-28) TYPE=NIR THELI-3.1.3/config/instruments/HAWKI@VLT_1.reg000066400000000000000000000001771417631501300205010ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(17,2040,2037,2040,2034,18,20.10742,15.10742) THELI-3.1.3/config/instruments/HAWKI@VLT_2.reg000066400000000000000000000002431417631501300204740ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(17,2037,1968,2039,2031,1959,2034,51,1986,18,1635,15,1586,51,1547,17,52,17,14,55) THELI-3.1.3/config/instruments/HAWKI@VLT_3.reg000066400000000000000000000002071417631501300204750ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(17,2040,2037,2040,2034,48,1985,18,20.10742,15.10742) THELI-3.1.3/config/instruments/HAWKI@VLT_4.reg000066400000000000000000000001771417631501300205040ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(17,2040,2032,2040,2034,18,20.10742,15.10742) THELI-3.1.3/config/instruments/HDI@KPNO_0.9m.ini000066400000000000000000000006631417631501300206710ustar00rootroot00000000000000INSTRUMENT=HDI@KPNO_0.9m NCHIPS=1 # Geographic location OBSLAT=31.95 OBSLONG=-111.6 # Plate scale PIXSCALE=0.425 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=4100) OVSCANX2=([1]=4150) OVSCANY1=([1]=4120) OVSCANY2=([1]=4150) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=4096) SIZEY=([1]=4111) REFPIXX=([1]=2048) REFPIXY=([1]=2055) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/HSC@SUBARU.ini000066400000000000000000000173521417631501300203740ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=HSC@SUBARU INSTSHORT=HSC # Number of chips NCHIPS=104 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.17 GAIN=3.0 # Overscan regions. (set internally) OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0 [37]=0 [38]=0 [39]=0 [40]=0 [41]=0 [42]=0 [43]=0 [44]=0 [45]=0 [46]=0 [47]=0 [48]=0 [49]=0 [50]=0 [51]=0 [52]=0 [53]=0 [54]=0 [55]=0 [56]=0 [57]=0 [58]=0 [59]=0 [60]=0 [61]=0 [62]=0 [63]=0 [64]=0 [65]=0 [66]=0 [67]=0 [68]=0 [69]=0 [70]=0 [71]=0 [72]=0 [73]=0 [74]=0 [75]=0 [76]=0 [77]=0 [78]=0 [79]=0 [80]=0 [81]=0 [82]=0 [83]=0 [84]=0 [85]=0 [86]=0 [87]=0 [88]=0 [89]=0 [90]=0 [91]=0 [92]=0 [93]=0 [94]=0 [95]=0 [96]=0 [97]=0 [98]=0 [99]=0 [100]=0 [101]=0 [102]=0 [103]=0 [104]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0 [37]=0 [38]=0 [39]=0 [40]=0 [41]=0 [42]=0 [43]=0 [44]=0 [45]=0 [46]=0 [47]=0 [48]=0 [49]=0 [50]=0 [51]=0 [52]=0 [53]=0 [54]=0 [55]=0 [56]=0 [57]=0 [58]=0 [59]=0 [60]=0 [61]=0 [62]=0 [63]=0 [64]=0 [65]=0 [66]=0 [67]=0 [68]=0 [69]=0 [70]=0 [71]=0 [72]=0 [73]=0 [74]=0 [75]=0 [76]=0 [77]=0 [78]=0 [79]=0 [80]=0 [81]=0 [82]=0 [83]=0 [84]=0 [85]=0 [86]=0 [87]=0 [88]=0 [89]=0 [90]=0 [91]=0 [92]=0 [93]=0 [94]=0 [95]=0 [96]=0 [97]=0 [98]=0 [99]=0 [100]=0 [101]=0 [102]=0 [103]=0 [104]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. #PLACEHOLDERS! These are set internally CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1 [11]=1 [12]=1 [13]=1 [14]=1 [15]=1 [16]=1 [17]=1 [18]=1 [19]=1 [20]=1 [21]=1 [22]=1 [23]=1 [24]=1 [25]=1 [26]=1 [27]=1 [28]=1 [29]=1 [30]=1 [31]=1 [32]=1 [33]=1 [34]=1 [35]=1 [36]=1 [37]=1 [38]=1 [39]=1 [40]=1 [41]=1 [42]=1 [43]=1 [44]=1 [45]=1 [46]=1 [47]=1 [48]=1 [49]=1 [50]=1 [51]=1 [52]=1 [53]=1 [54]=1 [55]=1 [56]=1 [57]=1 [58]=1 [59]=1 [60]=1 [61]=1 [62]=1 [63]=1 [64]=1 [65]=1 [66]=1 [67]=1 [68]=1 [69]=1 [70]=1 [71]=1 [72]=1 [73]=1 [74]=1 [75]=1 [76]=1 [77]=1 [78]=1 [79]=1 [80]=1 [81]=1 [82]=1 [83]=1 [84]=1 [85]=1 [86]=1 [87]=1 [88]=1 [89]=1 [90]=1 [91]=1 [92]=1 [93]=1 [94]=1 [95]=1 [96]=1 [97]=1 [98]=1 [99]=1 [100]=1 [101]=1 [102]=1 [103]=1 [104]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1 [11]=1 [12]=1 [13]=1 [14]=1 [15]=1 [16]=1 [17]=1 [18]=1 [19]=1 [20]=1 [21]=1 [22]=1 [23]=1 [24]=1 [25]=1 [26]=1 [27]=1 [28]=1 [29]=1 [30]=1 [31]=1 [32]=1 [33]=1 [34]=1 [35]=1 [36]=1 [37]=1 [38]=1 [39]=1 [40]=1 [41]=1 [42]=1 [43]=1 [44]=1 [45]=1 [46]=1 [47]=1 [48]=1 [49]=1 [50]=1 [51]=1 [52]=1 [53]=1 [54]=1 [55]=1 [56]=1 [57]=1 [58]=1 [59]=1 [60]=1 [61]=1 [62]=1 [63]=1 [64]=1 [65]=1 [66]=1 [67]=1 [68]=1 [69]=1 [70]=1 [71]=1 [72]=1 [73]=1 [74]=1 [75]=1 [76]=1 [77]=1 [78]=1 [79]=1 [80]=1 [81]=1 [82]=1 [83]=1 [84]=1 [85]=1 [86]=1 [87]=1 [88]=1 [89]=1 [90]=1 [91]=1 [92]=1 [93]=1 [94]=1 [95]=1 [96]=1 [97]=1 [98]=1 [99]=1 [100]=1 [101]=1 [102]=1 [103]=1 [104]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048 [9]=2048 [10]=2048 [11]=2048 [12]=2048 [13]=2048 [14]=2048 [15]=2048 [16]=2048 [17]=2048 [18]=2048 [19]=2048 [20]=2048 [21]=2048 [22]=2048 [23]=2048 [24]=2048 [25]=2048 [26]=2048 [27]=2048 [28]=2048 [29]=2048 [30]=2048 [31]=2048 [32]=2048 [33]=2048 [34]=2048 [35]=2048 [36]=2048 [37]=2048 [38]=2048 [39]=2048 [40]=2048 [41]=2048 [42]=2048 [43]=2048 [44]=2048 [45]=2048 [46]=2048 [47]=2048 [48]=2048 [49]=2048 [50]=2048 [51]=2048 [52]=2048 [53]=2048 [54]=2048 [55]=2048 [56]=2048 [57]=2048 [58]=2048 [59]=2048 [60]=2048 [61]=2048 [62]=2048 [63]=2048 [64]=2048 [65]=2048 [66]=2048 [67]=2048 [68]=2048 [69]=2048 [70]=2048 [71]=2048 [72]=2048 [73]=2048 [74]=2048 [75]=2048 [76]=2048 [77]=2048 [78]=2048 [79]=2048 [80]=2048 [81]=2048 [82]=2048 [83]=2048 [84]=2048 [85]=2048 [86]=2048 [87]=2048 [88]=2048 [89]=2048 [90]=2048 [91]=2048 [92]=2048 [93]=2048 [94]=2048 [95]=2048 [96]=2048 [97]=2048 [98]=2048 [99]=2048 [100]=2048 [101]=2048 [102]=2048 [103]=2048 [104]=2048) SIZEY=([1]=4224 [2]=4224 [3]=4224 [4]=4224 [5]=4224 [6]=4224 [7]=4224 [8]=4224 [9]=4224 [10]=4224 [11]=4224 [12]=4224 [13]=4224 [14]=4224 [15]=4224 [16]=4224 [17]=4224 [18]=4224 [19]=4224 [20]=4224 [21]=4224 [22]=4224 [23]=4224 [24]=4224 [25]=4224 [26]=4224 [27]=4224 [28]=4224 [29]=4224 [30]=4224 [31]=4224 [32]=4224 [33]=4224 [34]=4224 [35]=4224 [36]=4224 [37]=4224 [38]=4224 [39]=4224 [40]=4224 [41]=4224 [42]=4224 [43]=4224 [44]=4224 [45]=4224 [46]=4224 [47]=4224 [48]=4224 [49]=4224 [50]=4224 [51]=4224 [52]=4224 [53]=4224 [54]=4224 [55]=4224 [56]=4224 [57]=4224 [58]=4224 [59]=4224 [60]=4224 [61]=4224 [62]=4224 [63]=4224 [64]=4224 [65]=4224 [66]=4224 [67]=4224 [68]=4224 [69]=4224 [70]=4224 [71]=4224 [72]=4224 [73]=4224 [74]=4224 [75]=4224 [76]=4224 [77]=4224 [78]=4224 [79]=4224 [80]=4224 [81]=4224 [82]=4224 [83]=4224 [84]=4224 [85]=4224 [86]=4224 [87]=4224 [88]=4224 [89]=4224 [90]=4224 [91]=4224 [92]=4224 [93]=4224 [94]=4224 [95]=4224 [96]=4224 [97]=4224 [98]=4224 [99]=4224 [100]=4224 [101]=4224 [102]=4224 [103]=4224 [104]=4224) # Reference pixels for each chip. REFPIXX=([1]=-13834 [2]=-13834 [3]=-13834 [4]=-13834 [5]=-11711 [6]=-11711 [7]=-11711 [8]=-11711 [9]=-11711 [10]=-11711 [11]=-9588 [12]=-9588 [13]=-9588 [14]=-9588 [15]=-9588 [16]=-9588 [17]=9515 [18]=9515 [19]=9515 [20]=-7466 [21]=-7466 [22]=-7466 [23]=7392 [24]=7392 [25]=7392 [26]=7392 [27]=-5343 [28]=-5343 [29]=-5343 [30]=-5343 [31]=5269 [32]=5269 [33]=5269 [34]=5269 [35]=-3220 [36]=-3220 [37]=-3220 [38]=-3220 [39]=3147 [40]=3147 [41]=3147 [42]=3147 [43]=-1098 [44]=-1098 [45]=-1098 [46]=-1098 [47]=1024 [48]=1024 [49]=1024 [50]=1024 [51]=1024 [52]=1024 [53]=1024 [54]=1024 [55]=-1098 [56]=-1098 [57]=-1098 [58]=-1098 [59]=3147 [60]=3147 [61]=3147 [62]=3147 [63]=-3220 [64]=-3220 [65]=-3220 [66]=-3220 [67]=5269 [68]=5269 [69]=5269 [70]=5269 [71]=-5343 [72]=-5343 [73]=-5343 [74]=-5343 [75]=7392 [76]=7392 [77]=7392 [78]=7392 [79]=-7466 [80]=-7466 [81]=-7466 [82]=9515 [83]=9515 [84]=9515 [85]=-9588 [86]=-9588 [87]=-9588 [88]=-9588 [89]=-9588 [90]=-9588 [91]=-11711 [92]=-11711 [93]=-11711 [94]=-11711 [95]=-11711 [96]=-11711 [97]=-13834 [98]=-13834 [99]=-13834 [100]=-13834 [101]=-13308 [102]=15624 [103]=15357 [104]=-13575) REFPIXY=([1]=-4542 [2]=-73 [3]=4395 [4]=8863 [5]=-9010 [6]=-4542 [7]=-73 [8]=4395 [9]=8863 [10]=13332 [11]=-9010 [12]=-4542 [13]=-73 [14]=4395 [15]=8863 [16]=13332 [17]=13065 [18]=8597 [19]=4128 [20]=4395 [21]=8863 [22]=13332 [23]=17534 [24]=13065 [25]=8597 [26]=4128 [27]=4395 [28]=8863 [29]=13332 [30]=17801 [31]=17534 [32]=13065 [33]=8597 [34]=4128 [35]=4395 [36]=8863 [37]=13332 [38]=17801 [39]=17534 [40]=13065 [41]=8597 [42]=4128 [43]=4395 [44]=8863 [45]=13332 [46]=17801 [47]=17534 [48]=13065 [49]=8597 [50]=4128 [51]=4395 [52]=8863 [53]=13332 [54]=17801 [55]=17534 [56]=13065 [57]=8597 [58]=4128 [59]=4395 [60]=8863 [61]=13332 [62]=17801 [63]=17534 [64]=13065 [65]=8597 [66]=4128 [67]=4395 [68]=8863 [69]=13332 [70]=17801 [71]=17534 [72]=13065 [73]=8597 [74]=4128 [75]=4395 [76]=8863 [77]=13332 [78]=17801 [79]=13065 [80]=8597 [81]=4128 [82]=4395 [83]=8863 [84]=13332 [85]=13065 [86]=8597 [87]=4128 [88]=-340 [89]=-4808 [90]=-9277 [91]=13065 [92]=8597 [93]=4128 [94]=-340 [95]=-4808 [96]=-9277 [97]=8597 [98]=4128 [99]=-340 [100]=-4808 [101]=11691 [102]=11691 [103]=11691 [104]=11691) TYPE=OPT THELI-3.1.3/config/instruments/HSC@SUBARU.reg000066400000000000000000000001661417631501300203650ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(8.0,4212.0,2039.0,4212.0,2039.0,8.0,8.0,8.0) THELI-3.1.3/config/instruments/HSC@SUBARU_1.reg000066400000000000000000000002351417631501300206020ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(1021.9673,4224.1638,1538.0895,4224.1638,1542.9882,-12.120265,1019.9664,-20.169034) THELI-3.1.3/config/instruments/HSC@SUBARU_10.reg000066400000000000000000000001571417631501300206650ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(517,4229,2065,4241,2061,1989,521,393) THELI-3.1.3/config/instruments/HSC@SUBARU_100.reg000066400000000000000000000002321417631501300207370ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(1344.036,4296.2746,2719.8911,4323.8106,2719.8911,3100.4622,2132.2225,2807.9223) THELI-3.1.3/config/instruments/HSC@SUBARU_101.reg000066400000000000000000000002371417631501300207450ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-19.232008,38.649621,2105.2708,2979.3456,2101.2699,-113.38636,-26.841912,-116.99532) THELI-3.1.3/config/instruments/HSC@SUBARU_102.reg000066400000000000000000000002361417631501300207450ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-23.248106,3617.3561,2225.2841,424.60038,2105.2557,-119.52841,-67.258523,-195.5464) THELI-3.1.3/config/instruments/HSC@SUBARU_103.reg000066400000000000000000000002631417631501300207460ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-35.250947,2889.1837,2109.2566,208.54924,2241.2879,520.62311,2093.2528,-139.53314,-39.251894,-111.52652) THELI-3.1.3/config/instruments/HSC@SUBARU_104.reg000066400000000000000000000002611417631501300207450ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-63.257576,540.62784,912.97348,1736.911,2105.2557,3629.3589,2168.984,-43.223542,-54.968807,-43.223542) THELI-3.1.3/config/instruments/HSC@SUBARU_23.reg000066400000000000000000000002541417631501300206670ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-53.255682,1514.9678,1027,1006.8475,2139.2633,682.77083,2083.25,-73.408144,-61.257576,-73.408144) THELI-3.1.3/config/instruments/HSC@SUBARU_30.reg000066400000000000000000000002621417631501300206640ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-34.85473,928.32348,2101.2547,1844.9366,2099.2225,-86.403409,1996.8339,-1103.3651,-34.85473,-1103.3651) THELI-3.1.3/config/instruments/HSC@SUBARU_31.reg000066400000000000000000000002361417631501300206660ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-43.237689,872.89394,2117.2737,180.73011,2152.9199,-243.00797,-759.0449,-243.00797) THELI-3.1.3/config/instruments/HSC@SUBARU_38.reg000066400000000000000000000002361417631501300206750ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-64.266098,541.77652,2120.2509,1185.929,2143.9674,-214.11327,-119.99016,-214.11327) THELI-3.1.3/config/instruments/HSC@SUBARU_46.reg000066400000000000000000000002641417631501300206750ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-99.981939,545.48478,2200.2699,1045.8958,2328.3002,-74.369318,1115.7206,-670.21773,-99.981939,-670.21773) THELI-3.1.3/config/instruments/HSC@SUBARU_5.reg000066400000000000000000000003001417631501300205770ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(701.21399,4249.215,2068.9565,4249.215,2085.2509,2201.0208,1438.0739,2930.0294,825.92898,3558.178,57.747159,4266.3456) THELI-3.1.3/config/instruments/HSC@SUBARU_62.reg000066400000000000000000000002361417631501300206720ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-136.28314,677.87121,2220.2746,393.80398,2047.8265,-666.03955,-88.27178,-170.32955) THELI-3.1.3/config/instruments/HSC@SUBARU_63.reg000066400000000000000000000002371417631501300206740ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-74.252841,457.85038,2190.2831,1114.0057,2170.2784,-74.275568,-66.250947,-106.28314) THELI-3.1.3/config/instruments/HSC@SUBARU_70.reg000066400000000000000000000002361417631501300206710ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-102.32197,1088.9451,2122.2045,516.80966,2138.0265,-1195.4138,-62.13067,-1195.4138) THELI-3.1.3/config/instruments/HSC@SUBARU_71.reg000066400000000000000000000002371417631501300206730ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-73.291667,635.84564,2138.8435,1499.6616,2138.8435,-788.10293,-148.92111,-788.10293) THELI-3.1.3/config/instruments/HSC@SUBARU_78.reg000066400000000000000000000002371417631501300207020ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-85.858575,1818.6739,2114.2652,942.86364,2114.2652,-169.39962,-85.858575,-197.00914) THELI-3.1.3/config/instruments/HSC@SUBARU_9.reg000066400000000000000000000002531417631501300206120ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(517.31368,4233.068,2036.8056,4233.068,2062.268,2306.1004,2010.2557,2222.0805,525.90436,753.73295) THELI-3.1.3/config/instruments/HSC@SUBARU_91.reg000066400000000000000000000002371417631501300206750ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-51.270833,20.692235,2157.2519,2309.2339,2264.8006,-2175.3507,-46.792977,-2175.3507) THELI-3.1.3/config/instruments/HSC@SUBARU_96.reg000066400000000000000000000002341417631501300206770ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(-91.988438,4711.9951,2292.0074,4711.9951,2096.2453,1735.5748,-88.27178,3976.1051) THELI-3.1.3/config/instruments/HSC@SUBARU_97.reg000066400000000000000000000002361417631501300207020ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(692.41153,-12.868915,2228.2453,2208.1866,2579.7987,-1900.2561,692.41153,-1900.2561) THELI-3.1.3/config/instruments/IMACS_F2_200404-2008@LCO.ini000066400000000000000000000022461417631501300217520ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=IMACS_F2_200404-2008@LCO INSTSHORT=IMACS # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.2015 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=2 [2]=2 [3]=2 [4]=2 [5]=66 [6]=66 [7]=66 [8]=66) CUTY=([1]=62 [2]=62 [3]=62 [4]=62 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=2045 [2]=2045 [3]=2045 [4]=2045 [5]=2045 [6]=2045 [7]=2045 [8]=2045) SIZEY=([1]=4095 [2]=4095 [3]=4095 [4]=4095 [5]=4095 [6]=4095 [7]=4095 [8]=4095) # Reference pixels for each chip. REFPIXX=([1]=4219 [2]=2093 [3]=-44 [4]=-2166 [5]=2092 [6]=4222 [7]=-2165 [8]=-45) REFPIXY=([1]=-23 [2]=-25 [3]=-27 [4]=-22 [5]=4129 [6]=4126 [7]=4122 [8]=4124) TYPE=OPT THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO.ini000066400000000000000000000023151417631501300223360ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=IMACS_F2_2008-today@LCO INSTSHORT=IMACS # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.199 GAIN=1.45 # Overscan regions. OVSCANX1=([1]=2060 [2]=2060 [3]=2060 [4]=2060 [5]=2060 [6]=2060 [7]=2060 [8]=2060) OVSCANX2=([1]=2090 [2]=2090 [3]=2090 [4]=2090 [5]=2090 [6]=2090 [7]=2090 [8]=2090) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048) SIZEY=([1]=4096 [2]=4096 [3]=4096 [4]=4096 [5]=4096 [6]=4096 [7]=4096 [8]=4096) # Reference pixels for each chip. REFPIXX=([1]=4233 [2]=2095 [3]=-46 [4]=-2187 [5]=-45 [6]=-2188 [7]=4236 [8]=2097) REFPIXY=([1]=4130 [2]=4130 [3]=4130 [4]=4130 [5]=4130 [6]=4130 [7]=4130 [8]=4130) TYPE=OPT THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_1.reg000066400000000000000000000001131417631501300225460ustar00rootroot00000000000000# Region file format: DS9 version 4.1 circle(4380.5494,4276.4293,4655.621) THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_2.reg000066400000000000000000000003041417631501300225510ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(-12.664198,4114.0004,2063.1599,4110.4864,2080.5591,56.685078,607.70349,60.655039,282.16667,211.51357,-23.520349,457.65116) THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_3.reg000066400000000000000000000003301417631501300225510ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(-12.664198,4114.0004,2063.1599,4110.4864,2074.5891,474.49225,1848.3014,275.99419,1518.7946,89.406008,1193.2578,41.766473,-13.610465,41.766473) THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_4.reg000066400000000000000000000001141417631501300225520ustar00rootroot00000000000000# Region file format: DS9 version 4.1 circle(-2582.7626,4121.6008,4655.621) THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_5.reg000066400000000000000000000003301417631501300225530ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(-12.664198,4114.0004,2063.1599,4110.4864,2074.5891,474.49225,1848.3014,275.99419,1743.3527,211.75388,1417.8159,160.14438,-19.310078,156.17442) THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_6.reg000066400000000000000000000001141417631501300225540ustar00rootroot00000000000000# Region file format: DS9 version 4.1 circle(-2344.5649,4355.8285,4655.621) THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_7.reg000066400000000000000000000001131417631501300225540ustar00rootroot00000000000000# Region file format: DS9 version 4.1 circle(4459.9486,4343.9186,4655.621) THELI-3.1.3/config/instruments/IMACS_F2_2008-today@LCO_8.reg000066400000000000000000000003031417631501300225560ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(-12.664198,4114.0004,2063.1599,4110.4864,2074.8295,29.616279,820.32171,109.0155,363.77616,295.60368,-17.340116,557.62112) THELI-3.1.3/config/instruments/IMACS_F4_200404-2012@LCO.ini000066400000000000000000000022431417631501300217440ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=IMACS_F4_200404-2012@LCO INSTSHORT=IMACS # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.111 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=2 [2]=2 [3]=2 [4]=2 [5]=66 [6]=66 [7]=66 [8]=66) CUTY=([1]=62 [2]=62 [3]=62 [4]=62 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=2045 [2]=2045 [3]=2045 [4]=2045 [5]=2045 [6]=2045 [7]=2045 [8]=2045) SIZEY=([1]=4095 [2]=4095 [3]=4095 [4]=4095 [5]=4095 [6]=4095 [7]=4095 [8]=4095) # Reference pixels for each chip. REFPIXX=([1]=4219 [2]=2093 [3]=-44 [4]=-2166 [5]=2092 [6]=4222 [7]=-2165 [8]=-45) REFPIXY=([1]=-23 [2]=-25 [3]=-27 [4]=-22 [5]=4129 [6]=4126 [7]=4122 [8]=4124) TYPE=OPT THELI-3.1.3/config/instruments/IMACS_F4_2012-today@LCO.ini000066400000000000000000000023041417631501300223310ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=IMACS_F4_2012-today@LCO INSTSHORT=IMACS # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.1104 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2060 [2]=2060 [3]=2060 [4]=2060 [5]=2060 [6]=2060 [7]=2060 [8]=2060) OVSCANX2=([1]=2090 [2]=2090 [3]=2090 [4]=2090 [5]=2090 [6]=2090 [7]=2090 [8]=2090) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048) SIZEY=([1]=4096 [2]=4096 [3]=4096 [4]=4096 [5]=4096 [6]=4096 [7]=4096 [8]=4096) # Reference pixels for each chip. REFPIXX=([1]=4233 [2]=2095 [3]=-46 [4]=-2187 [5]=-45 [6]=-2188 [7]=4236 [8]=2097) REFPIXY=([1]=4130 [2]=4130 [3]=4130 [4]=4130 [5]=4130 [6]=4130 [7]=4130 [8]=4130) TYPE=OPT THELI-3.1.3/config/instruments/IMACS_F4_2012-today_2x2@LCO.ini000066400000000000000000000023071417631501300230270ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=IMACS_F4_2012-today_2x2@LCO INSTSHORT=IMACS # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.2208 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=1030 [2]=1030 [3]=1030 [4]=1030 [5]=1030 [6]=1030 [7]=1030 [8]=1030) OVSCANX2=([1]=1080 [2]=1080 [3]=1080 [4]=1080 [5]=1080 [6]=1080 [7]=1080 [8]=1080) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=1024 [2]=1024 [3]=1024 [4]=1024 [5]=1024 [6]=1024 [7]=1024 [8]=1024) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048) # Reference pixels for each chip. REFPIXX=([1]=2166 [2]=1040 [3]=-23 [4]=-1090 [5]=-22 [6]=-1090 [7]=2118 [8]=1046) REFPIXY=([1]=2070 [2]=2070 [3]=2070 [4]=2070 [5]=2070 [6]=2070 [7]=2070 [8]=2070) TYPE=OPT THELI-3.1.3/config/instruments/INGRID@WHT.ini000066400000000000000000000013561417631501300203710ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=INGRID@WHT INSTSHORT=INGRID # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.04 GAIN=5.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/INOLA@INO.ini000066400000000000000000000006441417631501300202410ustar00rootroot00000000000000INSTRUMENT=INOLA@INO NCHIPS=1 # Geographic location OBSLAT=33.674 OBSLONG=51.319 # Plate scale PIXSCALE=2.846 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0) OVSCANX2=([1]=0) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=3352) SIZEY=([1]=2532) REFPIXX=([1]=1700) REFPIXY=([1]=1260) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/IRCS_HIGHRES@SUBARU.ini000066400000000000000000000014051417631501300216600ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=IRCS_HIGHRES@SUBARU INSTSHORT=IRCS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.02091 GAIN=5.6 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=NIRMIR THELI-3.1.3/config/instruments/IRCS_LOWRES@SUBARU.ini000066400000000000000000000014031417631501300216000ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=IRCS_LOWRES@SUBARU INSTSHORT=IRCS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.05242 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=NIRMIR THELI-3.1.3/config/instruments/ISAAC@VLT.ini000066400000000000000000000013601417631501300202330ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ISAAC@VLT INSTSHORT=ISAAC # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.148 GAIN=4.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=504) REFPIXY=([1]=491) TYPE=NIRMIR THELI-3.1.3/config/instruments/ISPI@CTIO.ini000066400000000000000000000013671417631501300202570ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=ISPI@CTIO INSTSHORT=ISPI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.30 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) # Camera type TYPE=NIR THELI-3.1.3/config/instruments/KTMC@CTIO.ini000066400000000000000000000032511417631501300202430ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=KTMC@CTIO INSTSHORT=KTMC # Number of chips NCHIPS=16 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.3971 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=3 [7]=3 [8]=3 [9]=3 [10]=3 [11]=3 [12]=3 [13]=3 [14]=3 [15]=3 [16]=3) CUTY=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=3 [7]=3 [8]=3 [9]=3 [10]=3 [11]=3 [12]=3 [13]=3 [14]=3 [15]=3 [16]=3) SIZEX=([1]=4605 [2]=4605 [3]=4605 [4]=4605 [5]=4605 [6]=4605 [7]=4605 [8]=4605 [9]=4605 [10]=4605 [11]=4605 [12]=4605 [13]=4605 [14]=4605 [15]=4605 [16]=4605) SIZEY=([1]=4612 [2]=4612 [3]=4612 [4]=4612 [5]=4612 [6]=4612 [7]=4612 [8]=4612 [9]=4612 [10]=4612 [11]=4612 [12]=4612 [13]=4612 [14]=4612 [15]=4612 [16]=4612) # Reference pixels for each chip. REFPIXX=([1]=1000 [2]=1000 [3]=1000 [4]=1000 [5]=1000 [6]=1000 [7]=1000 [8]=1000 [9]=1000 [10]=1000 [11]=1000 [12]=1000 [13]=1000 [14]=1000 [15]=1000 [16]=1000) REFPIXY=([1]=1000 [2]=1000 [3]=1000 [4]=1000 [5]=1000 [6]=1000 [7]=1000 [8]=1000 [9]=1000 [10]=1000 [11]=1000 [12]=1000 [13]=1000 [14]=1000 [15]=1000 [16]=1000) TYPE=OPT THELI-3.1.3/config/instruments/KTMC@CTIO_14.reg000066400000000000000000000001461417631501300205450ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(4604,4613,-2,4615,7,3) THELI-3.1.3/config/instruments/KTMC@CTIO_3.reg000066400000000000000000000001451417631501300204620ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(4604,4613,4602,3,7,3) THELI-3.1.3/config/instruments/KTMC@CTIO_8.reg000066400000000000000000000001441417631501300204660ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(4606,-1,-2,4615,7,3) THELI-3.1.3/config/instruments/KTMC@CTIO_9.reg000066400000000000000000000001521417631501300204660ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(4606,-1,-2,4615,4606,4615) THELI-3.1.3/config/instruments/LAICA@CAHA.ini000066400000000000000000000016521417631501300202570ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LAICA@CAHA INSTSHORT=LAICA # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=37.22 OBSLONG=-2.55 # Pixel scale in arcsec PIXSCALE=0.225 GAIN=2.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=54 [2]=54 [3]=54 [4]=54) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=4092 [2]=4092 [3]=4092 [4]=4092) SIZEY=([1]=4092 [2]=4092 [3]=4092 [4]=4092) # Reference pixels for each chip. REFPIXX=([1]=5120 [2]=-1120 [3]=-1120 [4]=5120) REFPIXY=([1]=-2000 [2]=-2000 [3]=4000 [4]=4000) TYPE=OPT THELI-3.1.3/config/instruments/LAICA_2x2@CAHA.ini000066400000000000000000000016541417631501300207540ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LAICA_2x2@CAHA INSTSHORT=LAICA # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=37.22 OBSLONG=-2.55 # Pixel scale in arcsec PIXSCALE=0.450 GAIN=2.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=27 [2]=27 [3]=27 [4]=27) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2046 [2]=2046 [3]=2046 [4]=2046) SIZEY=([1]=2046 [2]=2046 [3]=2046 [4]=2046) # Reference pixels for each chip. REFPIXX=([1]=2560 [2]=-560 [3]=-560 [4]=2560) REFPIXY=([1]=-1000 [2]=-1000 [3]=3000 [4]=3000) TYPE=OPT THELI-3.1.3/config/instruments/LBC_BLUE@LBT.ahead000066400000000000000000000036441417631501300210700ustar00rootroot00000000000000CRPIX1 = -1.179662612E+03 / Reference pixel on this axis CRPIX2 = 3.249827962E+03 / Reference pixel on this axis CD1_1 = -6.220900701E-05 / Linear projection matrix CD1_2 = -1.272499790E-08 / Linear projection matrix CD2_1 = 1.666025317E-07 / Linear projection matrix CD2_2 = 6.261956676E-05 / Linear projection matrix END CRPIX1 = 9.599727493E+02 / Reference pixel on this axis CRPIX2 = 3.248247545E+03 / Reference pixel on this axis CD1_1 = -6.298412615E-05 / Linear projection matrix CD1_2 = 1.072999667E-07 / Linear projection matrix CD2_1 = 7.466442381E-08 / Linear projection matrix CD2_2 = 6.287291726E-05 / Linear projection matrix END CRPIX1 = 3.101321775E+03 / Reference pixel on this axis CRPIX2 = 3.248734886E+03 / Reference pixel on this axis CD1_1 = -6.222296026E-05 / Linear projection matrix CD1_2 = 2.105237344E-07 / Linear projection matrix CD2_1 = 1.112567528E-07 / Linear projection matrix CD2_2 = 6.267872206E-05 / Linear projection matrix END CRPIX1 = -1.458349710E+03 / Reference pixel on this axis CRPIX2 = 2.292035557E+03 / Reference pixel on this axis CD1_1 = 1.090416180E-07 / Linear projection matrix CD1_2 = 6.247531752E-05 / Linear projection matrix CD2_1 = 6.178509750E-05 / Linear projection matrix CD2_2 = -1.741228684E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/LBC_BLUE@LBT.ini000066400000000000000000000017111417631501300205760ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LBC_BLUE@LBT INSTSHORT=LBC_BLUE # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=32.70 OBSLONG=-109.89 # Pixel scale in arcsec PIXSCALE=0.2240 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2100 [2]=2100 [3]=2100 [4]=2100) OVSCANX2=([1]=2300 [2]=2300 [3]=2300 [4]=2300) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=51 [2]=51 [3]=51 [4]=51) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=4608 [2]=4608 [3]=4608 [4]=4608) # Reference pixels for each chip. REFPIXX=([1]=-1079 [2]=1043 [3]=3165 [4]=-1683) REFPIXY=([1]=2950 [2]=2950 [3]=2950 [4]=2264) TYPE=OPT THELI-3.1.3/config/instruments/LBC_RED@LBT.ini000066400000000000000000000017061417631501300204650ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LBC_RED@LBT INSTSHORT=LBC_RED # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=32.70 OBSLONG=-109.89 # Pixel scale in arcsec PIXSCALE=0.2240 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2100 [2]=2100 [3]=2100 [4]=2100) OVSCANX2=([1]=2300 [2]=2300 [3]=2300 [4]=2300) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=51 [2]=51 [3]=51 [4]=51) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=4608 [2]=4608 [3]=4608 [4]=4608) # Reference pixels for each chip. REFPIXX=([1]=-1079 [2]=1043 [3]=3165 [4]=-1683) REFPIXY=([1]=2950 [2]=2950 [3]=2950 [4]=2264) TYPE=OPT THELI-3.1.3/config/instruments/LDSS3_2004-201401@LCO.ahead000066400000000000000000000017221417631501300216720ustar00rootroot00000000000000CRPIX1 = 2.031560826E+03 / Reference pixel on this axis CRPIX2 = 2.016204035E+03 / Reference pixel on this axis CD1_1 = -5.232177091E-05 / Linear projection matrix CD1_2 = 1.153853116E-08 / Linear projection matrix CD2_1 = -1.038852589E-07 / Linear projection matrix CD2_2 = 5.245133255E-05 / Linear projection matrix END CRPIX1 = 2.027276541E+03 / Reference pixel on this axis CRPIX2 = -1.282021246E+01 / Reference pixel on this axis CD1_1 = -5.225156641E-05 / Linear projection matrix CD1_2 = 1.074800917E-07 / Linear projection matrix CD2_1 = -8.503109529E-08 / Linear projection matrix CD2_2 = 5.231982815E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/LDSS3_2004-201401@LCO.ini000066400000000000000000000014671417631501300214150ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LDSS3_2004-201401@LCO INSTSHORT=LDSS3 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.188 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=4064 [2]=4064) OVSCANX2=([1]=4180 [2]=4180) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1) CUTY=([1]=1 [2]=129) SIZEX=([1]=4062 [2]=4062) SIZEY=([1]=2030 [2]=2030) # Reference pixels for each chip. REFPIXX=([1]=1960 [2]=2160) REFPIXY=([1]=1950 [2]=1950) TYPE=OPT THELI-3.1.3/config/instruments/LDSS3_from201402@LCO.ini000066400000000000000000000014711417631501300217120ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LDSS3_from201402@LCO INSTSHORT=LDSS3 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.188 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=1030 [2]=1150) OVSCANX2=([1]=1030 [2]=1150) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=20 [2]=20) CUTY=([1]=810 [2]=810) SIZEX=([1]=1005 [2]=1005) SIZEY=([1]=2620 [2]=2620) # Reference pixels for each chip. REFPIXX=([1]=1004 [2]=1004) REFPIXY=([1]=1310 [2]=1310) TYPE=OPT THELI-3.1.3/config/instruments/LDSS3_from201402@LCO_1.reg000066400000000000000000000001071417631501300221230ustar00rootroot00000000000000# Region file format: DS9 version 4.1 circle(841.72103,1311,1267.6657) THELI-3.1.3/config/instruments/LDSS3_from201402@LCO_2.reg000066400000000000000000000001121417631501300221200ustar00rootroot00000000000000# Region file format: DS9 version 4.1 circle(1161.754,1303.992,1267.6657) THELI-3.1.3/config/instruments/LIRIS@WHT.ini000066400000000000000000000013551417631501300202760ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LIRIS@WHT INSTSHORT=LIRIS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.2504 GAIN=3.6 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/LIRIS@WHT_1.reg000066400000000000000000000006051417631501300205110ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: or polygon(3.0425923,1014.4574,511.5,1013.5,511.5,513.5,3.0425923,512.54259,3.5,715,17,714,18.5,704.5,40.5,702.5,41.5,724,35.5,734.5,19,735.5,17.5,725,17.5,714.5,3.5,715) polygon(515.5,1013.5,1020.5,1014,1022.5,513.5,515,513.5) polygon(514.5,510.5,1022.5,510.5,1021.5,2,515,2.5) polygon(3.5,510.5,512,510.5,511,2,13.5,2,2.5,10) THELI-3.1.3/config/instruments/LIRIS_POL@WHT.ini000066400000000000000000000013471417631501300210110ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LIRIS_POL@WHT INSTSHORT=LIRIS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.251 GAIN=3.6 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=938) SIZEY=([1]=200) # Reference pixels for each chip. REFPIXX=([1]=470) REFPIXY=([1]=100) TYPE=NIR THELI-3.1.3/config/instruments/LORRI@NewHorizons.ini000066400000000000000000000013531417631501300221240ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=LORRI@NewHorizons INSTSHORT=LORRI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=0 OBSLONG=0.0 # Pixel scale in arcsec PIXSCALE=1.0228 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=OPT THELI-3.1.3/config/instruments/LRIS_BLUE@KECK.ahead000066400000000000000000000017101417631501300213250ustar00rootroot00000000000000CRPIX1 = 2.099093260577E+03 / Reference pixel on this axis CRPIX2 = 2.054179360997E+03 / Reference pixel on this axis CD1_1 = 2.466425461054E-07 / Linear projection matrix CD1_2 = -3.768203365806E-05 / Linear projection matrix CD2_1 = 3.757943138981E-05 / Linear projection matrix CD2_2 = 3.094175065481E-07 / Linear projection matrix END CRPIX1 = -5.228730840871E+01 / Reference pixel on this axis CRPIX2 = 2.050341775410E+03 / Reference pixel on this axis CD1_1 = -1.639479613091E-08 / Linear projection matrix CD1_2 = -3.770278168266E-05 / Linear projection matrix CD2_1 = 3.750514621498E-05 / Linear projection matrix CD2_2 = -3.921351020403E-08 / Linear projection matrix END THELI-3.1.3/config/instruments/LRIS_BLUE@KECK.ini000066400000000000000000000010011417631501300210330ustar00rootroot00000000000000INSTRUMENT=LRIS_BLUE@KECK INSTSHORT=LRIS NCHIPS=2 # Geographic location OBSLAT=19.82 OBSLONG=-155.47 # Plate scale PIXSCALE=0.135 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) OVSCANY1=([1]=0 [2]=0) OVSCANY2=([1]=0 [2]=0) CUTX=([1]=1 [2]=1) CUTY=([1]=1 [2]=1) SIZEX=([1]=2048 [2]=2048) SIZEY=([1]=4096 [2]=4096) REFPIXX=([1]=2099 [2]=-52) REFPIXY=([1]=2054 [2]=2050) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/LRIS_BLUE@KECK_1.reg000066400000000000000000000001371417631501300212620ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(332,3233,2070,3231,2069,771,335,773) THELI-3.1.3/config/instruments/LRIS_BLUE@KECK_2.reg000066400000000000000000000002111417631501300212540ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(-3.341637,3225.71,1734.6584,3223.71,1733.6584,763.70996,-0.34163701,765.70996) THELI-3.1.3/config/instruments/LRIS_RED@KECK.ahead000066400000000000000000000017101417631501300212100ustar00rootroot00000000000000CRPIX1 = -1.271997413702E+02 / Reference pixel on this axis CRPIX2 = 1.262795871889E+03 / Reference pixel on this axis CD1_1 = -1.324578732566E-07 / Linear projection matrix CD1_2 = -3.746607019089E-05 / Linear projection matrix CD2_1 = -3.747943171639E-05 / Linear projection matrix CD2_2 = 1.324578732566E-07 / Linear projection matrix END CRPIX1 = 1.832227025450E+03 / Reference pixel on this axis CRPIX2 = 1.258590427722E+03 / Reference pixel on this axis CD1_1 = -9.199897957125E-08 / Linear projection matrix CD1_2 = -3.745487423382E-05 / Linear projection matrix CD2_1 = -3.734522130742E-05 / Linear projection matrix CD2_2 = 1.627714014732E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/LRIS_RED@KECK.ini000066400000000000000000000010011417631501300207160ustar00rootroot00000000000000INSTRUMENT=LRIS_RED@KECK INSTSHORT=LRIS NCHIPS=2 # Geographic location OBSLAT=19.82 OBSLONG=-155.47 # Plate scale PIXSCALE=0.135 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) OVSCANY1=([1]=0 [2]=0) OVSCANY2=([1]=0 [2]=0) CUTX=([1]=1 [2]=1) CUTY=([1]=1 [2]=1) SIZEX=([1]=1648 [2]=1752) SIZEY=([1]=2520 [2]=2520) REFPIXX=([1]=-126 [2]=1835) REFPIXY=([1]=1265 [2]=1260) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/LRIS_RED@KECK_1.reg000066400000000000000000000001621417631501300211430ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(7.1765537,2492.8234,1621,2496,1605,323,1457,161,19,161) THELI-3.1.3/config/instruments/LRIS_RED@KECK_2.reg000066400000000000000000000002131417631501300211410ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(14.689063,2493.9505,1739.5297,2495.4516,1742.9922,150.45104,12.461979,147.21563) THELI-3.1.3/config/instruments/MEGACAM_2x2@LCO.ahead000066400000000000000000000420201417631501300213710ustar00rootroot00000000000000CRPIX1 = -3.788557819869E+03 / Reference pixel on this axis CRPIX2 = 4.880971183068E+03 / Reference pixel on this axis CD1_1 = -2.780227558305E-07 / Linear projection matrix CD1_2 = -4.376598916048E-05 / Linear projection matrix CD2_1 = 4.367248873997E-05 / Linear projection matrix CD2_2 = 3.103734377429E-07 / Linear projection matrix END CRPIX1 = -2.690898347503E+03 / Reference pixel on this axis CRPIX2 = 4.874011163095E+03 / Reference pixel on this axis CD1_1 = -2.910789408862E-07 / Linear projection matrix CD1_2 = -4.383648898953E-05 / Linear projection matrix CD2_1 = 4.388756713363E-05 / Linear projection matrix CD2_2 = 9.943933064125E-08 / Linear projection matrix END CRPIX1 = -1.610755775198E+03 / Reference pixel on this axis CRPIX2 = 4.861334486316E+03 / Reference pixel on this axis CD1_1 = -2.194954523188E-07 / Linear projection matrix CD1_2 = -4.388716548670E-05 / Linear projection matrix CD2_1 = 4.412924952978E-05 / Linear projection matrix CD2_2 = 4.991919115755E-08 / Linear projection matrix END CRPIX1 = -5.447932385322E+02 / Reference pixel on this axis CRPIX2 = 4.852004732563E+03 / Reference pixel on this axis CD1_1 = -7.403261350812E-08 / Linear projection matrix CD1_2 = -4.393268731197E-05 / Linear projection matrix CD2_1 = 4.417273234919E-05 / Linear projection matrix CD2_2 = -1.471827312655E-10 / Linear projection matrix END CRPIX1 = 5.226670020430E+02 / Reference pixel on this axis CRPIX2 = 4.849253280279E+03 / Reference pixel on this axis CD1_1 = -5.089873123744E-08 / Linear projection matrix CD1_2 = -4.393834820441E-05 / Linear projection matrix CD2_1 = 4.420001961032E-05 / Linear projection matrix CD2_2 = -7.758311629535E-08 / Linear projection matrix END CRPIX1 = 1.583300772346E+03 / Reference pixel on this axis CRPIX2 = 4.851400273825E+03 / Reference pixel on this axis CD1_1 = 1.435497445261E-07 / Linear projection matrix CD1_2 = -4.395088832729E-05 / Linear projection matrix CD2_1 = 4.413137089925E-05 / Linear projection matrix CD2_2 = -3.843871648965E-08 / Linear projection matrix END CRPIX1 = 2.666080357523E+03 / Reference pixel on this axis CRPIX2 = 4.853270407068E+03 / Reference pixel on this axis CD1_1 = 5.667085428636E-08 / Linear projection matrix CD1_2 = -4.388003380313E-05 / Linear projection matrix CD2_1 = 4.403915019360E-05 / Linear projection matrix CD2_2 = -2.444768110422E-07 / Linear projection matrix END CRPIX1 = 3.748992693140E+03 / Reference pixel on this axis CRPIX2 = 4.858028985306E+03 / Reference pixel on this axis CD1_1 = 1.185432253001E-07 / Linear projection matrix CD1_2 = -4.382430972276E-05 / Linear projection matrix CD2_1 = 4.382775064100E-05 / Linear projection matrix CD2_2 = -3.339426068662E-07 / Linear projection matrix END CRPIX1 = 4.826165236387E+03 / Reference pixel on this axis CRPIX2 = 4.870279941071E+03 / Reference pixel on this axis CD1_1 = 2.341900354862E-07 / Linear projection matrix CD1_2 = -4.376728012863E-05 / Linear projection matrix CD2_1 = 4.366906962133E-05 / Linear projection matrix CD2_2 = -3.505277025967E-07 / Linear projection matrix END CRPIX1 = -3.768065002575E+03 / Reference pixel on this axis CRPIX2 = 2.322813472669E+03 / Reference pixel on this axis CD1_1 = -1.274358377526E-08 / Linear projection matrix CD1_2 = -4.409124250513E-05 / Linear projection matrix CD2_1 = 4.379220818317E-05 / Linear projection matrix CD2_2 = 2.017041154514E-07 / Linear projection matrix END CRPIX1 = -2.678510192136E+03 / Reference pixel on this axis CRPIX2 = 2.332868968552E+03 / Reference pixel on this axis CD1_1 = -1.978219869592E-07 / Linear projection matrix CD1_2 = -4.418900694220E-05 / Linear projection matrix CD2_1 = 4.403881010223E-05 / Linear projection matrix CD2_2 = -9.093260659997E-08 / Linear projection matrix END CRPIX1 = -1.610422471864E+03 / Reference pixel on this axis CRPIX2 = 2.324032250974E+03 / Reference pixel on this axis CD1_1 = -1.057279487902E-07 / Linear projection matrix CD1_2 = -4.422936218555E-05 / Linear projection matrix CD2_1 = 4.417887221867E-05 / Linear projection matrix CD2_2 = -1.469209927310E-08 / Linear projection matrix END CRPIX1 = -5.485979414433E+02 / Reference pixel on this axis CRPIX2 = 2.317931663538E+03 / Reference pixel on this axis CD1_1 = 4.311338582917E-08 / Linear projection matrix CD1_2 = -4.425815174639E-05 / Linear projection matrix CD2_1 = 4.426864856919E-05 / Linear projection matrix CD2_2 = 9.561682163419E-08 / Linear projection matrix END CRPIX1 = 5.151033288650E+02 / Reference pixel on this axis CRPIX2 = 2.318079385936E+03 / Reference pixel on this axis CD1_1 = 4.682020677370E-08 / Linear projection matrix CD1_2 = -4.429699245610E-05 / Linear projection matrix CD2_1 = 4.430450307712E-05 / Linear projection matrix CD2_2 = 3.327184038046E-08 / Linear projection matrix END CRPIX1 = 1.577709126288E+03 / Reference pixel on this axis CRPIX2 = 2.320447574953E+03 / Reference pixel on this axis CD1_1 = 1.006043443282E-07 / Linear projection matrix CD1_2 = -4.427863734964E-05 / Linear projection matrix CD2_1 = 4.427512153339E-05 / Linear projection matrix CD2_2 = 6.139640840431E-08 / Linear projection matrix END CRPIX1 = 2.642500825759E+03 / Reference pixel on this axis CRPIX2 = 2.325506485070E+03 / Reference pixel on this axis CD1_1 = 1.483540482734E-07 / Linear projection matrix CD1_2 = -4.423318038237E-05 / Linear projection matrix CD2_1 = 4.418515786581E-05 / Linear projection matrix CD2_2 = 3.985592935821E-08 / Linear projection matrix END CRPIX1 = 3.715060042265E+03 / Reference pixel on this axis CRPIX2 = 2.330243476048E+03 / Reference pixel on this axis CD1_1 = 1.889694192033E-07 / Linear projection matrix CD1_2 = -4.417493627378E-05 / Linear projection matrix CD2_1 = 4.400924024812E-05 / Linear projection matrix CD2_2 = 2.715106800646E-08 / Linear projection matrix END CRPIX1 = 4.796502749235E+03 / Reference pixel on this axis CRPIX2 = 2.329157262214E+03 / Reference pixel on this axis CD1_1 = 1.275694793349E-07 / Linear projection matrix CD1_2 = -4.411635629188E-05 / Linear projection matrix CD2_1 = 4.380140895824E-05 / Linear projection matrix CD2_2 = -6.755593215126E-08 / Linear projection matrix END CRPIX1 = 4.788562491563E+03 / Reference pixel on this axis CRPIX2 = 2.335744356640E+03 / Reference pixel on this axis CD1_1 = -2.052493797638E-07 / Linear projection matrix CD1_2 = 4.411524195379E-05 / Linear projection matrix CD2_1 = -4.378844971402E-05 / Linear projection matrix CD2_2 = -1.464600941046E-08 / Linear projection matrix END CRPIX1 = 3.707980150163E+03 / Reference pixel on this axis CRPIX2 = 2.318660388083E+03 / Reference pixel on this axis CD1_1 = -5.101634157102E-08 / Linear projection matrix CD1_2 = 4.421011548390E-05 / Linear projection matrix CD2_1 = -4.401502955644E-05 / Linear projection matrix CD2_2 = 4.523423778186E-08 / Linear projection matrix END CRPIX1 = 2.637642928730E+03 / Reference pixel on this axis CRPIX2 = 2.316911660072E+03 / Reference pixel on this axis CD1_1 = -6.510615410274E-09 / Linear projection matrix CD1_2 = 4.423686318597E-05 / Linear projection matrix CD2_1 = -4.418044429552E-05 / Linear projection matrix CD2_2 = 9.338193575523E-08 / Linear projection matrix END CRPIX1 = 1.570834811629E+03 / Reference pixel on this axis CRPIX2 = 2.318533257491E+03 / Reference pixel on this axis CD1_1 = -6.393441531936E-08 / Linear projection matrix CD1_2 = 4.427926959106E-05 / Linear projection matrix CD2_1 = -4.426740228150E-05 / Linear projection matrix CD2_2 = -2.753811202834E-09 / Linear projection matrix END CRPIX1 = 5.054700626814E+02 / Reference pixel on this axis CRPIX2 = 2.318640700423E+03 / Reference pixel on this axis CD1_1 = -7.396191061630E-08 / Linear projection matrix CD1_2 = 4.427809660441E-05 / Linear projection matrix CD2_1 = -4.429437750343E-05 / Linear projection matrix CD2_2 = -6.651494495569E-08 / Linear projection matrix END CRPIX1 = -5.553937622659E+02 / Reference pixel on this axis CRPIX2 = 2.318727129604E+03 / Reference pixel on this axis CD1_1 = -2.882601721451E-08 / Linear projection matrix CD1_2 = 4.426074968649E-05 / Linear projection matrix CD2_1 = -4.426710127673E-05 / Linear projection matrix CD2_2 = -7.886222510252E-08 / Linear projection matrix END CRPIX1 = -1.618663072219E+03 / Reference pixel on this axis CRPIX2 = 2.324616773755E+03 / Reference pixel on this axis CD1_1 = 1.170309717353E-07 / Linear projection matrix CD1_2 = 4.423810779189E-05 / Linear projection matrix CD2_1 = -4.416625868090E-05 / Linear projection matrix CD2_2 = 9.150888019742E-09 / Linear projection matrix END CRPIX1 = -2.692417586061E+03 / Reference pixel on this axis CRPIX2 = 2.323765931157E+03 / Reference pixel on this axis CD1_1 = 5.200498313820E-08 / Linear projection matrix CD1_2 = 4.417878974599E-05 / Linear projection matrix CD2_1 = -4.401386723648E-05 / Linear projection matrix CD2_2 = -8.485412506127E-08 / Linear projection matrix END CRPIX1 = -3.773210853405E+03 / Reference pixel on this axis CRPIX2 = 2.334271317745E+03 / Reference pixel on this axis CD1_1 = 1.231899404748E-07 / Linear projection matrix CD1_2 = 4.411923376143E-05 / Linear projection matrix CD2_1 = -4.379238659129E-05 / Linear projection matrix CD2_2 = -4.896688592922E-08 / Linear projection matrix END CRPIX1 = 4.813024424397E+03 / Reference pixel on this axis CRPIX2 = 4.884508661091E+03 / Reference pixel on this axis CD1_1 = -3.585181887109E-07 / Linear projection matrix CD1_2 = 4.375127989067E-05 / Linear projection matrix CD2_1 = -4.367097386746E-05 / Linear projection matrix CD2_2 = 2.719156657516E-07 / Linear projection matrix END CRPIX1 = 3.719123047999E+03 / Reference pixel on this axis CRPIX2 = 4.874052556076E+03 / Reference pixel on this axis CD1_1 = -3.262237151225E-07 / Linear projection matrix CD1_2 = 4.383322309752E-05 / Linear projection matrix CD2_1 = -4.389211648843E-05 / Linear projection matrix CD2_2 = 1.204001667460E-07 / Linear projection matrix END CRPIX1 = 2.645337951317E+03 / Reference pixel on this axis CRPIX2 = 4.857768595378E+03 / Reference pixel on this axis CD1_1 = -1.547731796170E-07 / Linear projection matrix CD1_2 = 4.390180302744E-05 / Linear projection matrix CD2_1 = -4.407070120792E-05 / Linear projection matrix CD2_2 = 1.064707072856E-07 / Linear projection matrix END CRPIX1 = 1.579815461321E+03 / Reference pixel on this axis CRPIX2 = 4.852512683341E+03 / Reference pixel on this axis CD1_1 = -8.397821111046E-08 / Linear projection matrix CD1_2 = 4.392092194148E-05 / Linear projection matrix CD2_1 = -4.416184263450E-05 / Linear projection matrix CD2_2 = 9.556700348712E-08 / Linear projection matrix END CRPIX1 = 5.011747633969E+02 / Reference pixel on this axis CRPIX2 = 4.848483873812E+03 / Reference pixel on this axis CD1_1 = -6.176374965628E-08 / Linear projection matrix CD1_2 = 4.394302596406E-05 / Linear projection matrix CD2_1 = -4.417752140642E-05 / Linear projection matrix CD2_2 = -9.491497891602E-08 / Linear projection matrix END CRPIX1 = -5.595675785301E+02 / Reference pixel on this axis CRPIX2 = 4.850833061184E+03 / Reference pixel on this axis CD1_1 = 5.143080117743E-08 / Linear projection matrix CD1_2 = 4.392748622286E-05 / Linear projection matrix CD2_1 = -4.418354304969E-05 / Linear projection matrix CD2_2 = -7.947777992248E-08 / Linear projection matrix END CRPIX1 = -1.625156542041E+03 / Reference pixel on this axis CRPIX2 = 4.861161458470E+03 / Reference pixel on this axis CD1_1 = 2.240548466732E-07 / Linear projection matrix CD1_2 = 4.389347931247E-05 / Linear projection matrix CD2_1 = -4.406703214077E-05 / Linear projection matrix CD2_2 = -8.836705846309E-08 / Linear projection matrix END CRPIX1 = -2.704294567016E+03 / Reference pixel on this axis CRPIX2 = 4.871762364815E+03 / Reference pixel on this axis CD1_1 = 2.720261874533E-07 / Linear projection matrix CD1_2 = 4.383721093016E-05 / Linear projection matrix CD2_1 = -4.391599383754E-05 / Linear projection matrix CD2_2 = -1.767675979869E-07 / Linear projection matrix END CRPIX1 = -3.797635159685E+03 / Reference pixel on this axis CRPIX2 = 4.883263251138E+03 / Reference pixel on this axis CD1_1 = 2.992838859232E-07 / Linear projection matrix CD1_2 = 4.375334577299E-05 / Linear projection matrix CD2_1 = -4.366708789748E-05 / Linear projection matrix CD2_2 = -3.078199679764E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/MEGACAM_2x2@LCO.ini000066400000000000000000000064101417631501300211110ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MEGACAM_2x2@LCO INSTSHORT=MEGACAM # Number of chips NCHIPS=36 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.158 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=1055 [2]=1055 [3]=1055 [4]=1055 [5]=1055 [6]=1055 [7]=1055 [8]=1055 [9]=1055 [10]=1055 [11]=1055 [12]=1055 [13]=1055 [14]=1055 [15]=1055 [16]=1055 [17]=1055 [18]=1055 [19]=1055 [20]=1055 [21]=1055 [22]=1055 [23]=1055 [24]=1055 [25]=1055 [26]=1055 [27]=1055 [28]=1055 [29]=1055 [30]=1055 [31]=1055 [32]=1055 [33]=1055 [34]=1055 [35]=1055 [36]=1055) OVSCANX2=([1]=1098 [2]=1098 [3]=1098 [4]=1098 [5]=1098 [6]=1098 [7]=1098 [8]=1098 [9]=1098 [10]=1098 [11]=1098 [12]=1098 [13]=1098 [14]=1098 [15]=1098 [16]=1098 [17]=1098 [18]=1098 [19]=1098 [20]=1098 [21]=1098 [22]=1098 [23]=1098 [24]=1098 [25]=1098 [26]=1098 [27]=1098 [28]=1098 [29]=1098 [30]=1098 [31]=1098 [32]=1098 [33]=1098 [34]=1098 [35]=1098 [36]=1098) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=27 [2]=27 [3]=27 [4]=27 [5]=27 [6]=27 [7]=27 [8]=27 [9]=27 [10]=27 [11]=27 [12]=27 [13]=27 [14]=27 [15]=27 [16]=27 [17]=27 [18]=27 [19]=27 [20]=27 [21]=27 [22]=27 [23]=27 [24]=27 [25]=27 [26]=27 [27]=27 [28]=27 [29]=27 [30]=27 [31]=27 [32]=27 [33]=27 [34]=27 [35]=27 [36]=27) CUTY=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=3 [7]=3 [8]=3 [9]=3 [10]=3 [11]=3 [12]=3 [13]=3 [14]=3 [15]=3 [16]=3 [17]=3 [18]=3 [19]=3 [20]=3 [21]=3 [22]=3 [23]=3 [24]=3 [25]=3 [26]=3 [27]=3 [28]=3 [29]=3 [30]=3 [31]=3 [32]=3 [33]=3 [34]=3 [35]=3 [36]=3) SIZEX=([1]=1020 [2]=1020 [3]=1020 [4]=1020 [5]=1020 [6]=1020 [7]=1020 [8]=1020 [9]=1020 [10]=1020 [11]=1020 [12]=1020 [13]=1020 [14]=1020 [15]=1020 [16]=1020 [17]=1020 [18]=1020 [19]=1020 [20]=1020 [21]=1020 [22]=1020 [23]=1020 [24]=1020 [25]=1020 [26]=1020 [27]=1020 [28]=1020 [29]=1020 [30]=1020 [31]=1020 [32]=1020 [33]=1020 [34]=1020 [35]=1020 [36]=1020) SIZEY=([1]=2300 [2]=2300 [3]=2300 [4]=2300 [5]=2300 [6]=2300 [7]=2300 [8]=2300 [9]=2300 [10]=2300 [11]=2300 [12]=2300 [13]=2300 [14]=2300 [15]=2300 [16]=2300 [17]=2300 [18]=2300 [19]=2300 [20]=2300 [21]=2300 [22]=2300 [23]=2300 [24]=2300 [25]=2300 [26]=2300 [27]=2300 [28]=2300 [29]=2300 [30]=2300 [31]=2300 [32]=2300 [33]=2300 [34]=2300 [35]=2300 [36]=2300) # Reference pixels for each chip. REFPIXX=([1]=-3698 [2]=-2636 [3]=-1574 [4]=-512 [5]=549 [6]=1611 [7]=2673 [8]=3735 [9]=4797 [10]=-3698 [11]=-2636 [12]=-1574 [13]=-512 [14]=549 [15]=1611 [16]=2673 [17]=3735 [18]=4797 [19]=4773 [20]=3711 [21]=2649 [22]=1587 [23]=525 [24]=-536 [25]=-1598 [26]=-2660 [27]=-3722 [28]=4773 [29]=3711 [30]=2649 [31]=1587 [32]=525 [33]=-536 [34]=-1598 [35]=-2660 [36]=-3722) REFPIXY=([1]=4830 [2]=4830 [3]=4830 [4]=4830 [5]=4830 [6]=4830 [7]=4830 [8]=4830 [9]=4830 [10]=2319 [11]=2319 [12]=2319 [13]=2319 [14]=2319 [15]=2319 [16]=2319 [17]=2319 [18]=2319 [19]=2319 [20]=2319 [21]=2319 [22]=2319 [23]=2319 [24]=2319 [25]=2319 [26]=2319 [27]=2319 [28]=4831 [29]=4831 [30]=4831 [31]=4831 [32]=4831 [33]=4831 [34]=4831 [35]=4831 [36]=4831) TYPE=OPT THELI-3.1.3/config/instruments/MEGAPRIME@CFHT.ahead000066400000000000000000000420201417631501300212610ustar00rootroot00000000000000CRPIX1 = 9.532824661E+03 / Reference pixel on this axis CRPIX2 = -5.261742494E+03 / Reference pixel on this axis CD1_1 = -5.111691172E-05 / Linear projection matrix CD1_2 = -5.452696378E-07 / Linear projection matrix CD2_1 = 2.287252989E-07 / Linear projection matrix CD2_2 = 5.124410405E-05 / Linear projection matrix END CRPIX1 = 7.356457273E+03 / Reference pixel on this axis CRPIX2 = -5.240249327E+03 / Reference pixel on this axis CD1_1 = -5.141639131E-05 / Linear projection matrix CD1_2 = -4.392614097E-07 / Linear projection matrix CD2_1 = 1.955497883E-07 / Linear projection matrix CD2_2 = 5.133831314E-05 / Linear projection matrix END CRPIX1 = 5.203604379E+03 / Reference pixel on this axis CRPIX2 = -5.214132360E+03 / Reference pixel on this axis CD1_1 = -5.160642109E-05 / Linear projection matrix CD1_2 = -3.402014757E-07 / Linear projection matrix CD2_1 = 4.217800973E-08 / Linear projection matrix CD2_2 = 5.142146862E-05 / Linear projection matrix END CRPIX1 = 3.062570233E+03 / Reference pixel on this axis CRPIX2 = -5.203549371E+03 / Reference pixel on this axis CD1_1 = -5.176924216E-05 / Linear projection matrix CD1_2 = -2.478453484E-07 / Linear projection matrix CD2_1 = -6.842873426E-08 / Linear projection matrix CD2_2 = 5.146984886E-05 / Linear projection matrix END CRPIX1 = 9.285174574E+02 / Reference pixel on this axis CRPIX2 = -5.202421745E+03 / Reference pixel on this axis CD1_1 = -5.181473042E-05 / Linear projection matrix CD1_2 = -1.347683359E-07 / Linear projection matrix CD2_1 = -1.612411479E-07 / Linear projection matrix CD2_2 = 5.145985660E-05 / Linear projection matrix END CRPIX1 = -1.197294601E+03 / Reference pixel on this axis CRPIX2 = -5.202276112E+03 / Reference pixel on this axis CD1_1 = -5.176175195E-05 / Linear projection matrix CD1_2 = -7.531991203E-08 / Linear projection matrix CD2_1 = -2.408610597E-07 / Linear projection matrix CD2_2 = 5.147232749E-05 / Linear projection matrix END CRPIX1 = -3.347156268E+03 / Reference pixel on this axis CRPIX2 = -5.221270603E+03 / Reference pixel on this axis CD1_1 = -5.160594007E-05 / Linear projection matrix CD1_2 = 7.481824350E-08 / Linear projection matrix CD2_1 = -3.347005299E-07 / Linear projection matrix CD2_2 = 5.138332834E-05 / Linear projection matrix END CRPIX1 = -5.493167192E+03 / Reference pixel on this axis CRPIX2 = -5.233352390E+03 / Reference pixel on this axis CD1_1 = -5.144900493E-05 / Linear projection matrix CD1_2 = 1.632911545E-07 / Linear projection matrix CD2_1 = -4.105280028E-07 / Linear projection matrix CD2_2 = 5.133942589E-05 / Linear projection matrix END CRPIX1 = -7.665119534E+03 / Reference pixel on this axis CRPIX2 = -5.249515266E+03 / Reference pixel on this axis CD1_1 = -5.113842829E-05 / Linear projection matrix CD1_2 = 2.261235029E-07 / Linear projection matrix CD2_1 = -4.183176213E-07 / Linear projection matrix CD2_2 = 5.124354694E-05 / Linear projection matrix END CRPIX1 = 9.483685849E+03 / Reference pixel on this axis CRPIX2 = -1.493757895E+02 / Reference pixel on this axis CD1_1 = -5.124290732E-05 / Linear projection matrix CD1_2 = -2.628473668E-07 / Linear projection matrix CD2_1 = 3.615911667E-08 / Linear projection matrix CD2_2 = 5.168579317E-05 / Linear projection matrix END CRPIX1 = 7.315458437E+03 / Reference pixel on this axis CRPIX2 = -1.299884450E+02 / Reference pixel on this axis CD1_1 = -5.156002954E-05 / Linear projection matrix CD1_2 = -2.092726126E-07 / Linear projection matrix CD2_1 = -5.458619254E-08 / Linear projection matrix CD2_2 = 5.177867794E-05 / Linear projection matrix END CRPIX1 = 5.175019275E+03 / Reference pixel on this axis CRPIX2 = -1.239839825E+02 / Reference pixel on this axis CD1_1 = -5.180925063E-05 / Linear projection matrix CD1_2 = -2.181854305E-07 / Linear projection matrix CD2_1 = -7.149423587E-08 / Linear projection matrix CD2_2 = 5.186092571E-05 / Linear projection matrix END CRPIX1 = 3.048497235E+03 / Reference pixel on this axis CRPIX2 = -1.221656858E+02 / Reference pixel on this axis CD1_1 = -5.193659086E-05 / Linear projection matrix CD1_2 = -1.665836105E-07 / Linear projection matrix CD2_1 = -1.005716607E-07 / Linear projection matrix CD2_2 = 5.190743442E-05 / Linear projection matrix END CRPIX1 = 9.300872091E+02 / Reference pixel on this axis CRPIX2 = -1.210780358E+02 / Reference pixel on this axis CD1_1 = -5.197987259E-05 / Linear projection matrix CD1_2 = -1.449656256E-07 / Linear projection matrix CD2_1 = -1.452542064E-07 / Linear projection matrix CD2_2 = 5.192237819E-05 / Linear projection matrix END CRPIX1 = -1.188587791E+03 / Reference pixel on this axis CRPIX2 = -1.182617799E+02 / Reference pixel on this axis CD1_1 = -5.194303704E-05 / Linear projection matrix CD1_2 = -1.144405285E-07 / Linear projection matrix CD2_1 = -1.279427603E-07 / Linear projection matrix CD2_2 = 5.190732220E-05 / Linear projection matrix END CRPIX1 = -3.318437342E+03 / Reference pixel on this axis CRPIX2 = -1.259913906E+02 / Reference pixel on this axis CD1_1 = -5.175973451E-05 / Linear projection matrix CD1_2 = -7.539742746E-08 / Linear projection matrix CD2_1 = -1.888363064E-07 / Linear projection matrix CD2_2 = 5.185387894E-05 / Linear projection matrix END CRPIX1 = -5.452181038E+03 / Reference pixel on this axis CRPIX2 = -1.366565248E+02 / Reference pixel on this axis CD1_1 = -5.160718567E-05 / Linear projection matrix CD1_2 = -5.387965717E-08 / Linear projection matrix CD2_1 = -2.427595437E-07 / Linear projection matrix CD2_2 = 5.178427367E-05 / Linear projection matrix END CRPIX1 = -7.616418559E+03 / Reference pixel on this axis CRPIX2 = -1.245750237E+02 / Reference pixel on this axis CD1_1 = -5.129628014E-05 / Linear projection matrix CD1_2 = 1.061611661E-08 / Linear projection matrix CD2_1 = -1.600395127E-07 / Linear projection matrix CD2_2 = 5.169473144E-05 / Linear projection matrix END CRPIX1 = 9.469982913E+03 / Reference pixel on this axis CRPIX2 = 4.561538607E+03 / Reference pixel on this axis CD1_1 = -5.130888498E-05 / Linear projection matrix CD1_2 = -1.045222272E-08 / Linear projection matrix CD2_1 = -2.523697923E-07 / Linear projection matrix CD2_2 = 5.168445277E-05 / Linear projection matrix END CRPIX1 = 7.314546863E+03 / Reference pixel on this axis CRPIX2 = 4.554079631E+03 / Reference pixel on this axis CD1_1 = -5.156268078E-05 / Linear projection matrix CD1_2 = -6.712780554E-08 / Linear projection matrix CD2_1 = -2.432455016E-07 / Linear projection matrix CD2_2 = 5.176858868E-05 / Linear projection matrix END CRPIX1 = 5.172972127E+03 / Reference pixel on this axis CRPIX2 = 4.547026015E+03 / Reference pixel on this axis CD1_1 = -5.179867626E-05 / Linear projection matrix CD1_2 = -8.937520882E-08 / Linear projection matrix CD2_1 = -2.043765665E-07 / Linear projection matrix CD2_2 = 5.186455820E-05 / Linear projection matrix END CRPIX1 = 3.045524488E+03 / Reference pixel on this axis CRPIX2 = 4.543481260E+03 / Reference pixel on this axis CD1_1 = -5.190717568E-05 / Linear projection matrix CD1_2 = -1.122467853E-07 / Linear projection matrix CD2_1 = -1.762069396E-07 / Linear projection matrix CD2_2 = 5.190139269E-05 / Linear projection matrix END CRPIX1 = 9.267556303E+02 / Reference pixel on this axis CRPIX2 = 4.541659814E+03 / Reference pixel on this axis CD1_1 = -5.196543496E-05 / Linear projection matrix CD1_2 = -1.746166963E-07 / Linear projection matrix CD2_1 = -1.433651312E-07 / Linear projection matrix CD2_2 = 5.192177829E-05 / Linear projection matrix END CRPIX1 = -1.197695404E+03 / Reference pixel on this axis CRPIX2 = 4.537758999E+03 / Reference pixel on this axis CD1_1 = -5.189782651E-05 / Linear projection matrix CD1_2 = -2.371036860E-07 / Linear projection matrix CD2_1 = -2.125894539E-07 / Linear projection matrix CD2_2 = 5.189069465E-05 / Linear projection matrix END CRPIX1 = -3.319852332E+03 / Reference pixel on this axis CRPIX2 = 4.546806855E+03 / Reference pixel on this axis CD1_1 = -5.177841752E-05 / Linear projection matrix CD1_2 = -2.240993033E-07 / Linear projection matrix CD2_1 = -6.654906352E-08 / Linear projection matrix CD2_2 = 5.184264130E-05 / Linear projection matrix END CRPIX1 = -5.464145557E+03 / Reference pixel on this axis CRPIX2 = 4.550176470E+03 / Reference pixel on this axis CD1_1 = -5.154214380E-05 / Linear projection matrix CD1_2 = -2.646994986E-07 / Linear projection matrix CD2_1 = -6.255979925E-08 / Linear projection matrix CD2_2 = 5.176183567E-05 / Linear projection matrix END CRPIX1 = -7.615691198E+03 / Reference pixel on this axis CRPIX2 = 4.561479631E+03 / Reference pixel on this axis CD1_1 = -5.129562633E-05 / Linear projection matrix CD1_2 = -2.673749624E-07 / Linear projection matrix CD2_1 = -1.174595517E-08 / Linear projection matrix CD2_2 = 5.166739311E-05 / Linear projection matrix END CRPIX1 = 9.518051167E+03 / Reference pixel on this axis CRPIX2 = 9.687718773E+03 / Reference pixel on this axis CD1_1 = -5.113539254E-05 / Linear projection matrix CD1_2 = 2.204513437E-07 / Linear projection matrix CD2_1 = -5.269847101E-07 / Linear projection matrix CD2_2 = 5.121824112E-05 / Linear projection matrix END CRPIX1 = 7.346777736E+03 / Reference pixel on this axis CRPIX2 = 9.645217409E+03 / Reference pixel on this axis CD1_1 = -5.143503667E-05 / Linear projection matrix CD1_2 = 1.313819485E-07 / Linear projection matrix CD2_1 = -3.982166034E-07 / Linear projection matrix CD2_2 = 5.137004561E-05 / Linear projection matrix END CRPIX1 = 5.195431528E+03 / Reference pixel on this axis CRPIX2 = 9.641470651E+03 / Reference pixel on this axis CD1_1 = -5.163294026E-05 / Linear projection matrix CD1_2 = 3.899178214E-08 / Linear projection matrix CD2_1 = -3.892637585E-07 / Linear projection matrix CD2_2 = 5.137150886E-05 / Linear projection matrix END CRPIX1 = 3.056576782E+03 / Reference pixel on this axis CRPIX2 = 9.627450963E+03 / Reference pixel on this axis CD1_1 = -5.174483738E-05 / Linear projection matrix CD1_2 = -7.189112243E-08 / Linear projection matrix CD2_1 = -2.152465763E-07 / Linear projection matrix CD2_2 = 5.141177370E-05 / Linear projection matrix END CRPIX1 = 9.237699155E+02 / Reference pixel on this axis CRPIX2 = 9.620314179E+03 / Reference pixel on this axis CD1_1 = -5.183257873E-05 / Linear projection matrix CD1_2 = -1.746020310E-07 / Linear projection matrix CD2_1 = -1.678741636E-07 / Linear projection matrix CD2_2 = 5.144833602E-05 / Linear projection matrix END CRPIX1 = -1.206066305E+03 / Reference pixel on this axis CRPIX2 = 9.618061465E+03 / Reference pixel on this axis CD1_1 = -5.174622973E-05 / Linear projection matrix CD1_2 = -2.592727974E-07 / Linear projection matrix CD2_1 = -8.225746749E-08 / Linear projection matrix CD2_2 = 5.148521673E-05 / Linear projection matrix END CRPIX1 = -3.346338507E+03 / Reference pixel on this axis CRPIX2 = 9.632157901E+03 / Reference pixel on this axis CD1_1 = -5.162754766E-05 / Linear projection matrix CD1_2 = -3.684399260E-07 / Linear projection matrix CD2_1 = 4.749394215E-08 / Linear projection matrix CD2_2 = 5.141777563E-05 / Linear projection matrix END CRPIX1 = -5.499167850E+03 / Reference pixel on this axis CRPIX2 = 9.664057939E+03 / Reference pixel on this axis CD1_1 = -5.141081564E-05 / Linear projection matrix CD1_2 = -4.370366832E-07 / Linear projection matrix CD2_1 = 1.865452308E-07 / Linear projection matrix CD2_2 = 5.128549707E-05 / Linear projection matrix END CRPIX1 = -7.665582988E+03 / Reference pixel on this axis CRPIX2 = 9.689417575E+03 / Reference pixel on this axis CD1_1 = -5.114121370E-05 / Linear projection matrix CD1_2 = -4.992009460E-07 / Linear projection matrix CD2_1 = 2.717330349E-07 / Linear projection matrix CD2_2 = 5.120512680E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/MEGAPRIME@CFHT.ini000066400000000000000000000061571417631501300210110ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MEGAPRIME@CFHT INSTSHORT=MEGAPRIME # Number of chips NCHIPS=36 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.186 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=5 [2]=5 [3]=5 [4]=5 [5]=5 [6]=5 [7]=5 [8]=5 [9]=5 [10]=5 [11]=5 [12]=5 [13]=5 [14]=5 [15]=5 [16]=5 [17]=5 [18]=5 [19]=5 [20]=5 [21]=5 [22]=5 [23]=5 [24]=5 [25]=5 [26]=5 [27]=5 [28]=5 [29]=5 [30]=5 [31]=5 [32]=5 [33]=5 [34]=5 [35]=5 [36]=5) OVSCANX2=([1]=30 [2]=30 [3]=30 [4]=30 [5]=30 [6]=30 [7]=30 [8]=30 [9]=30 [10]=30 [11]=30 [12]=30 [13]=30 [14]=30 [15]=30 [16]=30 [17]=30 [18]=30 [19]=30 [20]=30 [21]=30 [22]=30 [23]=30 [24]=30 [25]=30 [26]=30 [27]=30 [28]=30 [29]=30 [30]=30 [31]=30 [32]=30 [33]=30 [34]=30 [35]=30 [36]=30) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=35 [2]=35 [3]=35 [4]=35 [5]=35 [6]=35 [7]=35 [8]=35 [9]=35 [10]=35 [11]=35 [12]=35 [13]=35 [14]=35 [15]=35 [16]=35 [17]=35 [18]=35 [19]=38 [20]=38 [21]=38 [22]=38 [23]=38 [24]=38 [25]=38 [26]=38 [27]=38 [28]=38 [29]=38 [30]=38 [31]=38 [32]=38 [33]=38 [34]=38 [35]=38 [36]=38) CUTY=([1]=34 [2]=34 [3]=34 [4]=34 [5]=34 [6]=34 [7]=34 [8]=34 [9]=34 [10]=34 [11]=34 [12]=34 [13]=34 [14]=34 [15]=34 [16]=34 [17]=34 [18]=34 [19]=3 [20]=3 [21]=3 [22]=3 [23]=3 [24]=3 [25]=3 [26]=3 [27]=3 [28]=3 [29]=3 [30]=3 [31]=3 [32]=3 [33]=3 [34]=3 [35]=3 [36]=3) SIZEX=([1]=2041 [2]=2041 [3]=2041 [4]=2041 [5]=2041 [6]=2041 [7]=2041 [8]=2041 [9]=2041 [10]=2041 [11]=2041 [12]=2041 [13]=2041 [14]=2041 [15]=2041 [16]=2041 [17]=2041 [18]=2041 [19]=2041 [20]=2041 [21]=2041 [22]=2041 [23]=2041 [24]=2041 [25]=2041 [26]=2041 [27]=2041 [28]=2041 [29]=2041 [30]=2041 [31]=2041 [32]=2041 [33]=2041 [34]=2041 [35]=2041 [36]=2041) SIZEY=([1]=4607 [2]=4607 [3]=4607 [4]=4607 [5]=4607 [6]=4607 [7]=4607 [8]=4607 [9]=4607 [10]=4607 [11]=4607 [12]=4607 [13]=4607 [14]=4607 [15]=4607 [16]=4607 [17]=4607 [18]=4607 [19]=4607 [20]=4607 [21]=4607 [22]=4607 [23]=4607 [24]=4607 [25]=4607 [26]=4607 [27]=4607 [28]=4607 [29]=4607 [30]=4607 [31]=4607 [32]=4607 [33]=4607 [34]=4607 [35]=4607 [36]=4607) # Reference pixels for each chip. REFPIXX=([1]=-7300 [2]=-5220 [3]=-3118 [4]=-1023 [5]=1083 [6]=3191 [7]=5312 [8]=7394 [9]=9486 [10]=-7346 [11]=-5257 [12]=-3156 [13]=-1049 [14]=1066 [15]=3180 [16]=5308 [17]=7393 [18]=9487 [19]=9496 [20]=7402 [21]=5295 [22]=3179 [23]=1066 [24]=-1053 [25]=-3168 [26]=-5233 [27]=-7348 [28]=9498 [29]=7405 [30]=5303 [31]=3194 [32]=1091 [33]=-1017 [34]=-3121 [35]=-5230 [36]=-7308) REFPIXY=([1]=9635 [2]=9647 [3]=9640 [4]=9653 [5]=9639 [6]=9639 [7]=9609 [8]=9587 [9]=9576 [10]=4642 [11]=4649 [12]=4643 [13]=4638 [14]=4633 [15]=4624 [16]=4613 [17]=4610 [18]=4592 [19]=4587 [20]=4606 [21]=4613 [22]=4625 [23]=4633 [24]=4637 [25]=4649 [26]=4632 [27]=4644 [28]=9574 [29]=9596 [30]=9612 [31]=9631 [32]=9634 [33]=9643 [34]=9643 [35]=9651 [36]=9639) TYPE=OPT THELI-3.1.3/config/instruments/MEGAPRIME_ELIXIR@CFHT.ini000066400000000000000000000161311417631501300220560ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MEGAPRIME_ELIXIR@CFHT INSTSHORT=MEGAPRIME # Number of chips NCHIPS=36 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.186 GAIN=1.62 # Overscan regions. OVSCANX1=([1]=5 [2]=5 [3]=5 [4]=5 [5]=5 [6]=5 [7]=5 [8]=5 [9]=5 [10]=5 [11]=5 [12]=5 [13]=5 [14]=5 [15]=5 [16]=5 [17]=5 [18]=5 [19]=5 [20]=5 [21]=5 [22]=5 [23]=5 [24]=5 [25]=5 [26]=5 [27]=5 [28]=5 [29]=5 [30]=5 [31]=5 [32]=5 [33]=5 [34]=5 [35]=5 [36]=5) OVSCANX2=([1]=30 [2]=30 [3]=30 [4]=30 [5]=30 [6]=30 [7]=30 [8]=30 [9]=30 [10]=30 [11]=30 [12]=30 [13]=30 [14]=30 [15]=30 [16]=30 [17]=30 [18]=30 [19]=30 [20]=30 [21]=30 [22]=30 [23]=30 [24]=30 [25]=30 [26]=30 [27]=30 [28]=30 [29]=30 [30]=30 [31]=30 [32]=30 [33]=30 [34]=30 [35]=30 [36]=30) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=35 [2]=35 [3]=35 [4]=35 [5]=35 [6]=35 [7]=35 [8]=35 [9]=35 [10]=35 [11]=35 [12]=35 [13]=35 [14]=35 [15]=35 [16]=35 [17]=35 [18]=35 [19]=38 [20]=38 [21]=38 [22]=38 [23]=38 [24]=38 [25]=38 [26]=38 [27]=38 [28]=38 [29]=38 [30]=38 [31]=38 [32]=38 [33]=38 [34]=38 [35]=38 [36]=38) CUTY=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=3 [7]=3 [8]=3 [9]=3 [10]=3 [11]=3 [12]=3 [13]=3 [14]=3 [15]=3 [16]=3 [17]=3 [18]=3 [19]=34 [20]=34 [21]=34 [22]=34 [23]=34 [24]=34 [25]=34 [26]=34 [27]=34 [28]=34 [29]=34 [30]=34 [31]=34 [32]=34 [33]=34 [34]=34 [35]=34 [36]=34) SIZEX=([1]=2043 [2]=2043 [3]=2043 [4]=2043 [5]=2043 [6]=2043 [7]=2043 [8]=2043 [9]=2043 [10]=2043 [11]=2043 [12]=2043 [13]=2043 [14]=2043 [15]=2043 [16]=2043 [17]=2043 [18]=2043 [19]=2043 [20]=2043 [21]=2043 [22]=2043 [23]=2043 [24]=2043 [25]=2043 [26]=2043 [27]=2043 [28]=2043 [29]=2043 [30]=2043 [31]=2043 [32]=2043 [33]=2043 [34]=2043 [35]=2043 [36]=2043) SIZEY=([1]=4606 [2]=4606 [3]=4606 [4]=4606 [5]=4606 [6]=4606 [7]=4606 [8]=4606 [9]=4606 [10]=4606 [11]=4606 [12]=4606 [13]=4606 [14]=4606 [15]=4606 [16]=4606 [17]=4606 [18]=4606 [19]=4606 [20]=4606 [21]=4606 [22]=4606 [23]=4606 [24]=4606 [25]=4606 [26]=4606 [27]=4606 [28]=4606 [29]=4606 [30]=4606 [31]=4606 [32]=4606 [33]=4606 [34]=4606 [35]=4606 [36]=4606) # Reference pixels for each chip. REFPIXX=([1]=-7300.4 [2]=-5220.2 [3]=-3118.8 [4]=-1023.5 [5]=1083.9 [6]=3191.2 [7]=5312.4 [8]=7394.6 [9]=9486.6 [10]=-7346.7 [11]=-5257.2 [12]=-3156.8 [13]=-1049.3 [14]=1066.2 [15]=3180.8 [16]=5308.3 [17]=7393.9 [18]=9487.0 [19]=9496.3 [20]=7402.2 [21]=5295.4 [22]=3179.9 [23]=1066.2 [24]=-1053.7 [25]=-3168.1 [26]=-5233.7 [27]=-7348.7 [28]=9498.2 [29]=7405.4 [30]=5303.0 [31]=3194.3 [32]=1091.0 [33]=-1017.7 [34]=-3121.3 [35]=-5230.7 [36]=-7308.7) REFPIXY=([1]=9635.9 [2]=9647.5 [3]=9640.5 [4]=9653.2 [5]=9639.9 [6]=9639.9 [7]=9609.0 [8]=9587.7 [9]=9576.0 [10]=4642.5 [11]=4649.7 [12]=4643.3 [13]=4638.0 [14]=4633.7 [15]=4624.1 [16]=4613.1 [17]=4610.4 [18]=4592.2 [19]=4587.2 [20]=4606.1 [21]=4613.0 [22]=4625.3 [23]=4633.7 [24]=4637.7 [25]=4649.4 [26]=4632.5 [27]=4644.8 [28]=9574.1 [29]=9596.6 [30]=9612.3 [31]=9631.1 [32]=9634.0 [33]=9643.7 [34]=9643.4 [35]=9651.0 [36]=9639.7) CD11=([1]=5.194000e-05 [2]=5.194000e-05 [3]=5.194000e-05 [4]=5.194000e-05 [5]=5.194000e-05 [6]=5.194000e-05 [7]=5.194000e-05 [8]=5.194000e-05 [9]=5.194000e-05 [10]=5.194000e-05 [11]=5.194000e-05 [12]=5.194000e-05 [13]=5.194000e-05 [14]=5.194000e-05 [15]=5.194000e-05 [16]=5.194000e-05 [17]=5.194000e-05 [18]=5.194000e-05 [19]=-5.194000e-05 [20]=-5.194000e-05 [21]=-5.194000e-05 [22]=-5.194000e-05 [23]=-5.194000e-05 [24]=-5.194000e-05 [25]=-5.194000e-05 [26]=-5.194000e-05 [27]=-5.194000e-05 [28]=-5.194000e-05 [29]=-5.194000e-05 [30]=-5.194000e-05 [31]=-5.194000e-05 [32]=-5.194000e-05 [33]=-5.194000e-05 [34]=-5.194000e-05 [35]=-5.194000e-05 [36]=-5.194000e-05) CD12=([1]=0.000000e+00 [2]=0.000000e+00 [3]=0.000000e+00 [4]=0.000000e+00 [5]=0.000000e+00 [6]=0.000000e+00 [7]=0.000000e+00 [8]=0.000000e+00 [9]=0.000000e+00 [10]=0.000000e+00 [11]=0.000000e+00 [12]=0.000000e+00 [13]=0.000000e+00 [14]=0.000000e+00 [15]=0.000000e+00 [16]=0.000000e+00 [17]=0.000000e+00 [18]=0.000000e+00 [19]=0.000000e+00 [20]=0.000000e+00 [21]=0.000000e+00 [22]=0.000000e+00 [23]=0.000000e+00 [24]=0.000000e+00 [25]=0.000000e+00 [26]=0.000000e+00 [27]=0.000000e+00 [28]=0.000000e+00 [29]=0.000000e+00 [30]=0.000000e+00 [31]=0.000000e+00 [32]=0.000000e+00 [33]=0.000000e+00 [34]=0.000000e+00 [35]=0.000000e+00 [36]=0.000000e+00) CD21=([1]=0.000000e+00 [2]=0.000000e+00 [3]=0.000000e+00 [4]=0.000000e+00 [5]=0.000000e+00 [6]=0.000000e+00 [7]=0.000000e+00 [8]=0.000000e+00 [9]=0.000000e+00 [10]=0.000000e+00 [11]=0.000000e+00 [12]=0.000000e+00 [13]=0.000000e+00 [14]=0.000000e+00 [15]=0.000000e+00 [16]=0.000000e+00 [17]=0.000000e+00 [18]=0.000000e+00 [19]=0.000000e+00 [20]=0.000000e+00 [21]=0.000000e+00 [22]=0.000000e+00 [23]=0.000000e+00 [24]=0.000000e+00 [25]=0.000000e+00 [26]=0.000000e+00 [27]=0.000000e+00 [28]=0.000000e+00 [29]=0.000000e+00 [30]=0.000000e+00 [31]=0.000000e+00 [32]=0.000000e+00 [33]=0.000000e+00 [34]=0.000000e+00 [35]=0.000000e+00 [36]=0.000000e+00) CD22=([1]=-5.194000e-05 [2]=-5.194000e-05 [3]=-5.194000e-05 [4]=-5.194000e-05 [5]=-5.194000e-05 [6]=-5.194000e-05 [7]=-5.194000e-05 [8]=-5.194000e-05 [9]=-5.194000e-05 [10]=-5.194000e-05 [11]=-5.194000e-05 [12]=-5.194000e-05 [13]=-5.194000e-05 [14]=-5.194000e-05 [15]=-5.194000e-05 [16]=-5.194000e-05 [17]=-5.194000e-05 [18]=-5.194000e-05 [19]=5.194000e-05 [20]=5.194000e-05 [21]=5.194000e-05 [22]=5.194000e-05 [23]=5.194000e-05 [24]=5.194000e-05 [25]=5.194000e-05 [26]=5.194000e-05 [27]=5.194000e-05 [28]=5.194000e-05 [29]=5.194000e-05 [30]=5.194000e-05 [31]=5.194000e-05 [32]=5.194000e-05 [33]=5.194000e-05 [34]=5.194000e-05 [35]=5.194000e-05 [36]=5.194000e-05) M11=([1]=-1 [2]=-1 [3]=-1 [4]=-1 [5]=-1 [6]=-1 [7]=-1 [8]=-1 [9]=-1 [10]=-1 [11]=-1 [12]=-1 [13]=-1 [14]=-1 [15]=-1 [16]=-1 [17]=-1 [18]=-1 [19]=1 [20]=1 [21]=1 [22]=1 [23]=1 [24]=1 [25]=1 [26]=1 [27]=1 [28]=1 [29]=1 [30]=1 [31]=1 [32]=1 [33]=1 [34]=1 [35]=1 [36]=1) M12=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0) M21=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0 [32]=0 [33]=0 [34]=0 [35]=0 [36]=0) M22=([1]=-1 [2]=-1 [3]=-1 [4]=-1 [5]=-1 [6]=-1 [7]=-1 [8]=-1 [9]=-1 [10]=-1 [11]=-1 [12]=-1 [13]=-1 [14]=-1 [15]=-1 [16]=-1 [17]=-1 [18]=-1 [19]=1 [20]=1 [21]=1 [22]=1 [23]=1 [24]=1 [25]=1 [26]=1 [27]=1 [28]=1 [29]=1 [30]=1 [31]=1 [32]=1 [33]=1 [34]=1 [35]=1 [36]=1) IMAGEID=([28]=1 [29]=2 [30]=3 [31]=4 [32]=5 [33]=6 [34]=7 [35]=8 [36]=9 [19]=10 [20]=11 [21]=12 [22]=13 [23]=14 [24]=15 [25]=16 [26]=17 [27]=18 [10]=19 [11]=20 [12]=21 [13]=22 [14]=23 [15]=24 [16]=25 [17]=26 [18]=27 [1]=28 [2]=29 [3]=30 [4]=31 [5]=32 [6]=33 [7]=34 [8]=35 [9]=36) TYPE=OPT THELI-3.1.3/config/instruments/MEROPE@MERCATOR.ini000066400000000000000000000013661417631501300211570ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MEROPE@MERCATOR INSTSHORT=MEROPE # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.1934 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=5) OVSCANX2=([1]=48) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=50) CUTY=([1]=2) SIZEX=([1]=2046) SIZEY=([1]=2043) # Reference pixels for each chip. REFPIXX=([1]=1068) REFPIXY=([1]=960) TYPE=OPT THELI-3.1.3/config/instruments/MMIRS@LCO.ini000066400000000000000000000013511417631501300202520ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MMIRS@LCO INSTSHORT=MMIRS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.2 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) TYPE=NIR THELI-3.1.3/config/instruments/MMIRS@MMTO.ini000066400000000000000000000014121417631501300204070ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MMIRS@MMTO INSTSHORT=MMIRS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=31.68 OBSLONG=-110.885 # Pixel scale in arcsec PIXSCALE=0.2 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) OVSCANY1=([1]=0) OVSCANY2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=5) CUTY=([1]=5) SIZEX=([1]=2044) SIZEY=([1]=2044) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) TYPE=NIR THELI-3.1.3/config/instruments/MOIRCS_200406-200806@SUBARU.ahead000066400000000000000000000017221417631501300226000ustar00rootroot00000000000000CRPIX1 = 1.961223532963E+03 / Reference pixel on this axis CRPIX2 = 1.012343362744E+03 / Reference pixel on this axis CD1_1 = -3.196687957941E-05 / Linear projection matrix CD1_2 = -1.938137874333E-07 / Linear projection matrix CD2_1 = -1.795347075107E-07 / Linear projection matrix CD2_2 = 3.193607419085E-05 / Linear projection matrix END CRPIX1 = 4.154337427535E+02 / Reference pixel on this axis CRPIX2 = 1.000756330764E+03 / Reference pixel on this axis CD1_1 = -3.212713938540E-05 / Linear projection matrix CD1_2 = -2.935879842887E-07 / Linear projection matrix CD2_1 = -2.245041834946E-07 / Linear projection matrix CD2_2 = 3.209776893973E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/MOIRCS_200406-200806@SUBARU.ini000066400000000000000000000014661417631501300223220ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOIRCS_200406-200806@SUBARU INSTSHORT=MOIRCS # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.114 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1) CUTY=([1]=1 [2]=1) SIZEX=([1]=2048 [2]=2048) SIZEY=([1]=2048 [2]=2048) # Reference pixels for each chip. REFPIXX=([1]=1750 [2]=50) REFPIXY=([1]=1024 [2]=1024) TYPE=NIR THELI-3.1.3/config/instruments/MOIRCS_200406-200806@SUBARU_1.reg000066400000000000000000000003651417631501300225350ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(275,2048,1791.2778,2047.7222,1789.5556,7.5,88.944444,3.5,90,674,172,673,193,532,201,499,245,433,1026.4444,434.05556,1026.4444,668.77778,90.333333,674.33333,102,1890) THELI-3.1.3/config/instruments/MOIRCS_200406-200806@SUBARU_2.reg000066400000000000000000000002311417631501300225260ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(272.05556,1967.6667,1617,1967,1973,1609,1942.3333,99,277.05556,92.055556) THELI-3.1.3/config/instruments/MOIRCS_200807-201505@SUBARU.ahead000066400000000000000000000017221417631501300226020ustar00rootroot00000000000000CRPIX1 = 1.816956755873E+03 / Reference pixel on this axis CRPIX2 = 1.028189519400E+03 / Reference pixel on this axis CD1_1 = -1.586964270374E-05 / Linear projection matrix CD1_2 = -2.767685801718E-05 / Linear projection matrix CD2_1 = -2.772810479925E-05 / Linear projection matrix CD2_2 = 1.593911760342E-05 / Linear projection matrix END CRPIX1 = 2.379247470930E+02 / Reference pixel on this axis CRPIX2 = 1.016894813570E+03 / Reference pixel on this axis CD1_1 = -1.587517607994E-05 / Linear projection matrix CD1_2 = -2.787203601857E-05 / Linear projection matrix CD2_1 = -2.799385742104E-05 / Linear projection matrix CD2_2 = 1.579560614678E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/MOIRCS_200807-201505@SUBARU.ini000066400000000000000000000014661417631501300223240ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOIRCS_200807-201505@SUBARU INSTSHORT=MOIRCS # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.114 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1) CUTY=([1]=1 [2]=1) SIZEX=([1]=2048 [2]=2048) SIZEY=([1]=2048 [2]=2048) # Reference pixels for each chip. REFPIXX=([1]=1750 [2]=50) REFPIXY=([1]=1024 [2]=1024) TYPE=NIR THELI-3.1.3/config/instruments/MOIRCS_200807-201505@SUBARU_1.reg000066400000000000000000000010311417631501300225260ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(1769.5189,2046.3541,1766.9353,1620.3994,1713.4018,1620.6616,1717.088,1649.9765,1690.9104,1711.6292,1647.8792,1750.6438,1584.4757,1759.8657,1513.6561,1729.6714,1482.7597,1663.9171,1479.0896,1605.1945,1485.3813,1561.1525,1516.8398,1524.9752,1561.9304,1510.2945,1623.2746,1510.8188,1672.5596,1537.0343,1700.3101,1574.4759,1713.4018,1620.3994,1766.8813,1620.2684,1763.2272,1033.3889,1769.5189,9.937564,110.60491,9.937564,118.99386,1027.0972,112.70215,2042.1597) THELI-3.1.3/config/instruments/MOIRCS_200807-201505@SUBARU_2.reg000066400000000000000000000002311417631501300225300ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(272.05556,1967.6667,1617,1967,1973,1609,1942.3333,99,277.05556,92.055556) THELI-3.1.3/config/instruments/MOIRCS_201512-today@SUBARU.ahead000066400000000000000000000017221417631501300231600ustar00rootroot00000000000000CRPIX1 = 1.829409447461E+03 / Reference pixel on this axis CRPIX2 = 1.016049211401E+03 / Reference pixel on this axis CD1_1 = -1.440651554753E-07 / Linear projection matrix CD1_2 = 3.187121747448E-05 / Linear projection matrix CD2_1 = 3.189563232566E-05 / Linear projection matrix CD2_2 = 1.176379036759E-07 / Linear projection matrix END CRPIX1 = 2.218423938535E+02 / Reference pixel on this axis CRPIX2 = 1.041433887377E+03 / Reference pixel on this axis CD1_1 = 1.994792277100E-07 / Linear projection matrix CD1_2 = 3.194170177707E-05 / Linear projection matrix CD2_1 = 3.197729296792E-05 / Linear projection matrix CD2_2 = -1.803962617296E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/MOIRCS_201512-today@SUBARU.ini000066400000000000000000000014671417631501300227030ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOIRCS_201512-today@SUBARU INSTSHORT=MOIRCS # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.117 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1) CUTY=([1]=1 [2]=1) SIZEX=([1]=2048 [2]=2048) SIZEY=([1]=2048 [2]=2048) # Reference pixels for each chip. REFPIXX=([1]=1750 [2]=50) REFPIXY=([1]=1024 [2]=1024) TYPE=NIR THELI-3.1.3/config/instruments/MOIRCS_201512-today@SUBARU_1.reg000066400000000000000000000001541417631501300231110ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(6,2043,1801,2042,1799,8,7,7) THELI-3.1.3/config/instruments/MOIRCS_201512-today@SUBARU_2.reg000066400000000000000000000002641417631501300231140ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(266.99864,2040.0029,1611.9995,2038.9953,2035.0031,1638.0018,2029.9966,6.9994745,266.99926,8.0060371) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m.ahead000066400000000000000000000171001417631501300217620ustar00rootroot00000000000000CRPIX1 = -2.240391900200E+03 / Reference pixel on this axis CRPIX2 = 4.264764810831E+03 / Reference pixel on this axis CD1_1 = 5.240000160396E-07 / Linear projection matrix CD1_2 = 7.109270224599E-05 / Linear projection matrix CD2_1 = 7.108280301400E-05 / Linear projection matrix CD2_2 = 9.063083184049E-07 / Linear projection matrix END CRPIX1 = -1.291457838785E+02 / Reference pixel on this axis CRPIX2 = 4.230114749847E+03 / Reference pixel on this axis CD1_1 = -1.116010354577E-08 / Linear projection matrix CD1_2 = 7.150697001660E-05 / Linear projection matrix CD2_1 = 7.218410103915E-05 / Linear projection matrix CD2_2 = 4.828374008596E-07 / Linear projection matrix END CRPIX1 = -2.212427277821E+03 / Reference pixel on this axis CRPIX2 = 2.157548055651E+03 / Reference pixel on this axis CD1_1 = -7.211289586633E-09 / Linear projection matrix CD1_2 = 7.215066041286E-05 / Linear projection matrix CD2_1 = 7.145988846780E-05 / Linear projection matrix CD2_2 = 4.924669104465E-07 / Linear projection matrix END CRPIX1 = -1.203440923285E+02 / Reference pixel on this axis CRPIX2 = 2.148771123456E+03 / Reference pixel on this axis CD1_1 = -1.444307151781E-07 / Linear projection matrix CD1_2 = 7.250160893351E-05 / Linear projection matrix CD2_1 = 7.250082330445E-05 / Linear projection matrix CD2_2 = 3.399803080287E-07 / Linear projection matrix END CRPIX1 = 2.152964138345E+03 / Reference pixel on this axis CRPIX2 = 4.231132807954E+03 / Reference pixel on this axis CD1_1 = -5.439400258712E-07 / Linear projection matrix CD1_2 = 7.154915939761E-05 / Linear projection matrix CD2_1 = 7.216804419756E-05 / Linear projection matrix CD2_2 = 6.232108578748E-08 / Linear projection matrix END CRPIX1 = 4.249623180171E+03 / Reference pixel on this axis CRPIX2 = 4.251467218885E+03 / Reference pixel on this axis CD1_1 = -8.737883270487E-07 / Linear projection matrix CD1_2 = 7.124881258191E-05 / Linear projection matrix CD2_1 = 7.129442755058E-05 / Linear projection matrix CD2_2 = -2.758179362924E-07 / Linear projection matrix END CRPIX1 = 2.144397027216E+03 / Reference pixel on this axis CRPIX2 = 2.151211490789E+03 / Reference pixel on this axis CD1_1 = -3.994211345402E-07 / Linear projection matrix CD1_2 = 7.250137303814E-05 / Linear projection matrix CD2_1 = 7.249349539638E-05 / Linear projection matrix CD2_2 = 2.035196029964E-07 / Linear projection matrix END CRPIX1 = 4.233845299888E+03 / Reference pixel on this axis CRPIX2 = 2.160905870614E+03 / Reference pixel on this axis CD1_1 = -5.478579971139E-07 / Linear projection matrix CD1_2 = 7.215845683145E-05 / Linear projection matrix CD2_1 = 7.148412203057E-05 / Linear projection matrix CD2_2 = 9.091114694374E-08 / Linear projection matrix END CRPIX1 = -1.192892756485E+02 / Reference pixel on this axis CRPIX2 = -2.187854166095E+03 / Reference pixel on this axis CD1_1 = -5.604646125635E-07 / Linear projection matrix CD1_2 = 7.152506193781E-05 / Linear projection matrix CD2_1 = 7.219487562056E-05 / Linear projection matrix CD2_2 = 1.336414459416E-07 / Linear projection matrix END CRPIX1 = -2.218403204750E+03 / Reference pixel on this axis CRPIX2 = -2.219755993404E+03 / Reference pixel on this axis CD1_1 = -1.089827684946E-06 / Linear projection matrix CD1_2 = 7.116864187015E-05 / Linear projection matrix CD2_1 = 7.117404056331E-05 / Linear projection matrix CD2_2 = -1.325323526297E-07 / Linear projection matrix END CRPIX1 = -1.112425908423E+02 / Reference pixel on this axis CRPIX2 = -1.085642230818E+02 / Reference pixel on this axis CD1_1 = -4.773052941863E-07 / Linear projection matrix CD1_2 = 7.247425375612E-05 / Linear projection matrix CD2_1 = 7.249512282950E-05 / Linear projection matrix CD2_2 = 2.623918690302E-07 / Linear projection matrix END CRPIX1 = -2.200950096933E+03 / Reference pixel on this axis CRPIX2 = -1.172669944298E+02 / Reference pixel on this axis CD1_1 = -6.098519764509E-07 / Linear projection matrix CD1_2 = 7.218463631302E-05 / Linear projection matrix CD2_1 = 7.150558897240E-05 / Linear projection matrix CD2_2 = 1.326833959551E-07 / Linear projection matrix END CRPIX1 = 4.263108885419E+03 / Reference pixel on this axis CRPIX2 = -2.210882950241E+03 / Reference pixel on this axis CD1_1 = 4.453226196947E-07 / Linear projection matrix CD1_2 = 7.115857154245E-05 / Linear projection matrix CD2_1 = 7.123779293180E-05 / Linear projection matrix CD2_2 = 9.465383003069E-07 / Linear projection matrix END CRPIX1 = 2.158855194168E+03 / Reference pixel on this axis CRPIX2 = -2.182305376857E+03 / Reference pixel on this axis CD1_1 = -6.420715271478E-08 / Linear projection matrix CD1_2 = 7.147869183843E-05 / Linear projection matrix CD2_1 = 7.216466723943E-05 / Linear projection matrix CD2_2 = 5.091879776952E-07 / Linear projection matrix END CRPIX1 = 4.241969192067E+03 / Reference pixel on this axis CRPIX2 = -1.099428366859E+02 / Reference pixel on this axis CD1_1 = -2.994819040711E-08 / Linear projection matrix CD1_2 = 7.215330736080E-05 / Linear projection matrix CD2_1 = 7.146793203965E-05 / Linear projection matrix CD2_2 = 5.342222155666E-07 / Linear projection matrix END CRPIX1 = 2.150865946974E+03 / Reference pixel on this axis CRPIX2 = -9.962987954378E+01 / Reference pixel on this axis CD1_1 = -1.936555522489E-07 / Linear projection matrix CD1_2 = 7.250836868715E-05 / Linear projection matrix CD2_1 = 7.250046646658E-05 / Linear projection matrix CD2_2 = 3.916356409922E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m.ini000066400000000000000000000032421417631501300215010ustar00rootroot00000000000000INSTRUMENT=MOSAIC-III@KPNO_4m NCHIPS=16 # Geographic location OBSLAT=31.95 OBSLONG=-111.6 # Plate scale PIXSCALE=0.257 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=2066 [2]=2066 [3]=2066 [4]=2066 [5]=2066 [6]=2066 [7]=2066 [8]=2066 [9]=2066 [10]=2066 [11]=2066 [12]=2066 [13]=2066 [14]=2066 [15]=2066 [16]=2066) OVSCANX2=([1]=2111 [2]=2111 [3]=2111 [4]=2111 [5]=2111 [6]=2111 [7]=2111 [8]=2111 [9]=2111 [10]=2111 [11]=2111 [12]=2111 [13]=2111 [14]=2111 [15]=2111 [16]=2111) OVSCANY1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0) OVSCANY2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0) CUTX=([1]=3 [2]=9 [3]=3 [4]=9 [5]=3 [6]=9 [7]=3 [8]=9 [9]=9 [10]=3 [11]=9 [12]=3 [13]=9 [14]=3 [15]=9 [16]=3) CUTY=([1]=18 [2]=18 [3]=48 [4]=48 [5]=18 [6]=18 [7]=48 [8]=48 [9]=48 [10]=48 [11]=18 [12]=18 [13]=48 [14]=48 [15]=18 [16]=18) SIZEX=([1]=2056 [2]=2056 [3]=2056 [4]=2056 [5]=2056 [6]=2056 [7]=2056 [8]=2056 [9]=2056 [10]=2056 [11]=2056 [12]=2056 [13]=2056 [14]=2056 [15]=2056 [16]=2056) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048 [9]=2048 [10]=2048 [11]=2048 [12]=2048 [13]=2048 [14]=2048 [15]=2048 [16]=2048) REFPIXX=([1]=-2240 [2]=-129 [3]=-2212 [4]=-120 [5]=2152 [6]=4249 [7]=2144 [8]=4233 [9]=-119 [10]=-2218 [11]=-111 [12]=-2200 [13]=4263 [14]=2158 [15]=4241 [16]=2150) REFPIXY=([1]=4264 [2]=4230 [3]=2157 [4]=2148 [5]=4231 [6]=4251 [7]=2151 [8]=2160 [9]=-2187 [10]=-2219 [11]=-108 [12]=-117 [13]=-2210 [14]=-2182 [15]=-109 [16]=-99) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_1.reg000066400000000000000000000002311417631501300217120ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(3.6716324,2044.7655,1867.143,2047.4606,1859.7258,40.367421,3.5728507,32.950226) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_10.reg000066400000000000000000000002331417631501300217740ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(3.6716324,2031.7854,1867.143,2034.4805,1863.4344,-1.0036199,3.5728507,-1.0036199) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_11.reg000066400000000000000000000002301417631501300217720ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(6.9621729,2043.8722,2058.1358,2044.8643,2058.1358,27.38733,7.2814479,27.38733) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_12.reg000066400000000000000000000002311417631501300217740ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(3.6716324,2044.7655,1867.143,2047.4606,1859.7258,40.367421,3.5728507,32.950226) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_13.reg000066400000000000000000000002321417631501300217760ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(120.49245,2013.2424,2054.4271,2017.0498,2052.3611,2.6054299,120.39367,1.4271491) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_14.reg000066400000000000000000000002341417631501300220010ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(1.399277,2016.0577,2052.5729,2017.0498,2052.5729,-0.42714932,1.718552,-0.42714932) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_15.reg000066400000000000000000000002311417631501300217770ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(164.99561,2039.2026,2054.4271,2046.7186,2054.2154,20.671493,164.89683,27.38733) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_16.reg000066400000000000000000000002261417631501300220040ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(1.399277,2042.0179,2052.5729,2043.01,2052.5729,25.533032,1.718552,25.533032) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_2.reg000066400000000000000000000002301417631501300217120ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(7.2814165,2043.01,2056.2814,2046.7186,2048.8643,38.513122,5.4271493,40.367421) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_3.reg000066400000000000000000000002311417631501300217140ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(3.6716324,2015.0967,1867.143,2017.7918,1883.8317,3.8705882,3.5728507,3.2814477) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_4.reg000066400000000000000000000002341417631501300217200ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(14.433484,2011.7059,2056.2814,2011.4869,2054.9041,-0.2561086,11.466968,-0.2561086) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_5.reg000066400000000000000000000002311417631501300217160ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(1.399277,2047.5808,2055.8045,2047.7385,2057.6588,43.241629,3.0959276,56.221719) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_6.reg000066400000000000000000000002321417631501300217200ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(114.83077,2046.7186,2055.8045,2047.7385,2054.4271,38.513122,112.97647,31.095928) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_7.reg000066400000000000000000000002341417631501300217230ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(1.399277,2016.0577,2052.5729,2017.0498,2052.5729,-0.42714932,1.718552,-0.42714932) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_8.reg000066400000000000000000000002311417631501300217210ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(116.68507,2022.6127,2057.6588,2023.6326,2054.4271,1.4271493,118.53937,3.281448) THELI-3.1.3/config/instruments/MOSAIC-III@KPNO_4m_9.reg000066400000000000000000000002341417631501300217250ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(1.399277,2016.0577,2052.5729,2017.0498,2052.5729,-0.42714932,1.718552,-0.42714932) THELI-3.1.3/config/instruments/MOSAIC-III_4@KPNO_4m.ini000066400000000000000000000012061417631501300217220ustar00rootroot00000000000000INSTRUMENT=MOSAIC-III_4@KPNO_4m NCHIPS=4 # Geographic location OBSLAT=31.95 OBSLONG=-111.6 # Plate scale PIXSCALE=0.257 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANY1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANY2=([1]=0 [2]=0 [3]=0 [4]=0) CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=4112 [2]=4112 [3]=4112 [4]=4112) SIZEY=([1]=4096 [2]=4096 [3]=4096 [4]=4096) REFPIXX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) REFPIXY=([1]=2048 [2]=2048 [3]=2048 [4]=2048) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/MOSAIC-III_4@KPNO_4m_1.reg000066400000000000000000000001651417631501300221430ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(5.3500668,4072.6499,3953,4073,3941,57,5,45) THELI-3.1.3/config/instruments/MOSAIC-III_4@KPNO_4m_2.reg000066400000000000000000000001671417631501300221460ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(161.35007,4072.6499,4109,4073,4097,57,161,45) THELI-3.1.3/config/instruments/MOSAIC-III_4@KPNO_4m_3.reg000066400000000000000000000001651417631501300221450ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(5.3500668,4072.6499,3953,4073,3949,33,5,45) THELI-3.1.3/config/instruments/MOSAIC-III_4@KPNO_4m_4.reg000066400000000000000000000001671417631501300221500ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(157.35007,4064.6499,4105,4065,4093,49,157,37) THELI-3.1.3/config/instruments/MOSAIC-II_15@CTIO.ahead000066400000000000000000000075101417631501300215510ustar00rootroot00000000000000CRPIX1 = 4.385776026E+03 / Reference pixel on this axis CRPIX2 = 4.199929111E+03 / Reference pixel on this axis CD1_1 = -2.598598846E-06 / Linear projection matrix CD1_2 = 7.372960962E-05 / Linear projection matrix CD2_1 = 7.316578211E-05 / Linear projection matrix CD2_2 = 1.346184015E-06 / Linear projection matrix END CRPIX1 = 2.243964417E+03 / Reference pixel on this axis CRPIX2 = 4.156214408E+03 / Reference pixel on this axis CD1_1 = -1.932681548E-06 / Linear projection matrix CD1_2 = 7.430044824E-05 / Linear projection matrix CD2_1 = 7.461601131E-05 / Linear projection matrix CD2_2 = 1.652578141E-06 / Linear projection matrix END CRPIX1 = 1.328995240E+02 / Reference pixel on this axis CRPIX2 = 4.154908085E+03 / Reference pixel on this axis CD1_1 = -1.624415917E-06 / Linear projection matrix CD1_2 = 7.424437472E-05 / Linear projection matrix CD2_1 = 7.456064298E-05 / Linear projection matrix CD2_2 = 2.020116178E-06 / Linear projection matrix END CRPIX1 = -3.056069270E+03 / Reference pixel on this axis CRPIX2 = 4.193735269E+03 / Reference pixel on this axis CD1_1 = -9.798079151E-07 / Linear projection matrix CD1_2 = 7.353011973E-05 / Linear projection matrix CD2_1 = 7.277996409E-05 / Linear projection matrix CD2_2 = 2.443408604E-06 / Linear projection matrix END CRPIX1 = 4.400041472E+03 / Reference pixel on this axis CRPIX2 = -1.843546076E+01 / Reference pixel on this axis CD1_1 = -1.192492695E-06 / Linear projection matrix CD1_2 = 7.371686453E-05 / Linear projection matrix CD2_1 = 7.320299964E-05 / Linear projection matrix CD2_2 = 2.475451998E-06 / Linear projection matrix END CRPIX1 = 2.249463959E+03 / Reference pixel on this axis CRPIX2 = 8.372370495E+00 / Reference pixel on this axis CD1_1 = -1.537812405E-06 / Linear projection matrix CD1_2 = 7.409689971E-05 / Linear projection matrix CD2_1 = 7.445230921E-05 / Linear projection matrix CD2_2 = 2.049698291E-06 / Linear projection matrix END CRPIX1 = 1.362658841E+02 / Reference pixel on this axis CRPIX2 = 8.919800407E+00 / Reference pixel on this axis CD1_1 = -1.956172391E-06 / Linear projection matrix CD1_2 = 7.418701509E-05 / Linear projection matrix CD2_1 = 7.453284595E-05 / Linear projection matrix CD2_2 = 1.607488755E-06 / Linear projection matrix END CRPIX1 = -2.005987455E+03 / Reference pixel on this axis CRPIX2 = -3.308026261E+01 / Reference pixel on this axis CD1_1 = -2.583669704E-06 / Linear projection matrix CD1_2 = 7.365390029E-05 / Linear projection matrix CD2_1 = 7.316581856E-05 / Linear projection matrix CD2_2 = 1.234474630E-06 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSAIC-II_15@CTIO.ini000066400000000000000000000022331417631501300212630ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSAIC-II_15@CTIO INSTSHORT=MOSAIC-II # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.263 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=14 [2]=2 [3]=2 [4]=1025 [5]=2 [6]=2 [7]=2 [8]=2) CUTY=([1]=2 [2]=2 [3]=2 [4]=2 [5]=8 [6]=2 [7]=2 [8]=4) SIZEX=([1]=2034 [2]=2046 [3]=2041 [4]=1022 [5]=2039 [6]=2046 [7]=2046 [8]=2046) SIZEY=([1]=4095 [2]=4092 [3]=4094 [4]=4094 [5]=4089 [6]=4095 [7]=4095 [8]=4093) # Reference pixels for each chip. REFPIXX=([1]=4196 [2]=2045 [3]=-61 [4]=-3230 [5]=4197 [6]=2047 [7]=-67 [8]=-2210) REFPIXY=([1]=4174 [2]=4133 [3]=4127 [4]=4146 [5]=-43 [6]=-19 [7]=-23 [8]=-58) TYPE=OPT THELI-3.1.3/config/instruments/MOSAIC-II_16@CTIO.ahead000066400000000000000000000074401417631501300215540ustar00rootroot00000000000000CRPIX1 = 4.219648410627E+03 / Reference pixel on this axis CRPIX2 = 4.148736279581E+03 / Reference pixel on this axis CD1_1 = -1.390012982044E-06 / Linear projection matrix CD1_2 = 7.383522401459E-05 / Linear projection matrix CD2_1 = 7.330948407242E-05 / Linear projection matrix CD2_2 = 3.857249096193E-07 / Linear projection matrix END CRPIX1 = 2.078606511602E+03 / Reference pixel on this axis CRPIX2 = 4.121423639231E+03 / Reference pixel on this axis CD1_1 = -9.366896057230E-07 / Linear projection matrix CD1_2 = 7.422601881131E-05 / Linear projection matrix CD2_1 = 7.451901840131E-05 / Linear projection matrix CD2_2 = 6.145727800826E-07 / Linear projection matrix END CRPIX1 = -3.380319099895E+01 / Reference pixel on this axis CRPIX2 = 4.119747476926E+03 / Reference pixel on this axis CD1_1 = -6.789018671966E-07 / Linear projection matrix CD1_2 = 7.424358618408E-05 / Linear projection matrix CD2_1 = 7.452452746865E-05 / Linear projection matrix CD2_2 = 9.672408313488E-07 / Linear projection matrix END CRPIX1 = -2.166684502038E+03 / Reference pixel on this axis CRPIX2 = 4.136653541182E+03 / Reference pixel on this axis CD1_1 = -3.173257580366E-07 / Linear projection matrix CD1_2 = 7.386778867162E-05 / Linear projection matrix CD2_1 = 7.340238910748E-05 / Linear projection matrix CD2_2 = 1.224955201192E-06 / Linear projection matrix END CRPIX1 = 4.221703407246E+03 / Reference pixel on this axis CRPIX2 = -3.428519344128E+01 / Reference pixel on this axis CD1_1 = -4.505459473331E-07 / Linear projection matrix CD1_2 = 7.383932377318E-05 / Linear projection matrix CD2_1 = 7.332622818637E-05 / Linear projection matrix CD2_2 = 1.354257993685E-06 / Linear projection matrix END CRPIX1 = 2.081270718126E+03 / Reference pixel on this axis CRPIX2 = -2.402771790623E+01 / Reference pixel on this axis CD1_1 = -6.233586504990E-07 / Linear projection matrix CD1_2 = 7.414388936822E-05 / Linear projection matrix CD2_1 = 7.448742692311E-05 / Linear projection matrix CD2_2 = 1.000256495302E-06 / Linear projection matrix END CRPIX1 = -3.106585082115E+01 / Reference pixel on this axis CRPIX2 = -2.643440145763E+01 / Reference pixel on this axis CD1_1 = -8.716713712746E-07 / Linear projection matrix CD1_2 = 7.418927351089E-05 / Linear projection matrix CD2_1 = 7.449316083390E-05 / Linear projection matrix CD2_2 = 5.849174005713E-07 / Linear projection matrix END CRPIX1 = -2.169299411462E+03 / Reference pixel on this axis CRPIX2 = -5.645553721226E+01 / Reference pixel on this axis CD1_1 = -1.405922593032E-06 / Linear projection matrix CD1_2 = 7.375528340784E-05 / Linear projection matrix CD2_1 = 7.330462882868E-05 / Linear projection matrix CD2_2 = 2.639914483855E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSAIC-II_16@CTIO.ini000066400000000000000000000022241417631501300212640ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSAIC-II_16@CTIO INSTSHORT=MOSAIC-II # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.264 GAIN=2.6 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048) SIZEY=([1]=4096 [2]=4096 [3]=4096 [4]=4096 [5]=4096 [6]=4096 [7]=4096 [8]=4096) # Reference pixels for each chip. REFPIXX=([1]=4196 [2]=2045 [3]=-61 [4]=-2210 [5]=4197 [6]=2047 [7]=-67 [8]=-2210) REFPIXY=([1]=4174 [2]=4133 [3]=4127 [4]=4146 [5]=-43 [6]=-19 [7]=-23 [8]=-58) TYPE=OPT THELI-3.1.3/config/instruments/MOSAIC-II_16_old@CTIO.ahead000066400000000000000000000075101417631501300224100ustar00rootroot00000000000000CRPIX1 = 4.358642556822E+03 / Reference pixel on this axis CRPIX2 = 4.310388638036E+03 / Reference pixel on this axis CD1_1 = -1.220773303584E-06 / Linear projection matrix CD1_2 = 7.372637422222E-05 / Linear projection matrix CD2_1 = 7.319102976495E-05 / Linear projection matrix CD2_2 = 1.216637980061E-08 / Linear projection matrix END CRPIX1 = 2.206134517693E+03 / Reference pixel on this axis CRPIX2 = 4.268267243914E+03 / Reference pixel on this axis CD1_1 = -6.330207532892E-07 / Linear projection matrix CD1_2 = 7.432877475396E-05 / Linear projection matrix CD2_1 = 7.454300634107E-05 / Linear projection matrix CD2_2 = 2.985127434950E-07 / Linear projection matrix END CRPIX1 = 9.309893072339E+01 / Reference pixel on this axis CRPIX2 = 4.265118145158E+03 / Reference pixel on this axis CD1_1 = -3.281067924807E-07 / Linear projection matrix CD1_2 = 7.430184427940E-05 / Linear projection matrix CD2_1 = 7.454911403378E-05 / Linear projection matrix CD2_2 = 6.563772445989E-07 / Linear projection matrix END CRPIX1 = -2.039640299432E+03 / Reference pixel on this axis CRPIX2 = 4.287219918344E+03 / Reference pixel on this axis CD1_1 = 1.155951458657E-07 / Linear projection matrix CD1_2 = 7.393820429281E-05 / Linear projection matrix CD2_1 = 7.340656342065E-05 / Linear projection matrix CD2_2 = 9.220348936098E-07 / Linear projection matrix END CRPIX1 = 4.354600373989E+03 / Reference pixel on this axis CRPIX2 = 1.013981791488E+02 / Reference pixel on this axis CD1_1 = 1.040074878616E-07 / Linear projection matrix CD1_2 = 7.383859211896E-05 / Linear projection matrix CD2_1 = 7.326144065431E-05 / Linear projection matrix CD2_2 = 1.113177038439E-06 / Linear projection matrix END CRPIX1 = 2.206382327900E+03 / Reference pixel on this axis CRPIX2 = 1.252185595048E+02 / Reference pixel on this axis CD1_1 = -2.769293726124E-07 / Linear projection matrix CD1_2 = 7.431319363878E-05 / Linear projection matrix CD2_1 = 7.454967241581E-05 / Linear projection matrix CD2_2 = 6.879896998482E-07 / Linear projection matrix END CRPIX1 = 9.646756057520E+01 / Reference pixel on this axis CRPIX2 = 1.222250236044E+02 / Reference pixel on this axis CD1_1 = -5.824774911779E-07 / Linear projection matrix CD1_2 = 7.434669382593E-05 / Linear projection matrix CD2_1 = 7.457138088476E-05 / Linear projection matrix CD2_2 = 2.981630029200E-07 / Linear projection matrix END CRPIX1 = -2.046562926320E+03 / Reference pixel on this axis CRPIX2 = 8.504593657535E+01 / Reference pixel on this axis CD1_1 = -1.155021313731E-06 / Linear projection matrix CD1_2 = 7.370321829193E-05 / Linear projection matrix CD2_1 = 7.322597958673E-05 / Linear projection matrix CD2_2 = -8.686015344108E-08 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSAIC-II_16_old@CTIO.ini000066400000000000000000000022201417631501300221160ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSAIC-II_16_old@CTIO INSTSHORT=MOSAIC-II # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.263 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048) SIZEY=([1]=4096 [2]=4096 [3]=4096 [4]=4096 [5]=4096 [6]=4096 [7]=4096 [8]=4096) # Reference pixels for each chip. REFPIXX=([1]=4196 [2]=2045 [3]=-61 [4]=-2210 [5]=4197 [6]=2047 [7]=-67 [8]=-2210) REFPIXY=([1]=4174 [2]=4133 [3]=4127 [4]=4146 [5]=-43 [6]=-19 [7]=-23 [8]=-58) TYPE=OPT THELI-3.1.3/config/instruments/MOSAIC-II_8@CTIO.ahead000066400000000000000000000075101417631501300214730ustar00rootroot00000000000000CRPIX1 = 4.270222203E+03 / Reference pixel on this axis CRPIX2 = 4.265399080E+03 / Reference pixel on this axis CD1_1 = -1.282308180E-06 / Linear projection matrix CD1_2 = 7.360829879E-05 / Linear projection matrix CD2_1 = 7.315803119E-05 / Linear projection matrix CD2_2 = -8.700045215E-08 / Linear projection matrix END CRPIX1 = 2.133709275E+03 / Reference pixel on this axis CRPIX2 = 4.225478448E+03 / Reference pixel on this axis CD1_1 = -7.470917167E-07 / Linear projection matrix CD1_2 = 7.410989823E-05 / Linear projection matrix CD2_1 = 7.436614304E-05 / Linear projection matrix CD2_2 = 2.205945528E-07 / Linear projection matrix END CRPIX1 = 1.605287353E+01 / Reference pixel on this axis CRPIX2 = 4.215684034E+03 / Reference pixel on this axis CD1_1 = -2.233249167E-07 / Linear projection matrix CD1_2 = 7.432416677E-05 / Linear projection matrix CD2_1 = 7.461099675E-05 / Linear projection matrix CD2_2 = 6.485450863E-07 / Linear projection matrix END CRPIX1 = -2.114029198E+03 / Reference pixel on this axis CRPIX2 = 4.256322064E+03 / Reference pixel on this axis CD1_1 = 5.504790512E-07 / Linear projection matrix CD1_2 = 7.383338867E-05 / Linear projection matrix CD2_1 = 7.343712197E-05 / Linear projection matrix CD2_2 = 7.679340833E-07 / Linear projection matrix END CRPIX1 = 4.276145771E+03 / Reference pixel on this axis CRPIX2 = 3.122920907E+01 / Reference pixel on this axis CD1_1 = 4.515695623E-07 / Linear projection matrix CD1_2 = 7.369461543E-05 / Linear projection matrix CD2_1 = 7.313449910E-05 / Linear projection matrix CD2_2 = 7.841819297E-07 / Linear projection matrix END CRPIX1 = 2.129733778E+03 / Reference pixel on this axis CRPIX2 = 7.886780784E+01 / Reference pixel on this axis CD1_1 = -2.242319125E-07 / Linear projection matrix CD1_2 = 7.427717662E-05 / Linear projection matrix CD2_1 = 7.457920305E-05 / Linear projection matrix CD2_2 = 6.738973136E-07 / Linear projection matrix END CRPIX1 = 1.795276219E+01 / Reference pixel on this axis CRPIX2 = 7.446525474E+01 / Reference pixel on this axis CD1_1 = -6.189957984E-07 / Linear projection matrix CD1_2 = 7.422309087E-05 / Linear projection matrix CD2_1 = 7.452427945E-05 / Linear projection matrix CD2_2 = 2.243813842E-07 / Linear projection matrix END CRPIX1 = -2.126989702E+03 / Reference pixel on this axis CRPIX2 = 3.866252382E+01 / Reference pixel on this axis CD1_1 = -1.156327619E-06 / Linear projection matrix CD1_2 = 7.368328306E-05 / Linear projection matrix CD2_1 = 7.317761643E-05 / Linear projection matrix CD2_2 = -1.290428499E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSAIC-II_8@CTIO.ini000066400000000000000000000023031417631501300212030ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSAIC-II_8@CTIO INSTSHORT=MOSAIC-II # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.263 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=10 [2]=10 [3]=10 [4]=10 [5]=2100 [6]=2100 [7]=2100 [8]=2100) OVSCANX2=([1]=40 [2]=40 [3]=40 [4]=40 [5]=2130 [6]=2130 [7]=2130 [8]=2130) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=80 [2]=66 [3]=66 [4]=66 [5]=26 [6]=26 [7]=26 [8]=26) CUTY=([1]=10 [2]=10 [3]=10 [4]=10 [5]=10 [6]=5 [7]=5 [8]=5) SIZEX=([1]=2031 [2]=2044 [3]=2040 [4]=2044 [5]=2044 [6]=2044 [7]=2044 [8]=2044) SIZEY=([1]=4080 [2]=4080 [3]=4080 [4]=4080 [5]=4080 [6]=4080 [7]=4080 [8]=4080) # Reference pixels for each chip. REFPIXX=([1]=4236 [2]=2088 [3]=-19 [4]=-2165 [5]=4197 [6]=2048 [7]=-65 [8]=-2207) REFPIXY=([1]=4170 [2]=4130 [3]=4124 [4]=4143 [5]=-45 [6]=-21 [7]=-26 [8]=-60) TYPE=OPT THELI-3.1.3/config/instruments/MOSAIC-II_8_2x2@CTIO.ahead000066400000000000000000000075101417631501300221660ustar00rootroot00000000000000CRPIX1 = 2.139431907E+03 / Reference pixel on this axis CRPIX2 = 2.150886981E+03 / Reference pixel on this axis CD1_1 = -2.012006509E-06 / Linear projection matrix CD1_2 = 1.473390912E-04 / Linear projection matrix CD2_1 = 1.462604667E-04 / Linear projection matrix CD2_2 = -5.913656733E-07 / Linear projection matrix END CRPIX1 = 1.063289753E+03 / Reference pixel on this axis CRPIX2 = 2.130267563E+03 / Reference pixel on this axis CD1_1 = -6.756975337E-07 / Linear projection matrix CD1_2 = 1.483169204E-04 / Linear projection matrix CD2_1 = 1.489226787E-04 / Linear projection matrix CD2_2 = 1.244298530E-09 / Linear projection matrix END CRPIX1 = 6.154377567E+00 / Reference pixel on this axis CRPIX2 = 2.127644417E+03 / Reference pixel on this axis CD1_1 = -1.293842458E-07 / Linear projection matrix CD1_2 = 1.484022172E-04 / Linear projection matrix CD2_1 = 1.490441221E-04 / Linear projection matrix CD2_2 = 7.507039014E-07 / Linear projection matrix END CRPIX1 = -1.062525214E+03 / Reference pixel on this axis CRPIX2 = 2.139060462E+03 / Reference pixel on this axis CD1_1 = 7.735989890E-07 / Linear projection matrix CD1_2 = 1.476266217E-04 / Linear projection matrix CD2_1 = 1.466375443E-04 / Linear projection matrix CD2_2 = 1.331766810E-06 / Linear projection matrix END CRPIX1 = 2.137521975E+03 / Reference pixel on this axis CRPIX2 = 4.392301022E+01 / Reference pixel on this axis CD1_1 = 7.925866681E-07 / Linear projection matrix CD1_2 = 1.473614608E-04 / Linear projection matrix CD2_1 = 1.463322206E-04 / Linear projection matrix CD2_2 = 1.747364922E-06 / Linear projection matrix END CRPIX1 = 1.062087024E+03 / Reference pixel on this axis CRPIX2 = 5.664208691E+01 / Reference pixel on this axis CD1_1 = 5.686545668E-08 / Linear projection matrix CD1_2 = 1.484677287E-04 / Linear projection matrix CD2_1 = 1.489716897E-04 / Linear projection matrix CD2_2 = 8.029126747E-07 / Linear projection matrix END CRPIX1 = 6.327778897E+00 / Reference pixel on this axis CRPIX2 = 5.396626707E+01 / Reference pixel on this axis CD1_1 = -8.109680505E-07 / Linear projection matrix CD1_2 = 1.483535129E-04 / Linear projection matrix CD2_1 = 1.489351014E-04 / Linear projection matrix CD2_2 = -5.726685673E-08 / Linear projection matrix END CRPIX1 = -1.060374012E+03 / Reference pixel on this axis CRPIX2 = 4.332775148E+01 / Reference pixel on this axis CD1_1 = -1.457502544E-06 / Linear projection matrix CD1_2 = 1.478546084E-04 / Linear projection matrix CD2_1 = 1.466871428E-04 / Linear projection matrix CD2_2 = -5.083894485E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSAIC-II_8_2x2@CTIO.ini000066400000000000000000000023041417631501300216770ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSAIC-II_8_2x2@CTIO INSTSHORT=MOSAIC-II # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.526 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=5 [2]=5 [3]=5 [4]=5 [5]=1060 [6]=1060 [7]=1060 [8]=1060) OVSCANX2=([1]=40 [2]=40 [3]=40 [4]=40 [5]=1095 [6]=1095 [7]=1095 [8]=1095) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=70 [2]=70 [3]=70 [4]=70 [5]=20 [6]=20 [7]=20 [8]=20) CUTY=([1]=10 [2]=10 [3]=10 [4]=10 [5]=10 [6]=10 [7]=10 [8]=10) SIZEX=([1]=1015 [2]=1015 [3]=1015 [4]=1015 [5]=1015 [6]=1015 [7]=1015 [8]=1015) SIZEY=([1]=2030 [2]=2030 [3]=2030 [4]=2030 [5]=2030 [6]=2030 [7]=2030 [8]=2030) # Reference pixels for each chip. REFPIXX=([1]=2150 [2]=1076 [3]=70 [4]=-1002 [5]=2099 [6]=1024 [7]=15 [8]=-1055) REFPIXY=([1]=2085 [2]=2065 [3]=2062 [4]=2072 [5]=-22 [6]=-10 [7]=-12 [8]=-30) TYPE=OPT THELI-3.1.3/config/instruments/MOSAIC-I_old@KPNO_0.9m.ini000066400000000000000000000023031417631501300222550ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSAIC-I_old@KPNO_0.9m INSTSHORT=MOSAIC-I # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=31.96 OBSLONG=-111.60 # Pixel scale in arcsec PIXSCALE=0.425 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=1 [2]=1 [3]=1 [4]=1 [5]=2105 [6]=2105 [7]=2105 [8]=2105) OVSCANX2=([1]=30 [2]=30 [3]=30 [4]=30 [5]=2135 [6]=2135 [7]=2135 [8]=2135) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=75 [2]=70 [3]=66 [4]=66 [5]=26 [6]=26 [7]=26 [8]=26) CUTY=([1]=15 [2]=15 [3]=2 [4]=5 [5]=2 [6]=2 [7]=5 [8]=5) SIZEX=([1]=2035 [2]=2040 [3]=2044 [4]=2044 [5]=2044 [6]=2044 [7]=2044 [8]=2044) SIZEY=([1]=4076 [2]=4076 [3]=4089 [4]=4086 [5]=4089 [6]=4089 [7]=4086 [8]=4086) # Reference pixels for each chip. REFPIXX=([1]=4350 [2]=2206 [3]=97 [4]=-2036 [5]=4302 [6]=2175 [7]=55 [8]=-2080) REFPIXY=([1]=3992 [2]=3956 [3]=3957 [4]=3980 [5]=-204 [6]=-200 [7]=-190 [8]=-206) TYPE=OPT THELI-3.1.3/config/instruments/MOSAIC-I_old@KPNO_4.0m.ahead000066400000000000000000000075101417631501300225400ustar00rootroot00000000000000CRPIX1 = 4.193174353E+03 / Reference pixel on this axis CRPIX2 = 4.273516503E+03 / Reference pixel on this axis CD1_1 = 5.340047566E-07 / Linear projection matrix CD1_2 = -7.172092693E-05 / Linear projection matrix CD2_1 = -7.127580359E-05 / Linear projection matrix CD2_2 = 4.891436664E-07 / Linear projection matrix END CRPIX1 = 2.057752927E+03 / Reference pixel on this axis CRPIX2 = 4.242966692E+03 / Reference pixel on this axis CD1_1 = 6.414875709E-08 / Linear projection matrix CD1_2 = -7.212140890E-05 / Linear projection matrix CD2_1 = -7.236816332E-05 / Linear projection matrix CD2_2 = 1.632725625E-07 / Linear projection matrix END CRPIX1 = -4.395667887E+01 / Reference pixel on this axis CRPIX2 = 4.251450652E+03 / Reference pixel on this axis CD1_1 = -2.031063827E-07 / Linear projection matrix CD1_2 = -7.222004934E-05 / Linear projection matrix CD2_1 = -7.243564838E-05 / Linear projection matrix CD2_2 = -2.440234696E-08 / Linear projection matrix END CRPIX1 = -2.182275311E+03 / Reference pixel on this axis CRPIX2 = 4.276377448E+03 / Reference pixel on this axis CD1_1 = -6.048099136E-07 / Linear projection matrix CD1_2 = -7.169876486E-05 / Linear projection matrix CD2_1 = -7.128132297E-05 / Linear projection matrix CD2_2 = -3.629556176E-07 / Linear projection matrix END CRPIX1 = 4.201017252E+03 / Reference pixel on this axis CRPIX2 = 9.015570846E+01 / Reference pixel on this axis CD1_1 = -7.345064228E-07 / Linear projection matrix CD1_2 = -7.177030628E-05 / Linear projection matrix CD2_1 = -7.134356891E-05 / Linear projection matrix CD2_2 = -8.026841171E-08 / Linear projection matrix END CRPIX1 = 2.066842345E+03 / Reference pixel on this axis CRPIX2 = 1.038972562E+02 / Reference pixel on this axis CD1_1 = -3.882620817E-07 / Linear projection matrix CD1_2 = -7.210999588E-05 / Linear projection matrix CD2_1 = -7.234578661E-05 / Linear projection matrix CD2_2 = 1.264079834E-07 / Linear projection matrix END CRPIX1 = -4.760794527E+01 / Reference pixel on this axis CRPIX2 = 1.083982944E+02 / Reference pixel on this axis CD1_1 = -1.294315770E-07 / Linear projection matrix CD1_2 = -7.209440693E-05 / Linear projection matrix CD2_1 = -7.237034896E-05 / Linear projection matrix CD2_2 = 3.936478296E-07 / Linear projection matrix END CRPIX1 = -2.183512100E+03 / Reference pixel on this axis CRPIX2 = 9.296086111E+01 / Reference pixel on this axis CD1_1 = 3.110436058E-07 / Linear projection matrix CD1_2 = -7.171344977E-05 / Linear projection matrix CD2_1 = -7.125847879E-05 / Linear projection matrix CD2_2 = 6.198675693E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSAIC-I_old@KPNO_4.0m.ini000066400000000000000000000023041417631501300222510ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSAIC-I_old@KPNO_4.0m INSTSHORT=MOSAIC-I # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=31.96 OBSLONG=-111.60 # Pixel scale in arcsec PIXSCALE=0.260 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=1 [2]=1 [3]=1 [4]=1 [5]=2105 [6]=2105 [7]=2105 [8]=2105) OVSCANX2=([1]=30 [2]=30 [3]=30 [4]=30 [5]=2135 [6]=2135 [7]=2135 [8]=2135) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=75 [2]=70 [3]=66 [4]=66 [5]=26 [6]=26 [7]=26 [8]=26) CUTY=([1]=15 [2]=15 [3]=2 [4]=5 [5]=2 [6]=2 [7]=5 [8]=5) SIZEX=([1]=2035 [2]=2040 [3]=2044 [4]=2044 [5]=2044 [6]=2044 [7]=2044 [8]=2044) SIZEY=([1]=4076 [2]=4076 [3]=4089 [4]=4086 [5]=4089 [6]=4089 [7]=4086 [8]=4086) # Reference pixels for each chip. REFPIXX=([1]=4350 [2]=2206 [3]=97 [4]=-2036 [5]=4302 [6]=2175 [7]=55 [8]=-2080) REFPIXY=([1]=3992 [2]=3956 [3]=3957 [4]=3980 [5]=-204 [6]=-200 [7]=-190 [8]=-206) TYPE=OPT THELI-3.1.3/config/instruments/MOSCA_2x2@NOT.ahead000066400000000000000000000036161417631501300212340ustar00rootroot00000000000000CRPIX1 = 1.034998036591E+03 / Reference pixel on this axis CRPIX2 = 1.039542971578E+03 / Reference pixel on this axis CD1_1 = -6.023495613803E-05 / Linear projection matrix CD1_2 = -7.239326657165E-07 / Linear projection matrix CD2_1 = -6.661887330115E-07 / Linear projection matrix CD2_2 = 6.023349146534E-05 / Linear projection matrix END CRPIX1 = -1.698578282813E+01 / Reference pixel on this axis CRPIX2 = 1.026470666315E+03 / Reference pixel on this axis CD1_1 = -6.021421668808E-05 / Linear projection matrix CD1_2 = -3.270392191294E-07 / Linear projection matrix CD2_1 = -3.778686244445E-07 / Linear projection matrix CD2_2 = 6.022864256178E-05 / Linear projection matrix END CRPIX1 = 1.035939904736E+03 / Reference pixel on this axis CRPIX2 = -1.634735652859E+01 / Reference pixel on this axis CD1_1 = -6.024359799787E-05 / Linear projection matrix CD1_2 = 3.166083316385E-08 / Linear projection matrix CD2_1 = -5.793481284478E-08 / Linear projection matrix CD2_2 = 6.024894407233E-05 / Linear projection matrix END CRPIX1 = -1.722915415602E+01 / Reference pixel on this axis CRPIX2 = -1.521579272289E+01 / Reference pixel on this axis CD1_1 = -6.021944826597E-05 / Linear projection matrix CD1_2 = -2.971201523512E-07 / Linear projection matrix CD2_1 = -2.316154914769E-07 / Linear projection matrix CD2_2 = 6.022753183706E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/MOSCA_2x2@NOT.ini000066400000000000000000000016351417631501300207500ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSCA_2x2@NOT INSTSHORT=MOSCA # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.217 GAIN=4.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=2 [2]=2 [3]=2 [4]=2) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=1021 [2]=1021 [3]=1021 [4]=1021) SIZEY=([1]=1016 [2]=1016 [3]=1016 [4]=1016) # Reference pixels for each chip. REFPIXX=([1]=1092 [2]=38 [3]=1092 [4]=38) REFPIXY=([1]=1057 [2]=1057 [3]=8 [4]=8) TYPE=OPT THELI-3.1.3/config/instruments/MOSFIRE@KECK.ini000066400000000000000000000013771417631501300205770ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=MOSFIRE@KECK INSTSHORT=MOSFIRE # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.1799 GAIN=2.15 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) # Camera type TYPE=NIR THELI-3.1.3/config/instruments/MOSFIRE@KECK.reg000066400000000000000000000012421417631501300205640ustar00rootroot00000000000000# Region file format: DS9 version 4.1 global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 image polygon(103.38933,1667.8429,195.85079,1790,304.50988,1895.2846,413.84387,1976.2727,513.05435,2039.0385,1573.1522,2037.2599,1701.8755,1959.5642,1836.1808,1852.2549,1918.2253,1762.4032,1979.9348,1683.5296,2038.42,1598.082,2038.1403,472.15711,1996.9713,400.17391,1929.0356,312.37549,1845.3478,217.88933,1731.9644,120.70356,1585.3004,25.916996,526.94763,21.077075,411.53953,85.192688,317.37154,158.49802,201.28854,271.88142,119.98221,368.65119,41.283597,498.24704,40.26087,1552.6482) THELI-3.1.3/config/instruments/NACO@VLT.ini000066400000000000000000000005001417631501300201260ustar00rootroot00000000000000INSTRUMENT=NACO@VLT INSTSHORT=NACO NCHIPS=1 # Geographic location OBSLAT=-24.67 OBSLONG=-70.42 # Plate scale PIXSCALE=0.01327 GAIN=1.0 # Detector geometries OVSCANX1=([1]=0) OVSCANX2=([1]=0) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=NIRMIR THELI-3.1.3/config/instruments/NACO@VLT_1.reg000066400000000000000000000075011417631501300203540ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out physical polygon(925.17355,1028.8265,1076.8265,1028.8265,1076.8265,877.17355,1033,864) polygon(1006.9,205.6,1015.3,201.1,1011.4,194.8,1003.3,183.4,990.47535,183.27535,990.7,199.6) polygon(319.91309,990.68691,332.48691,990.68691,332.48691,978.11309,319.91309,978.11309) polygon(878.9,531.45,886.85,531.3,887.9,529.65,942.05,529.05,944,532.8,951.5,534,953.45,530.4,1026.5,530.4,1026.2,527.4,953.45,527.25,953.45,523.8,946.1,523.8,945.65,519.75,940.1,519.45,941.75,526.65,887.3,526.65,885.8,524.25,878.91674,523.96674) polygon(3.5,512.5,4.5,512.5,4.5,0.5,3.5,0.5) polygon(11.5,512.5,12.5,512.5,12.5,0.5,11.5,0.5) polygon(19.5,512.5,20.5,512.5,20.5,0.5,19.5,0.5) polygon(27.5,512.5,28.5,512.5,28.5,0.5,27.5,0.5) polygon(35.5,512.5,36.5,512.5,36.5,0.5,35.5,0.5) polygon(43.5,512.5,44.5,512.5,44.5,0.5,43.5,0.5) polygon(51.5,512.5,52.5,512.5,52.5,0.5,51.5,0.5) polygon(59.5,512.5,60.5,512.5,60.5,0.5,59.5,0.5) polygon(67.5,512.5,68.5,512.5,68.5,0.5,67.5,0.5) polygon(75.5,512.5,76.5,512.5,76.5,0.5,75.5,0.5) polygon(83.5,512.5,84.5,512.5,84.5,0.5,83.5,0.5) polygon(91.5,512.5,92.5,512.5,92.5,0.5,91.5,0.5) polygon(99.5,512.5,100.5,512.5,100.5,0.5,99.5,0.5) polygon(107.5,512.5,108.5,512.5,108.5,0.5,107.5,0.5) polygon(115.5,512.5,116.5,512.5,116.5,0.5,115.5,0.5) polygon(123.5,512.5,124.5,512.5,124.5,0.5,123.5,0.5) polygon(131.5,512.5,132.5,512.5,132.5,0.5,131.5,0.5) polygon(139.5,512.5,140.5,512.5,140.5,0.5,139.5,0.5) polygon(147.5,512.5,148.5,512.5,148.5,0.5,147.5,0.5) polygon(155.5,512.5,156.5,512.5,156.5,0.5,155.5,0.5) polygon(163.5,512.5,164.5,512.5,164.5,0.5,163.5,0.5) polygon(171.5,512.5,172.5,512.5,172.5,0.5,171.5,0.5) polygon(179.5,512.5,180.5,512.5,180.5,0.5,179.5,0.5) polygon(187.5,512.5,188.5,512.5,188.5,0.5,187.5,0.5) polygon(195.5,512.5,196.5,512.5,196.5,0.5,195.5,0.5) polygon(203.5,512.5,204.5,512.5,204.5,0.5,203.5,0.5) polygon(211.5,512.5,212.5,512.5,212.5,0.5,211.5,0.5) polygon(219.5,512.5,220.5,512.5,220.5,0.5,219.5,0.5) polygon(227.5,512.5,228.5,512.5,228.5,0.5,227.5,0.5) polygon(235.5,512.5,236.5,512.5,236.5,0.5,235.5,0.5) polygon(243.5,512.5,244.5,512.5,244.5,0.5,243.5,0.5) polygon(251.5,512.5,252.5,512.5,252.5,0.5,251.5,0.5) polygon(259.5,512.5,260.5,512.5,260.5,0.5,259.5,0.5) polygon(267.5,512.5,268.5,512.5,268.5,0.5,267.5,0.5) polygon(275.5,512.5,276.5,512.5,276.5,0.5,275.5,0.5) polygon(283.5,512.5,284.5,512.5,284.5,0.5,283.5,0.5) polygon(291.5,512.5,292.5,512.5,292.5,0.5,291.5,0.5) polygon(299.5,512.5,300.5,512.5,300.5,0.5,299.5,0.5) polygon(307.5,512.5,308.5,512.5,308.5,0.5,307.5,0.5) polygon(315.5,512.5,316.5,512.5,316.5,0.5,315.5,0.5) polygon(323.5,512.5,324.5,512.5,324.5,0.5,323.5,0.5) polygon(331.5,512.5,332.5,512.5,332.5,0.5,331.5,0.5) polygon(339.5,512.5,340.5,512.5,340.5,0.5,339.5,0.5) polygon(347.5,512.5,348.5,512.5,348.5,0.5,347.5,0.5) polygon(355.5,512.5,356.5,512.5,356.5,0.5,355.5,0.5) polygon(363.5,512.5,364.5,512.5,364.5,0.5,363.5,0.5) polygon(371.5,512.5,372.5,512.5,372.5,0.5,371.5,0.5) polygon(379.5,512.5,380.5,512.5,380.5,0.5,379.5,0.5) polygon(387.5,512.5,388.5,512.5,388.5,0.5,387.5,0.5) polygon(395.5,512.5,396.5,512.5,396.5,0.5,395.5,0.5) polygon(403.5,512.5,404.5,512.5,404.5,0.5,403.5,0.5) polygon(411.5,512.5,412.5,512.5,412.5,0.5,411.5,0.5) polygon(419.5,512.5,420.5,512.5,420.5,0.5,419.5,0.5) polygon(427.5,512.5,428.5,512.5,428.5,0.5,427.5,0.5) polygon(435.5,512.5,436.5,512.5,436.5,0.5,435.5,0.5) polygon(443.5,512.5,444.5,512.5,444.5,0.5,443.5,0.5) polygon(451.5,512.5,452.5,512.5,452.5,0.5,451.5,0.5) polygon(459.5,512.5,460.5,512.5,460.5,0.5,459.5,0.5) polygon(467.5,512.5,468.5,512.5,468.5,0.5,467.5,0.5) polygon(475.5,512.5,476.5,512.5,476.5,0.5,475.5,0.5) polygon(483.5,512.5,484.5,512.5,484.5,0.5,483.5,0.5) polygon(491.5,512.5,492.5,512.5,492.5,0.5,491.5,0.5) polygon(499.5,512.5,500.5,512.5,500.5,0.5,499.5,0.5) polygon(507.5,512.5,508.5,512.5,508.5,0.5,507.5,0.5) THELI-3.1.3/config/instruments/NACOSDI@VLT.ini000066400000000000000000000016271417631501300205010ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NACOSDI@VLT INSTSHORT=NACOSDI # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.01732 GAIN=1 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=261 [2]=255 [3]=256 [4]=256) SIZEY=([1]=256 [2]=227 [3]=233 [4]=211) # Reference pixels for each chip. REFPIXX=([1]=120 [2]=120 [3]=120 [4]=120) REFPIXY=([1]=120 [2]=120 [3]=120 [4]=120) TYPE=NIR THELI-3.1.3/config/instruments/NEWFIRM@CTIO.ahead000066400000000000000000000036201417631501300210770ustar00rootroot00000000000000CRPIX1 = 2.102400188899E+03 / Reference pixel on this axis CRPIX2 = 2.100374688847E+03 / Reference pixel on this axis CD1_1 = -1.090459632842E-04 / Linear projection matrix CD1_2 = 6.739617057429E-07 / Linear projection matrix CD2_1 = -1.077234024773E-07 / Linear projection matrix CD2_2 = 1.090345833201E-04 / Linear projection matrix END CRPIX1 = -5.509856534694E+01 / Reference pixel on this axis CRPIX2 = 2.097417469752E+03 / Reference pixel on this axis CD1_1 = -1.090629796526E-04 / Linear projection matrix CD1_2 = -4.036105206471E-07 / Linear projection matrix CD2_1 = 5.344029807939E-07 / Linear projection matrix CD2_2 = 1.090477907281E-04 / Linear projection matrix END CRPIX1 = 2.098896906663E+03 / Reference pixel on this axis CRPIX2 = -5.916768382066E+01 / Reference pixel on this axis CD1_1 = -1.089966876393E-04 / Linear projection matrix CD1_2 = -1.188692909708E-07 / Linear projection matrix CD2_1 = 8.196709571959E-07 / Linear projection matrix CD2_2 = 1.089960214893E-04 / Linear projection matrix END CRPIX1 = -5.298120733632E+01 / Reference pixel on this axis CRPIX2 = -5.017950757085E+01 / Reference pixel on this axis CD1_1 = -1.090331417785E-04 / Linear projection matrix CD1_2 = 5.103259413540E-07 / Linear projection matrix CD2_1 = -3.249747360724E-07 / Linear projection matrix CD2_2 = 1.090018372029E-04 / Linear projection matrix END THELI-3.1.3/config/instruments/NEWFIRM@CTIO.ini000066400000000000000000000016361417631501300206210ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NEWFIRM@CTIO INSTSHORT=NEWFIRM # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.394 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=2 [2]=2 [3]=2 [4]=2) CUTY=([1]=2 [2]=2 [3]=2 [4]=2) SIZEX=([1]=2046 [2]=2046 [3]=2046 [4]=2046) SIZEY=([1]=2046 [2]=2046 [3]=2046 [4]=2046) # Reference pixels for each chip. REFPIXX=([1]=2076 [2]=-79 [3]=2072 [4]=-78) REFPIXY=([1]=2096 [2]=2092 [3]=-63 [4]=-55) TYPE=NIR THELI-3.1.3/config/instruments/NEWFIRM@KPNO_4m.ahead000066400000000000000000000036201417631501300215100ustar00rootroot00000000000000CRPIX1 = 2.092567242718E+03 / Reference pixel on this axis CRPIX2 = 2.087732781413E+03 / Reference pixel on this axis CD1_1 = -1.105068595454E-04 / Linear projection matrix CD1_2 = -1.972964432628E-07 / Linear projection matrix CD2_1 = -2.199065973199E-07 / Linear projection matrix CD2_2 = 1.105067512109E-04 / Linear projection matrix END CRPIX1 = -5.294575847398E+01 / Reference pixel on this axis CRPIX2 = 2.105782161979E+03 / Reference pixel on this axis CD1_1 = -1.096647847425E-04 / Linear projection matrix CD1_2 = -2.832361209588E-07 / Linear projection matrix CD2_1 = -2.072070119934E-07 / Linear projection matrix CD2_2 = 1.092175668678E-04 / Linear projection matrix END CRPIX1 = 2.095238335755E+03 / Reference pixel on this axis CRPIX2 = -4.732397113250E+01 / Reference pixel on this axis CD1_1 = -1.097387496649E-04 / Linear projection matrix CD1_2 = -2.342325212396E-07 / Linear projection matrix CD2_1 = -2.473444702973E-07 / Linear projection matrix CD2_2 = 1.097363470536E-04 / Linear projection matrix END CRPIX1 = -5.425124815712E+01 / Reference pixel on this axis CRPIX2 = -4.873970972958E+01 / Reference pixel on this axis CD1_1 = -1.096670007885E-04 / Linear projection matrix CD1_2 = 1.381224048413E-07 / Linear projection matrix CD2_1 = 1.429267913078E-07 / Linear projection matrix CD2_2 = 1.096502664282E-04 / Linear projection matrix END THELI-3.1.3/config/instruments/NEWFIRM@KPNO_4m.ini000066400000000000000000000016371417631501300212330ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NEWFIRM@KPNO_4m INSTSHORT=NEWFIRM # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=31.95 OBSLONG=-111.6 # Pixel scale in arcsec PIXSCALE=0.397 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=2 [2]=2 [3]=2 [4]=2) CUTY=([1]=2 [2]=2 [3]=2 [4]=2) SIZEX=([1]=2046 [2]=2046 [3]=2046 [4]=2046) SIZEY=([1]=2046 [2]=2046 [3]=2046 [4]=2046) # Reference pixels for each chip. REFPIXX=([1]=2076 [2]=-79 [3]=2072 [4]=-78) REFPIXY=([1]=2096 [2]=2092 [3]=-63 [4]=-55) TYPE=NIR THELI-3.1.3/config/instruments/NICI@GEMINI.ini000066400000000000000000000013531417631501300204420ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NICI@GEMINI INSTSHORT=NICI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0179 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/NICS@TNG.ini000066400000000000000000000013511417631501300201320ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NICS@TNG INSTSHORT=NICS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.25 GAIN=5.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/NIR000066400000000000000000000007121417631501300165770ustar00rootroot00000000000000FLAMINGOS2@GEMINI.ini FourStar@LCO.ini GROND_IRIM@MPGESO.ini GSAOI@GEMINI.ini HAWKI@VLT.ini INGRID@WHT.ini ISAAC@VLT.ini LIRIS_POL@WHT.ini LIRIS@WHT.ini MMIRS@LCO.ini MOIRCS@SUBARU.ini NACOSDI@VLT.ini NEWFIRM@CTIO.ini NICI@GEMINI.ini NICS@TNG.ini NIRI@GEMINI.ini NOTcam_highres@NOT.ini NOTcam_lowres@NOT.ini Omega2000@CAHA.ini OSIRIS_F3@SOAR.ini OSIRIS_F7@SOAR.ini OSIRIS@GTC.ini PISCES@LBT.ini SOFI@NTT.ini SPARTAN@SOAR.ini VIRCAM@VISTA.ini WIRCam@CFHT.ini THELI-3.1.3/config/instruments/NIRC2@KECK.ini000066400000000000000000000013751417631501300203060ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NIRC2@KECK INSTSHORT=NIRC2 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.039686 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=NIRMIR THELI-3.1.3/config/instruments/NIRI@GEMINI.ini000066400000000000000000000013541417631501300204620ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NIRI@GEMINI INSTSHORT=NIRI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.1171 GAIN=12.3 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIRMIR THELI-3.1.3/config/instruments/NIRI@GEMINI_1.reg000066400000000000000000000013431417631501300206760ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(1015.75,1008.5,1025.75,1008.5,1025.75,998.5,1015.75,998.5) polygon(1018.1819,7.8181362,1027.8181,7.8181362,1027.8181,-1.8181362,1018.1819,-1.8181362) polygon(-1.4415602,22.44156,-1.5,1024,1025.5,1025,1025.5,996.5,996,1014.5,26,1010,9,983,9.5,15,19,-1,-0.5,-0.5) polygon(23,811.875,29.125,812.875,33.875,810.75,33.75,803.75,29.625,801.375,28.75,802.125,28.625,512.25,27.125,512.375,27.375,801.5,24,802.375,23,803.75) polygon(1025.5,368.5,1025,358,850,69.5,806,-3.5,801.60033,-0.39966829) polygon(750.99829,324.00171,761.00171,324.00171,761.00171,313.99829,750.99829,313.99829) polygon(428.5,534,437,534,437.5,526.5,434.5,526,433.5,512,432.5,512,432,526.5,429,526.5) THELI-3.1.3/config/instruments/NIRI@GEMINI_1.reg2000066400000000000000000000004001417631501300207510ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and physical polygon(21.587324,1006.4289,1014.0996,1006.7162,1024.737,997.14261,1024.2504,8,1018.5771,0.19929577,18.929225,0.57464789,10.419366,20.785563,7.7588028,965.65246,10.595423,987.99085) THELI-3.1.3/config/instruments/NOTcam_highres@NOT.ini000066400000000000000000000013661417631501300222460ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NOTcam_highres@NOT INSTSHORT=NOTcam # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.078 GAIN=2.5 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/NOTcam_lowres@NOT.ini000066400000000000000000000013641417631501300221260ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=NOTcam_lowres@NOT INSTSHORT=NOTcam # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.234 GAIN=2.5 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/OASIS4x4@WHT.ini000066400000000000000000000013611417631501300206270ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=OASIS4x4@WHT INSTSHORT=OASIS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.1 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=523) OVSCANX2=([1]=537) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=10) CUTY=([1]=1) SIZEX=([1]=507) SIZEY=([1]=1048) # Reference pixels for each chip. REFPIXX=([1]=250) REFPIXY=([1]=500) TYPE=OPT THELI-3.1.3/config/instruments/OASIS@WHT.ini000066400000000000000000000013641417631501300202720ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=OASIS@WHT INSTSHORT=OASIS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.02 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2070) OVSCANX2=([1]=2140) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=15) CUTY=([1]=1) SIZEX=([1]=2046) SIZEY=([1]=2106) # Reference pixels for each chip. REFPIXX=([1]=1000) REFPIXY=([1]=1000) TYPE=OPT THELI-3.1.3/config/instruments/OMEGACAM@VST.ahead000066400000000000000000000364401417631501300210650ustar00rootroot00000000000000CRPIX1 = 8.433258042E+03 / Reference pixel on this axis CRPIX2 = 8.551502518E+03 / Reference pixel on this axis CD1_1 = 5.929255407E-05 / Linear projection matrix CD1_2 = -2.703789321E-08 / Linear projection matrix CD2_1 = 1.854092768E-08 / Linear projection matrix CD2_2 = 5.928486259E-05 / Linear projection matrix END CRPIX1 = 6.289155894E+03 / Reference pixel on this axis CRPIX2 = 8.557027698E+03 / Reference pixel on this axis CD1_1 = 5.927508444E-05 / Linear projection matrix CD1_2 = 1.592897003E-08 / Linear projection matrix CD2_1 = -1.384615412E-08 / Linear projection matrix CD2_2 = 5.928307311E-05 / Linear projection matrix END CRPIX1 = 4.148060302E+03 / Reference pixel on this axis CRPIX2 = 8.552678732E+03 / Reference pixel on this axis CD1_1 = 5.929397932E-05 / Linear projection matrix CD1_2 = -1.000720789E-08 / Linear projection matrix CD2_1 = -1.432183920E-09 / Linear projection matrix CD2_2 = 5.927979163E-05 / Linear projection matrix END CRPIX1 = 2.011026485E+03 / Reference pixel on this axis CRPIX2 = 8.551343073E+03 / Reference pixel on this axis CD1_1 = 5.925776578E-05 / Linear projection matrix CD1_2 = -5.755348194E-08 / Linear projection matrix CD2_1 = 5.225314364E-08 / Linear projection matrix CD2_2 = 5.927961006E-05 / Linear projection matrix END CRPIX1 = 8.431539690E+03 / Reference pixel on this axis CRPIX2 = 4.095130427E+03 / Reference pixel on this axis CD1_1 = 5.928255035E-05 / Linear projection matrix CD1_2 = 9.968758032E-09 / Linear projection matrix CD2_1 = -2.113748237E-08 / Linear projection matrix CD2_2 = 5.927760376E-05 / Linear projection matrix END CRPIX1 = 6.291180087E+03 / Reference pixel on this axis CRPIX2 = 4.087758290E+03 / Reference pixel on this axis CD1_1 = 5.928577701E-05 / Linear projection matrix CD1_2 = -3.858688008E-08 / Linear projection matrix CD2_1 = 2.850022656E-08 / Linear projection matrix CD2_2 = 5.927364817E-05 / Linear projection matrix END CRPIX1 = 4.151397058E+03 / Reference pixel on this axis CRPIX2 = 4.085624837E+03 / Reference pixel on this axis CD1_1 = 5.927346720E-05 / Linear projection matrix CD1_2 = -1.030195979E-07 / Linear projection matrix CD2_1 = 1.063822560E-07 / Linear projection matrix CD2_2 = 5.927904867E-05 / Linear projection matrix END CRPIX1 = 2.011051446E+03 / Reference pixel on this axis CRPIX2 = 4.086860273E+03 / Reference pixel on this axis CD1_1 = 5.927605038E-05 / Linear projection matrix CD1_2 = -3.411733574E-08 / Linear projection matrix CD2_1 = 2.453405144E-08 / Linear projection matrix CD2_2 = 5.927513748E-05 / Linear projection matrix END CRPIX1 = 8.434305830E+03 / Reference pixel on this axis CRPIX2 = -5.689503409E+01 / Reference pixel on this axis CD1_1 = 5.928676130E-05 / Linear projection matrix CD1_2 = -2.781008079E-08 / Linear projection matrix CD2_1 = 2.116033855E-08 / Linear projection matrix CD2_2 = 5.929064643E-05 / Linear projection matrix END CRPIX1 = 6.292814225E+03 / Reference pixel on this axis CRPIX2 = -6.581774192E+01 / Reference pixel on this axis CD1_1 = 5.927282519E-05 / Linear projection matrix CD1_2 = -8.415578132E-08 / Linear projection matrix CD2_1 = 9.444857111E-08 / Linear projection matrix CD2_2 = 5.928622706E-05 / Linear projection matrix END CRPIX1 = 4.151216628E+03 / Reference pixel on this axis CRPIX2 = -5.697639372E+01 / Reference pixel on this axis CD1_1 = 5.927297053E-05 / Linear projection matrix CD1_2 = 6.865257388E-09 / Linear projection matrix CD2_1 = -9.668194666E-09 / Linear projection matrix CD2_2 = 5.929006455E-05 / Linear projection matrix END CRPIX1 = 2.009877948E+03 / Reference pixel on this axis CRPIX2 = -5.891686361E+01 / Reference pixel on this axis CD1_1 = 5.925142996E-05 / Linear projection matrix CD1_2 = -2.648194589E-08 / Linear projection matrix CD2_1 = 1.347578083E-08 / Linear projection matrix CD2_2 = 5.928707962E-05 / Linear projection matrix END CRPIX1 = 8.433887973E+03 / Reference pixel on this axis CRPIX2 = -4.518906877E+03 / Reference pixel on this axis CD1_1 = 5.929425124E-05 / Linear projection matrix CD1_2 = -3.242446508E-08 / Linear projection matrix CD2_1 = 1.605457833E-08 / Linear projection matrix CD2_2 = 5.929950816E-05 / Linear projection matrix END CRPIX1 = 6.291283208E+03 / Reference pixel on this axis CRPIX2 = -4.523955236E+03 / Reference pixel on this axis CD1_1 = 5.927957976E-05 / Linear projection matrix CD1_2 = -3.550011772E-08 / Linear projection matrix CD2_1 = 3.699091922E-08 / Linear projection matrix CD2_2 = 5.929287641E-05 / Linear projection matrix END CRPIX1 = 4.144681201E+03 / Reference pixel on this axis CRPIX2 = -4.524168485E+03 / Reference pixel on this axis CD1_1 = 5.927420581E-05 / Linear projection matrix CD1_2 = -7.462680215E-08 / Linear projection matrix CD2_1 = 6.501676326E-08 / Linear projection matrix CD2_2 = 5.929580751E-05 / Linear projection matrix END CRPIX1 = 2.002282825E+03 / Reference pixel on this axis CRPIX2 = -4.523334856E+03 / Reference pixel on this axis CD1_1 = 5.927366818E-05 / Linear projection matrix CD1_2 = -7.447803327E-08 / Linear projection matrix CD2_1 = 8.457089500E-08 / Linear projection matrix CD2_2 = 5.929439065E-05 / Linear projection matrix END CRPIX1 = -1.275975205E+02 / Reference pixel on this axis CRPIX2 = 8.548242987E+03 / Reference pixel on this axis CD1_1 = 5.928639743E-05 / Linear projection matrix CD1_2 = -6.975799765E-08 / Linear projection matrix CD2_1 = 6.687282318E-08 / Linear projection matrix CD2_2 = 5.928115683E-05 / Linear projection matrix END CRPIX1 = -2.277466343E+03 / Reference pixel on this axis CRPIX2 = 8.546967651E+03 / Reference pixel on this axis CD1_1 = 5.929117755E-05 / Linear projection matrix CD1_2 = 2.897963876E-08 / Linear projection matrix CD2_1 = -3.041267100E-08 / Linear projection matrix CD2_2 = 5.929020920E-05 / Linear projection matrix END CRPIX1 = -4.407471982E+03 / Reference pixel on this axis CRPIX2 = 8.556542658E+03 / Reference pixel on this axis CD1_1 = 5.930273672E-05 / Linear projection matrix CD1_2 = -9.304644796E-08 / Linear projection matrix CD2_1 = 9.329111582E-08 / Linear projection matrix CD2_2 = 5.928707530E-05 / Linear projection matrix END CRPIX1 = -6.546562341E+03 / Reference pixel on this axis CRPIX2 = 8.560070385E+03 / Reference pixel on this axis CD1_1 = 5.930270304E-05 / Linear projection matrix CD1_2 = -1.105519045E-07 / Linear projection matrix CD2_1 = 1.081304355E-07 / Linear projection matrix CD2_2 = 5.929164876E-05 / Linear projection matrix END CRPIX1 = -1.280153158E+02 / Reference pixel on this axis CRPIX2 = 4.089935470E+03 / Reference pixel on this axis CD1_1 = 5.929101928E-05 / Linear projection matrix CD1_2 = -9.618228010E-08 / Linear projection matrix CD2_1 = 8.775847567E-08 / Linear projection matrix CD2_2 = 5.927509838E-05 / Linear projection matrix END CRPIX1 = -2.272274093E+03 / Reference pixel on this axis CRPIX2 = 4.087680317E+03 / Reference pixel on this axis CD1_1 = 5.928714331E-05 / Linear projection matrix CD1_2 = -1.610681097E-09 / Linear projection matrix CD2_1 = 1.128615846E-08 / Linear projection matrix CD2_2 = 5.927595814E-05 / Linear projection matrix END CRPIX1 = -4.413832562E+03 / Reference pixel on this axis CRPIX2 = 4.096679775E+03 / Reference pixel on this axis CD1_1 = 5.927982997E-05 / Linear projection matrix CD1_2 = -1.129891239E-07 / Linear projection matrix CD2_1 = 1.115670400E-07 / Linear projection matrix CD2_2 = 5.927467010E-05 / Linear projection matrix END CRPIX1 = -6.551736017E+03 / Reference pixel on this axis CRPIX2 = 4.102546536E+03 / Reference pixel on this axis CD1_1 = 5.929858222E-05 / Linear projection matrix CD1_2 = -1.462282113E-07 / Linear projection matrix CD2_1 = 1.502224267E-07 / Linear projection matrix CD2_2 = 5.928326298E-05 / Linear projection matrix END CRPIX1 = -1.262308152E+02 / Reference pixel on this axis CRPIX2 = -5.819406341E+01 / Reference pixel on this axis CD1_1 = 5.928196147E-05 / Linear projection matrix CD1_2 = 1.147944315E-08 / Linear projection matrix CD2_1 = -5.314686491E-09 / Linear projection matrix CD2_2 = 5.929068024E-05 / Linear projection matrix END CRPIX1 = -2.271219232E+03 / Reference pixel on this axis CRPIX2 = -5.344238120E+01 / Reference pixel on this axis CD1_1 = 5.930148093E-05 / Linear projection matrix CD1_2 = -9.261298375E-08 / Linear projection matrix CD2_1 = 9.828044999E-08 / Linear projection matrix CD2_2 = 5.928799478E-05 / Linear projection matrix END CRPIX1 = -4.416391049E+03 / Reference pixel on this axis CRPIX2 = -5.282039430E+01 / Reference pixel on this axis CD1_1 = 5.928930905E-05 / Linear projection matrix CD1_2 = -9.242071448E-08 / Linear projection matrix CD2_1 = 9.795046620E-08 / Linear projection matrix CD2_2 = 5.928880555E-05 / Linear projection matrix END CRPIX1 = -6.553640006E+03 / Reference pixel on this axis CRPIX2 = -6.728350884E+01 / Reference pixel on this axis CD1_1 = 5.929404364E-05 / Linear projection matrix CD1_2 = 5.483739486E-08 / Linear projection matrix CD2_1 = -3.969755188E-08 / Linear projection matrix CD2_2 = 5.928829256E-05 / Linear projection matrix END CRPIX1 = -1.350005647E+02 / Reference pixel on this axis CRPIX2 = -4.521597524E+03 / Reference pixel on this axis CD1_1 = 5.926390087E-05 / Linear projection matrix CD1_2 = -5.144079640E-08 / Linear projection matrix CD2_1 = 5.739656113E-08 / Linear projection matrix CD2_2 = 5.929727719E-05 / Linear projection matrix END CRPIX1 = -2.281688626E+03 / Reference pixel on this axis CRPIX2 = -4.513663618E+03 / Reference pixel on this axis CD1_1 = 5.929784454E-05 / Linear projection matrix CD1_2 = -1.230319210E-07 / Linear projection matrix CD2_1 = 1.286261529E-07 / Linear projection matrix CD2_2 = 5.930025335E-05 / Linear projection matrix END CRPIX1 = -4.417747327E+03 / Reference pixel on this axis CRPIX2 = -4.516586196E+03 / Reference pixel on this axis CD1_1 = 5.929395364E-05 / Linear projection matrix CD1_2 = -8.190214244E-08 / Linear projection matrix CD2_1 = 9.306297092E-08 / Linear projection matrix CD2_2 = 5.930131545E-05 / Linear projection matrix END CRPIX1 = -6.556730974E+03 / Reference pixel on this axis CRPIX2 = -4.514967067E+03 / Reference pixel on this axis CD1_1 = 5.931081093E-05 / Linear projection matrix CD1_2 = -4.346604193E-08 / Linear projection matrix CD2_1 = 7.160235752E-08 / Linear projection matrix CD2_2 = 5.930570412E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/OMEGACAM@VST.ini000066400000000000000000000055121417631501300205760ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=OMEGACAM@VST INSTSHORT=OMEGACAM # Number of chips NCHIPS=32 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.214 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2 [2]=2 [3]=2 [4]=2 [5]=2 [6]=2 [7]=2 [8]=2 [9]=2 [10]=2 [11]=2 [12]=2 [13]=2 [14]=2 [15]=2 [16]=2 [17]=2 [18]=2 [19]=2 [20]=2 [21]=2 [22]=2 [23]=2 [24]=2 [25]=2 [26]=2 [27]=2 [28]=2 [29]=2 [30]=2 [31]=2 [32]=2) OVSCANX2=([1]=45 [2]=45 [3]=45 [4]=45 [5]=45 [6]=45 [7]=45 [8]=45 [9]=45 [10]=45 [11]=45 [12]=45 [13]=45 [14]=45 [15]=45 [16]=45 [17]=45 [18]=45 [19]=45 [20]=45 [21]=45 [22]=45 [23]=45 [24]=45 [25]=45 [26]=45 [27]=45 [28]=45 [29]=45 [30]=45 [31]=45 [32]=45) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=51 [2]=51 [3]=51 [4]=51 [5]=51 [6]=51 [7]=51 [8]=51 [9]=51 [10]=51 [11]=51 [12]=51 [13]=51 [14]=51 [15]=51 [16]=51 [17]=51 [18]=51 [19]=51 [20]=51 [21]=51 [22]=51 [23]=51 [24]=51 [25]=51 [26]=51 [27]=51 [28]=51 [29]=51 [30]=51 [31]=51 [32]=51) CUTY=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=3 [7]=3 [8]=3 [9]=102 [10]=102 [11]=102 [12]=102 [13]=102 [14]=102 [15]=102 [16]=102 [17]=3 [18]=3 [19]=3 [20]=3 [21]=3 [22]=3 [23]=3 [24]=3 [25]=102 [26]=102 [27]=102 [28]=102 [29]=102 [30]=102 [31]=102 [32]=102) SIZEX=([1]=2044 [2]=2044 [3]=2044 [4]=2044 [5]=2044 [6]=2044 [7]=2044 [8]=2044 [9]=2044 [10]=2044 [11]=2044 [12]=2044 [13]=2044 [14]=2044 [15]=2044 [16]=2044 [17]=2044 [18]=2044 [19]=2044 [20]=2044 [21]=2044 [22]=2044 [23]=2044 [24]=2044 [25]=2044 [26]=2044 [27]=2044 [28]=2044 [29]=2044 [30]=2044 [31]=2044 [32]=2044) SIZEY=([1]=4096 [2]=4096 [3]=4096 [4]=4096 [5]=4096 [6]=4096 [7]=4096 [8]=4096 [9]=4096 [10]=4096 [11]=4096 [12]=4096 [13]=4096 [14]=4096 [15]=4096 [16]=4096 [17]=4096 [18]=4096 [19]=4096 [20]=4096 [21]=4096 [22]=4096 [23]=4096 [24]=4096 [25]=4096 [26]=4096 [27]=4096 [28]=4096 [29]=4096 [30]=4096 [31]=4096 [32]=4096) # Reference pixels for each chip. REFPIXX=([1]=8576 [2]=6438 [3]=4296 [4]=2154 [5]=8576 [6]=6438 [7]=4296 [8]=2154 [9]=8576 [10]=6438 [11]=4296 [12]=2154 [13]=8576 [14]=6438 [15]=4296 [16]=2154 [17]=14 [18]=-2125 [19]=-4268 [20]=-6408 [21]=14 [22]=-2125 [23]=-4268 [24]=-6408 [25]=14 [26]=-2125 [27]=-4268 [28]=-6408 [29]=14 [30]=-2125 [31]=-4268 [32]=-6408) REFPIXY=([1]=8563 [2]=8563 [3]=8563 [4]=8563 [5]=4104 [6]=4104 [7]=4104 [8]=4104 [9]=61 [10]=61 [11]=61 [12]=61 [13]=-4400 [14]=-4400 [15]=-4400 [16]=-4400 [17]=8563 [18]=8563 [19]=8563 [20]=8563 [21]=4104 [22]=4104 [23]=4104 [24]=4104 [25]=61 [26]=61 [27]=61 [28]=61 [29]=-4400 [30]=-4400 [31]=-4400 [32]=-4400) TYPE=OPT THELI-3.1.3/config/instruments/OSIRIS@GTC.ini000066400000000000000000000014531417631501300203760ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=OSIRIS@GTC INSTSHORT=OSIRIS # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.125 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2 [2]=2) OVSCANX2=([1]=23 [2]=23) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=27 [2]=27) CUTY=([1]=3 [2]=3) SIZEX=([1]=985 [2]=1019) SIZEY=([1]=2045 [2]=2045) # Reference pixels for each chip. REFPIXX=([1]=1000 [2]=1) REFPIXY=([1]=1000 [2]=1000) TYPE=NIR THELI-3.1.3/config/instruments/OSIRIS_F3@SOAR.ini000066400000000000000000000013601417631501300210520ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=OSIRIS_F3@SOAR INSTSHORT=OSIRIS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.331 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=235) CUTY=([1]=307) SIZEX=([1]=562) SIZEY=([1]=561) # Reference pixels for each chip. REFPIXX=([1]=280) REFPIXY=([1]=280) TYPE=NIR THELI-3.1.3/config/instruments/OSIRIS_F7@SOAR.ini000066400000000000000000000013571417631501300210640ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=OSIRIS_F7@SOAR INSTSHORT=OSIRIS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.139 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/Omega2000@CAHA.ini000066400000000000000000000013651417631501300210010ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=Omega2000@CAHA INSTSHORT=Omega2000 # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=37.22 OBSLONG=-2.55 # Pixel scale in arcsec PIXSCALE=0.449 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) TYPE=NIR THELI-3.1.3/config/instruments/PANIC@LCO.ini000066400000000000000000000013731417631501300202210ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=PANIC@LCO INSTSHORT=PANIC # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.01423 OBSLONG=-70.33 # Pixel scale in arcsec PIXSCALE=0.125 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=NIR THELI-3.1.3/config/instruments/PANIC_OLD_4det@CAHA2.2.ahead000066400000000000000000000036441417631501300224260ustar00rootroot00000000000000CRPIX1 = -8.844114104646E+01 / Reference pixel on this axis CRPIX2 = 2.127436214300E+03 / Reference pixel on this axis CD1_1 = -1.244708446515E-04 / Linear projection matrix CD1_2 = -4.523402691823E-08 / Linear projection matrix CD2_1 = 7.548460352066E-07 / Linear projection matrix CD2_2 = 1.244464901206E-04 / Linear projection matrix END CRPIX1 = -6.872712376614E+01 / Reference pixel on this axis CRPIX2 = -9.111089185834E+01 / Reference pixel on this axis CD1_1 = -1.245510871257E-04 / Linear projection matrix CD1_2 = -2.657009734177E-07 / Linear projection matrix CD2_1 = -1.096813153130E-06 / Linear projection matrix CD2_2 = 1.244703807651E-04 / Linear projection matrix END CRPIX1 = 2.128572894979E+03 / Reference pixel on this axis CRPIX2 = -6.897720967820E+01 / Reference pixel on this axis CD1_1 = -1.242466245492E-04 / Linear projection matrix CD1_2 = -6.602713252379E-08 / Linear projection matrix CD2_1 = 8.342548560519E-07 / Linear projection matrix CD2_2 = 1.243936990531E-04 / Linear projection matrix END CRPIX1 = 2.122921924663E+03 / Reference pixel on this axis CRPIX2 = 2.132318431969E+03 / Reference pixel on this axis CD1_1 = -1.242985009360E-04 / Linear projection matrix CD1_2 = 7.527865515692E-07 / Linear projection matrix CD2_1 = -1.896518898634E-09 / Linear projection matrix CD2_2 = 1.243957116432E-04 / Linear projection matrix END THELI-3.1.3/config/instruments/PANIC_OLD_4det@CAHA2.2.ini000066400000000000000000000007731417631501300221430ustar00rootroot00000000000000INSTRUMENT=PANIC_OLD_4det@CAHA2.2 INSTSHORT=PANIC_OLD NCHIPS=4 # Geographic location OBSLAT=37.22 OBSLONG=-2.55 # Plate scale PIXSCALE=0.45 GAIN=1.0 # Detector geometries OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048) REFPIXX=([1]=-80 [2]=-80 [3]=2132 [4]=2132) REFPIXY=([1]=2132 [2]=-80 [3]=-80 [4]=2132) # Camera type TYPE=NIR THELI-3.1.3/config/instruments/PAUCam@WHT.ahead000066400000000000000000000075101417631501300207440ustar00rootroot00000000000000CRPIX1 = 4.597519642283E+03 / Reference pixel on this axis CRPIX2 = 4.402168664649E+03 / Reference pixel on this axis CD1_1 = -1.952150544654E-05 / Linear projection matrix CD1_2 = 7.036185872952E-05 / Linear projection matrix CD2_1 = -6.936582026339E-05 / Linear projection matrix CD2_2 = -1.856345871678E-05 / Linear projection matrix END CRPIX1 = -2.534732539751E+03 / Reference pixel on this axis CRPIX2 = 4.405872386958E+03 / Reference pixel on this axis CD1_1 = 1.840107954568E-05 / Linear projection matrix CD1_2 = -6.996848836837E-05 / Linear projection matrix CD2_1 = 6.981954410917E-05 / Linear projection matrix CD2_2 = 1.955567796371E-05 / Linear projection matrix END CRPIX1 = 2.197184819958E+03 / Reference pixel on this axis CRPIX2 = 4.373822656213E+03 / Reference pixel on this axis CD1_1 = -1.927770012864E-05 / Linear projection matrix CD1_2 = 7.068526113884E-05 / Linear projection matrix CD2_1 = -7.089819673253E-05 / Linear projection matrix CD2_2 = -1.912478909686E-05 / Linear projection matrix END CRPIX1 = -1.544407540824E+02 / Reference pixel on this axis CRPIX2 = 4.375575760940E+03 / Reference pixel on this axis CD1_1 = 1.919803000784E-05 / Linear projection matrix CD1_2 = -7.041887335881E-05 / Linear projection matrix CD2_1 = 7.080842921676E-05 / Linear projection matrix CD2_2 = 1.943124681991E-05 / Linear projection matrix END CRPIX1 = -1.492130332551E+02 / Reference pixel on this axis CRPIX2 = 4.380774373995E+03 / Reference pixel on this axis CD1_1 = -1.915716695370E-05 / Linear projection matrix CD1_2 = 7.043881391740E-05 / Linear projection matrix CD2_1 = -7.084663316203E-05 / Linear projection matrix CD2_2 = -1.939882873464E-05 / Linear projection matrix END CRPIX1 = 2.195131140060E+03 / Reference pixel on this axis CRPIX2 = 4.378241010424E+03 / Reference pixel on this axis CD1_1 = 1.942509471795E-05 / Linear projection matrix CD1_2 = -7.050829340166E-05 / Linear projection matrix CD2_1 = 7.069779273496E-05 / Linear projection matrix CD2_2 = 1.898389273971E-05 / Linear projection matrix END CRPIX1 = -2.531537632174E+03 / Reference pixel on this axis CRPIX2 = 4.392125603020E+03 / Reference pixel on this axis CD1_1 = -1.865564367634E-05 / Linear projection matrix CD1_2 = 6.998925141341E-05 / Linear projection matrix CD2_1 = -6.978966213023E-05 / Linear projection matrix CD2_2 = -1.964824415240E-05 / Linear projection matrix END CRPIX1 = 4.593046292423E+03 / Reference pixel on this axis CRPIX2 = 4.412744434936E+03 / Reference pixel on this axis CD1_1 = 1.965265240183E-05 / Linear projection matrix CD1_2 = -7.017425841004E-05 / Linear projection matrix CD2_1 = 6.931453972198E-05 / Linear projection matrix CD2_2 = 1.833689751925E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/PAUCam@WHT.ini000066400000000000000000000022371417631501300204620ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=PAUCam@WHT INSTSHORT=PAUCam # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.27 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048) SIZEY=([1]=4224 [2]=4224 [3]=4224 [4]=4224 [5]=4224 [6]=4224 [7]=4224 [8]=4224) # Reference pixels for each chip. REFPIXX=([1]=4597 [2]=-2534 [3]=2197 [4]=-154 [5]=-149 [6]=2194 [7]=-2531 [8]=4592) REFPIXY=([1]=4401 [2]=4406 [3]=4373 [4]=4376 [5]=4380 [6]=4378 [7]=4391 [8]=4413) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/PFC_new@WHT.ini000066400000000000000000000013741417631501300206760ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=PFC_new@WHT INSTSHORT=PFC # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.262 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=10) OVSCANX2=([1]=40) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=52) CUTY=([1]=5) SIZEX=([1]=4092) SIZEY=([1]=4100) # Reference pixels for each chip. REFPIXX=([1]=2040) REFPIXY=([1]=2050) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/PFC_old@WHT.ahead000066400000000000000000000017221417631501300211430ustar00rootroot00000000000000CRPIX1 = -2.015603476E+02 / Reference pixel on this axis CRPIX2 = 1.926814299E+03 / Reference pixel on this axis CD1_1 = 6.564676913E-05 / Linear projection matrix CD1_2 = 4.559313681E-07 / Linear projection matrix CD2_1 = 6.443351978E-07 / Linear projection matrix CD2_2 = -6.538287638E-05 / Linear projection matrix END CRPIX1 = 2.155380801E+03 / Reference pixel on this axis CRPIX2 = 2.122582540E+03 / Reference pixel on this axis CD1_1 = 6.475556646E-05 / Linear projection matrix CD1_2 = 7.171631240E-07 / Linear projection matrix CD2_1 = 3.903906071E-07 / Linear projection matrix CD2_2 = -6.578825128E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/PFC_old@WHT.ini000066400000000000000000000014611417631501300206600ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=PFC_old@WHT INSTSHORT=PFC # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.237 GAIN=1.3 # Overscan regions. OVSCANX1=([1]=10 [2]=10) OVSCANX2=([1]=50 [2]=50) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=60 [2]=60) CUTY=([1]=10 [2]=10) SIZEX=([1]=2040 [2]=2040) SIZEY=([1]=4080 [2]=4080) # Reference pixels for each chip. REFPIXX=([1]=2000 [2]=30) REFPIXY=([1]=2105 [2]=2100) TYPE=OPT THELI-3.1.3/config/instruments/PF_QHY2x2@WHT.ini000066400000000000000000000006501417631501300207730ustar00rootroot00000000000000INSTRUMENT=PF_QHY2x2@WHT NCHIPS=1 # Geographic location OBSLAT=28.76 OBSLONG=-17.89 # Plate scale PIXSCALE=0.1333 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0) OVSCANX2=([1]=0) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=4788) SIZEY=([1]=3194) REFPIXX=([1]=2255) REFPIXY=([1]=1690) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/PF_QHY4x4@WHT.ini000066400000000000000000000006471417631501300210050ustar00rootroot00000000000000INSTRUMENT=PF_QHY4x4@WHT NCHIPS=1 # Geographic location OBSLAT=28.76 OBSLONG=-17.89 # Plate scale PIXSCALE=0.2666 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0) OVSCANX2=([1]=0) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2394) SIZEY=([1]=1597) REFPIXX=([1]=1130) REFPIXY=([1]=850) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/PICCD@WISE.ini000066400000000000000000000013421417631501300203370ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=PICCD@WISE INSTSHORT=PICCD # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=30.60 OBSLONG=034.76 # Pixel scale in arcsec PIXSCALE=0.58164 GAIN=2.1 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=2) SIZEX=([1]=1338) SIZEY=([1]=1299) # Reference pixels for each chip. REFPIXX=([1]=1670) REFPIXY=([1]=1650) TYPE=OPT THELI-3.1.3/config/instruments/PISCES@LBT.ini000066400000000000000000000013551417631501300203610ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=PISCES@LBT INSTSHORT=PISCES # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=32.70 OBSLONG=-109.89 # Pixel scale in arcsec PIXSCALE=0.0179 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/PISCO@LCO.ini000066400000000000000000000006511417631501300202420ustar00rootroot00000000000000INSTRUMENT=PISCO@LCO NCHIPS=1 # Geographic location OBSLAT=-29.01423 OBSLONG=-70.33 # Plate scale PIXSCALE=0.1103 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=0) OVSCANX2=([1]=0) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=3092) SIZEY=([1]=6147) REFPIXX=([1]=1500) REFPIXY=([1]=3000) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/PISCO@LCO_1.reg000066400000000000000000000003331417631501300204550ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(47.908672,5120.9585,410.83118,5330.7731,2585.5309,5330.7731,3033.5134,5092.6052,3029.6453,704.61624,2709.2528,571.35563,440.98708,574.19096,31.261993,723.05904) THELI-3.1.3/config/instruments/RetroCam_DUPONT@LCO.ini000066400000000000000000000007031417631501300221700ustar00rootroot00000000000000INSTRUMENT=RetroCam_DUPONT@LCO INSTSHORT=RetroCam NCHIPS=1 # Geographic location OBSLAT=-29.00730 OBSLONG=-70.70384 # Plate scale PIXSCALE=0.201 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=) OVSCANX2=([1]=) OVSCANY1=([1]=) OVSCANY2=([1]=) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=NIR FLIP=NOFLIP THELI-3.1.3/config/instruments/RetroCam_DUPONT@LCO_1.reg000066400000000000000000000002031417631501300224010ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(4,970,54,1020,994,1021,1022,992,1021,67,998,26,975,8,3,8) THELI-3.1.3/config/instruments/RetroCam_SWOPE@LCO.ini000066400000000000000000000007021417631501300220530ustar00rootroot00000000000000INSTRUMENT=RetroCam_SWOPE@LCO INSTSHORT=RetroCam NCHIPS=1 # Geographic location OBSLAT=-29.00730 OBSLONG=-70.70384 # Plate scale PIXSCALE=0.537 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=) OVSCANX2=([1]=) OVSCANY1=([1]=) OVSCANY2=([1]=) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1024) SIZEY=([1]=1024) REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=NIR FLIP=NOFLIP THELI-3.1.3/config/instruments/RetroCam_SWOPE@LCO_1.reg000066400000000000000000000002031417631501300222650ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(4,970,54,1020,994,1021,1022,992,1021,67,998,26,975,8,3,8) THELI-3.1.3/config/instruments/SAMI_2x2@SOAR.ini000066400000000000000000000013751417631501300207440ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SAMI_2x2@SOAR INSTSHORT=SAMI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.091 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2056) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1028) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/SDSS.ini000066400000000000000000000013341417631501300175020ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SDSS INSTSHORT=SDSS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=0 OBSLONG=0.0 # Pixel scale in arcsec PIXSCALE=0.396 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=1489) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=745) TYPE=OPT THELI-3.1.3/config/instruments/SITe3_SWOPE@LCO.ini000066400000000000000000000006761417631501300212400ustar00rootroot00000000000000INSTRUMENT=SITe3_SWOPE@LCO INSTSHORT=SITe3 NCHIPS=1 # Geographic location OBSLAT=-29.0 OBSLONG=-70.33 # Plate scale PIXSCALE=0.435 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=1205) OVSCANX2=([1]=1232) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=1201) SIZEY=([1]=1201) REFPIXX=([1]=600) REFPIXY=([1]=600) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/SITe@TLS.ini000066400000000000000000000013561417631501300202210ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SITe@TLS INSTSHORT=SITe # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=51.0 OBSLONG=0.0 # Pixel scale in arcsec PIXSCALE=1.233 GAIN=20.0 # Overscan regions. OVSCANX1=([1]=2050) OVSCANX2=([1]=2160) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=3) CUTY=([1]=2) SIZEX=([1]=2044) SIZEY=([1]=2047) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) # Camera type TYPE=OPT THELI-3.1.3/config/instruments/SOFI@NTT.ini000066400000000000000000000013551417631501300201570ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SOFI@NTT INSTSHORT=SOFI # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.290 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=10) CUTY=([1]=2) SIZEX=([1]=1010) SIZEY=([1]=1010) # Reference pixels for each chip. REFPIXX=([1]=512) REFPIXY=([1]=512) TYPE=NIR THELI-3.1.3/config/instruments/SOI@SOAR.ahead000066400000000000000000000017101417631501300204260ustar00rootroot00000000000000CRPIX1 = 1.050911616312E+03 / Reference pixel on this axis CRPIX2 = 1.024989033611E+03 / Reference pixel on this axis CD1_1 = -4.260472451758E-05 / Linear projection matrix CD1_2 = 2.400869423855E-07 / Linear projection matrix CD2_1 = 2.445292572607E-07 / Linear projection matrix CD2_2 = 4.261550710726E-05 / Linear projection matrix END CRPIX1 = -2.601837775412E+01 / Reference pixel on this axis CRPIX2 = 1.022988826770E+03 / Reference pixel on this axis CD1_1 = -4.259671941042E-05 / Linear projection matrix CD1_2 = 1.496986834908E-07 / Linear projection matrix CD2_1 = 1.449929713362E-07 / Linear projection matrix CD2_2 = 4.261404170076E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/SOI@SOAR.ini000066400000000000000000000014411417631501300201440ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SOI@SOAR INSTSHORT=SOI # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.1534 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0) OVSCANX2=([1]=0 [2]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1) CUTY=([1]=20 [2]=20) SIZEX=([1]=1024 [2]=1024) SIZEY=([1]=2048 [2]=2048) # Reference pixels for each chip. REFPIXX=([1]=1000 [2]=0) REFPIXY=([1]=940 [2]=940) TYPE=OPT THELI-3.1.3/config/instruments/SOI@SOAR_1.reg000066400000000000000000000001701417631501300203600ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(-1,2049,1025,2049,1025,11,1.0710678,10.071068) THELI-3.1.3/config/instruments/SOI@SOAR_2.reg000066400000000000000000000001701417631501300203610ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(-1,2049,1025,2049,1025,11,1.0710678,10.071068) THELI-3.1.3/config/instruments/SPARTAN@SOAR.ahead000066400000000000000000000036441417631501300211140ustar00rootroot00000000000000CRPIX1 = 2.331742537E+03 / Reference pixel on this axis CRPIX2 = 2.311651873E+03 / Reference pixel on this axis CD1_1 = 1.813520732E-05 / Linear projection matrix CD1_2 = -5.389241348E-07 / Linear projection matrix CD2_1 = -2.302745826E-07 / Linear projection matrix CD2_2 = -1.821445216E-05 / Linear projection matrix END CRPIX1 = -2.085966051E+02 / Reference pixel on this axis CRPIX2 = 2.302052113E+03 / Reference pixel on this axis CD1_1 = 1.867483419E-05 / Linear projection matrix CD1_2 = -4.816164760E-07 / Linear projection matrix CD2_1 = -3.093933812E-07 / Linear projection matrix CD2_2 = -1.824714449E-05 / Linear projection matrix END CRPIX1 = -2.179730384E+02 / Reference pixel on this axis CRPIX2 = -2.580846203E+02 / Reference pixel on this axis CD1_1 = 1.865922836E-05 / Linear projection matrix CD1_2 = -1.287822743E-07 / Linear projection matrix CD2_1 = -3.430719440E-07 / Linear projection matrix CD2_2 = -1.828594111E-05 / Linear projection matrix END CRPIX1 = 2.317733827E+03 / Reference pixel on this axis CRPIX2 = -2.666756097E+02 / Reference pixel on this axis CD1_1 = 1.813667561E-05 / Linear projection matrix CD1_2 = -1.339064892E-07 / Linear projection matrix CD2_1 = -4.477749171E-07 / Linear projection matrix CD2_2 = -1.822369705E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/SPARTAN@SOAR.ini000066400000000000000000000016431417631501300206260ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SPARTAN@SOAR INSTSHORT=SPARTAN # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.0659 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048) # Reference pixels for each chip. REFPIXX=([1]=2306 [2]=-247 [3]=-252 [4]=2299) REFPIXY=([1]=2511 [2]=2509 [3]=-65 [4]=-68) TYPE=NIR THELI-3.1.3/config/instruments/SPARTAN@SOAR.nldat000066400000000000000000000001241417631501300211420ustar00rootroot000000000000000.0 1.0 -2.0E-06 0.0 0.0 1.0 -0.4E-06 0.0 0.0 1.0 -0.3E-06 0.0 0.0 1.0 -2.4E-06 0.0 THELI-3.1.3/config/instruments/SPARTAN@SOAR_1.reg000066400000000000000000000002671417631501300210450ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(0,1967,83,1972,86,2047,1023.3887,2047.2579,1023.466,1.7550578,37.316474,1.6242775,37.316474,32.221098,-0.18930636,70.713873) THELI-3.1.3/config/instruments/SPARTAN@SOAR_2.reg000066400000000000000000000005461417631501300210460ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(4.2066474,1902.2413,66.018786,1924.2168,95.628613,1979.4884,95.628613,2044.6301,1881.0173,2046.0332,1886.9393,1979.9046,1956.0289,1933.5159,2045.8454,1957.2038,2047.1951,134.82081,1978.1055,79.549133,1949.4827,2.5635838,94.023121,1.7846821,91.062139,55.08237,58.491329,125.15896,4.2066474,142.92486) THELI-3.1.3/config/instruments/SPARTAN@SOAR_3.reg000066400000000000000000000015221417631501300210420ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(201.65101,2041.776,1996.9451,2044.6062,2042.3468,2006.1134,2046.1105,105.59754,1968.138,8.3786127,1765.8042,11.339595,1763.3367,29.105491,1727.3114,28.118497,1723.8569,8.3786127,96.066474,3.7290462,12.041185,64.637283,10.275289,909.46821,28.171965,1057.8085,157.46821,1199.9357,160.42919,1237.935,110.09249,1337.1279,81.96315,1426.4509,75.547688,1470.3721,87.730491,1600.4292,314.73916,1604.3772,276.24639,1599.9357,242.19509,1576.7413,223.4422,1543.677,219.98772,1488.4053,245.64957,1440.5361,284.63584,1412.9003,351.75145,1407.4718,392.71171,1425.2377,409.9841,1457.8085,415.90607,1510.1192,394.68569,1577.7283,353.72543,1602.4032,314.73916,1604.3772,87.730491,1600.4292,120.7948,1699.1286,193.75506,1832.5332,197.20954,1880.896,125.65246,1942.0896,126.63945,1980.5824,150.82081,2026.4776) THELI-3.1.3/config/instruments/SPARTAN@SOAR_4.reg000066400000000000000000000014631417631501300210470ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(42.251445,1976.3858,53.887283,2046.1532,754.19509,2044.6488,872.1409,2045.1423,951.10043,1971.1178,963.93136,1971.6113,965.90535,1939.534,958.50289,1928.677,959.98338,1917.3266,972.32081,1910.9111,983.67124,1920.2876,986.63223,1933.612,976.26879,1939.534,965.90535,1939.534,963.93136,1971.6113,1032.5275,1970.6243,1086.4075,1980.2861,1113.0564,1981.7666,1149.0816,2002.987,1959.5939,1998.6228,1985.2558,1954.7016,1985.7493,1896.9624,1984.7623,1811.0939,1988.7103,1776.0556,2008.9971,1753.9436,2021.6973,646.38801,2043.5419,81.351879,2025.2825,42.859104,1951.7514,12.262283,1316,9,1140,47,755,44,699,8,45.551301,3.5874277,23.343931,61.820087,25.317919,196.5448,5.0845376,200.49277,10.590318,545.66691,43.161127,586.13367,44.225434,1350.6315,43.238439,1569.7442) THELI-3.1.3/config/instruments/SUSI1@NTT.ini000066400000000000000000000006711417631501300202630ustar00rootroot00000000000000INSTRUMENT=SUSI1@NTT INSTSHORT=SUSI1 NCHIPS=1 # Geographic location OBSLAT=-29.257 OBSLONG=-70.73 # Plate scale PIXSCALE=0.13 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=1080) OVSCANX2=([1]=1116) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=50) CUTY=([1]=2) SIZEX=([1]=1024) SIZEY=([1]=1023) REFPIXX=([1]=512) REFPIXY=([1]=512) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/SUSI2_2x2@NTT.ini000066400000000000000000000014541417631501300207570ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SUSI2_2x2@NTT INSTSHORT=SUSI2 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.161 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2 [2]=2) OVSCANX2=([1]=20 [2]=20) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=27 [2]=27) CUTY=([1]=2 [2]=2) SIZEX=([1]=1020 [2]=1020) SIZEY=([1]=2044 [2]=2044) # Reference pixels for each chip. REFPIXX=([1]=938 [2]=-145) REFPIXY=([1]=1145 [2]=1145) TYPE=OPT THELI-3.1.3/config/instruments/SUSI2old_2x2@NTT.ini000066400000000000000000000014601417631501300214530ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SUSI2old_2x2@NTT INSTSHORT=SUSI2 # Number of chips NCHIPS=2 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.161 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2 [2]=2) OVSCANX2=([1]=20 [2]=20) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=27 [2]=27) CUTY=([1]=2 [2]=2) SIZEX=([1]=1020 [2]=1020) SIZEY=([1]=2044 [2]=2044) # Reference pixels for each chip. REFPIXX=([1]=938 [2]=-145) REFPIXY=([1]=1145 [2]=1145) TYPE=OPT THELI-3.1.3/config/instruments/SuprimeCam_200101-200104@SUBARU.ahead000066400000000000000000000104611417631501300236300ustar00rootroot00000000000000CRPIX1 = 5.753044044E+03 / Reference pixel on this axis CRPIX2 = 1.527714596E+02 / Reference pixel on this axis CD1_1 = -5.480743204E-05 / Linear projection matrix CD1_2 = -4.739649334E-07 / Linear projection matrix CD2_1 = 1.194510126E-07 / Linear projection matrix CD2_2 = 5.529965774E-05 / Linear projection matrix END CRPIX1 = 3.563589260E+03 / Reference pixel on this axis CRPIX2 = 1.695507069E+02 / Reference pixel on this axis CD1_1 = -5.564561938E-05 / Linear projection matrix CD1_2 = -2.558407020E-07 / Linear projection matrix CD2_1 = 9.999283071E-08 / Linear projection matrix CD2_2 = 5.564009339E-05 / Linear projection matrix END CRPIX1 = 1.408200871E+03 / Reference pixel on this axis CRPIX2 = 4.275411591E+03 / Reference pixel on this axis CD1_1 = -5.598530398E-05 / Linear projection matrix CD1_2 = -2.674022813E-08 / Linear projection matrix CD2_1 = -1.784328117E-08 / Linear projection matrix CD2_2 = 5.581797236E-05 / Linear projection matrix END CRPIX1 = -7.358116797E+02 / Reference pixel on this axis CRPIX2 = 4.274883745E+03 / Reference pixel on this axis CD1_1 = -5.566583296E-05 / Linear projection matrix CD1_2 = -4.124865238E-07 / Linear projection matrix CD2_1 = -1.284784953E-07 / Linear projection matrix CD2_2 = 5.566496662E-05 / Linear projection matrix END CRPIX1 = -7.299698409E+02 / Reference pixel on this axis CRPIX2 = 1.577171140E+02 / Reference pixel on this axis CD1_1 = -5.566449471E-05 / Linear projection matrix CD1_2 = 1.277756681E-07 / Linear projection matrix CD2_1 = -2.102184753E-07 / Linear projection matrix CD2_2 = 5.563810879E-05 / Linear projection matrix END CRPIX1 = 1.346289045E+03 / Reference pixel on this axis CRPIX2 = 1.709471785E+02 / Reference pixel on this axis CD1_1 = -5.599080495E-05 / Linear projection matrix CD1_2 = -8.983988319E-08 / Linear projection matrix CD2_1 = -8.848773801E-08 / Linear projection matrix CD2_2 = 5.577800135E-05 / Linear projection matrix END CRPIX1 = 3.470479019E+03 / Reference pixel on this axis CRPIX2 = 4.318659513E+03 / Reference pixel on this axis CD1_1 = -5.566860495E-05 / Linear projection matrix CD1_2 = 1.091114667E-07 / Linear projection matrix CD2_1 = -2.184032120E-07 / Linear projection matrix CD2_2 = 5.565779411E-05 / Linear projection matrix END CRPIX1 = -2.979128543E+03 / Reference pixel on this axis CRPIX2 = 4.302122889E+03 / Reference pixel on this axis CD1_1 = -5.492983863E-05 / Linear projection matrix CD1_2 = -4.839165366E-07 / Linear projection matrix CD2_1 = -8.340787864E-08 / Linear projection matrix CD2_2 = 5.528860429E-05 / Linear projection matrix END CRPIX1 = -2.881903379E+03 / Reference pixel on this axis CRPIX2 = 1.634572463E+02 / Reference pixel on this axis CD1_1 = -5.492714486E-05 / Linear projection matrix CD1_2 = 3.001470043E-07 / Linear projection matrix CD2_1 = -1.089400606E-07 / Linear projection matrix CD2_2 = 5.530103130E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/SuprimeCam_200101-200104@SUBARU.ini000066400000000000000000000024131417631501300233430ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SuprimeCam_200101-200104@SUBARU INSTSHORT=SUP # Number of chips NCHIPS=9 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.202 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=1990 [7]=1980 [8]=1980 [9]=3) OVSCANX2=([1]=20 [2]=60 [3]=60 [4]=60 [5]=20 [6]=2040 [7]=2040 [8]=2040 [9]=60) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=100 [2]=95 [3]=95 [4]=95 [5]=100 [6]=10 [7]=10 [8]=10 [9]=100) CUTY=([1]=5 [2]=5 [3]=40 [4]=40 [5]=10 [6]=5 [7]=10 [8]=10 [9]=5) SIZEX=([1]=1940 [2]=1945 [3]=1945 [4]=1930 [5]=1935 [6]=1955 [7]=1945 [8]=1940 [9]=1940) SIZEY=([1]=4075 [2]=4075 [3]=4040 [4]=4040 [5]=4050 [6]=4050 [7]=4050 [8]=4050 [9]=4075) # Reference pixels for each chip. REFPIXX=([1]=5356 [2]=3233 [3]=1097 [4]=-1026 [5]=-1026 [6]=1023 [7]=3146 [8]=-3223 [9]=-3136) REFPIXY=([1]=-50 [2]=-50 [3]=4142 [4]=4142 [5]=-50 [6]=-50 [7]=4142 [8]=4142 [9]=-50) TYPE=OPT THELI-3.1.3/config/instruments/SuprimeCam_200101-200104@SUBARU_1.reg000066400000000000000000000001641417631501300235620ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and image polygon(915,4077,1122,4082,1124,-24,912,-9) THELI-3.1.3/config/instruments/SuprimeCam_200105-200807@SUBARU.ahead000066400000000000000000000114321417631501300236450ustar00rootroot00000000000000CRPIX1 = 5.329699177830E+03 / Reference pixel on this axis CRPIX2 = -1.385763048352E+01 / Reference pixel on this axis CD1_1 = -5.497906897895E-05 / Linear projection matrix CD1_2 = -1.347284388029E-07 / Linear projection matrix CD2_1 = 2.972850556371E-07 / Linear projection matrix CD2_2 = 5.532226187501E-05 / Linear projection matrix END CRPIX1 = 3.159644122060E+03 / Reference pixel on this axis CRPIX2 = -1.961323246153E+01 / Reference pixel on this axis CD1_1 = -5.565227183517E-05 / Linear projection matrix CD1_2 = 1.391265128262E-07 / Linear projection matrix CD2_1 = 3.987873100670E-07 / Linear projection matrix CD2_2 = 5.565386496483E-05 / Linear projection matrix END CRPIX1 = 1.019585043136E+03 / Reference pixel on this axis CRPIX2 = 4.109554295388E+03 / Reference pixel on this axis CD1_1 = -5.595273546709E-05 / Linear projection matrix CD1_2 = 3.242989329383E-07 / Linear projection matrix CD2_1 = 3.472835405383E-07 / Linear projection matrix CD2_2 = 5.575101497794E-05 / Linear projection matrix END CRPIX1 = -1.120361552112E+03 / Reference pixel on this axis CRPIX2 = 4.114503327961E+03 / Reference pixel on this axis CD1_1 = -5.564965100541E-05 / Linear projection matrix CD1_2 = 1.484413950612E-07 / Linear projection matrix CD2_1 = 3.923415498696E-07 / Linear projection matrix CD2_2 = 5.564942665448E-05 / Linear projection matrix END CRPIX1 = -1.112482610092E+03 / Reference pixel on this axis CRPIX2 = -2.861725541599E+01 / Reference pixel on this axis CD1_1 = -5.567907698744E-05 / Linear projection matrix CD1_2 = 3.697216096507E-07 / Linear projection matrix CD2_1 = 6.874959405363E-08 / Linear projection matrix CD2_2 = 5.565452202625E-05 / Linear projection matrix END CRPIX1 = 1.021610648068E+03 / Reference pixel on this axis CRPIX2 = -1.538603367777E+01 / Reference pixel on this axis CD1_1 = -5.596943379899E-05 / Linear projection matrix CD1_2 = 2.831909014345E-07 / Linear projection matrix CD2_1 = 2.961338680592E-07 / Linear projection matrix CD2_2 = 5.576436034947E-05 / Linear projection matrix END CRPIX1 = 5.319242374192E+03 / Reference pixel on this axis CRPIX2 = 4.107358545135E+03 / Reference pixel on this axis CD1_1 = -5.509891404557E-05 / Linear projection matrix CD1_2 = 6.919285099558E-07 / Linear projection matrix CD2_1 = 3.880025504930E-07 / Linear projection matrix CD2_2 = 5.539107955427E-05 / Linear projection matrix END CRPIX1 = 3.158435629086E+03 / Reference pixel on this axis CRPIX2 = 4.113486015752E+03 / Reference pixel on this axis CD1_1 = -5.565000952957E-05 / Linear projection matrix CD1_2 = 5.066092532595E-07 / Linear projection matrix CD2_1 = 2.806313482829E-07 / Linear projection matrix CD2_2 = 5.564668942116E-05 / Linear projection matrix END CRPIX1 = -3.278377843038E+03 / Reference pixel on this axis CRPIX2 = 4.111376790386E+03 / Reference pixel on this axis CD1_1 = -5.506614614655E-05 / Linear projection matrix CD1_2 = 2.192953203683E-08 / Linear projection matrix CD2_1 = 3.616524787747E-07 / Linear projection matrix CD2_2 = 5.543467846918E-05 / Linear projection matrix END CRPIX1 = -3.282756360394E+03 / Reference pixel on this axis CRPIX2 = -1.998736539351E+01 / Reference pixel on this axis CD1_1 = -5.500454550794E-05 / Linear projection matrix CD1_2 = 6.620214684799E-07 / Linear projection matrix CD2_1 = 3.244340081844E-07 / Linear projection matrix CD2_2 = 5.527607485539E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/SuprimeCam_200105-200807@SUBARU.ini000066400000000000000000000025131417631501300233620ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SuprimeCam_200105-200807@SUBARU INSTSHORT=SUP # Number of chips NCHIPS=10 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.202 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=2050 [7]=2050 [8]=2050 [9]=2050 [10]=3) OVSCANX2=([1]=30 [2]=30 [3]=30 [4]=30 [5]=30 [6]=2075 [7]=2075 [8]=2075 [9]=2075 [10]=30) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=37 [2]=37 [3]=37 [4]=37 [5]=37 [6]=5 [7]=5 [8]=5 [9]=5 [10]=37) CUTY=([1]=6 [2]=6 [3]=6 [4]=6 [5]=6 [6]=6 [7]=6 [8]=6 [9]=6 [10]=6) SIZEX=([1]=2039 [2]=2039 [3]=2039 [4]=2039 [5]=2039 [6]=2039 [7]=2039 [8]=2039 [9]=2039 [10]=2039) SIZEY=([1]=4094 [2]=4094 [3]=4094 [4]=4094 [5]=4094 [6]=4094 [7]=4094 [8]=4094 [9]=4094 [10]=4094) # Reference pixels for each chip. REFPIXX=([1]=5353 [2]=3224 [3]=1097 [4]=-1026 [5]=-1020 [6]=1068 [7]=5320 [8]=3192 [9]=-3188 [10]=-3148) REFPIXY=([1]=-35 [2]=-43 [3]=4074 [4]=4075 [5]=-47 [6]=-40 [7]=4072 [8]=4075 [9]=4067 [10]=-47) TYPE=OPT THELI-3.1.3/config/instruments/SuprimeCam_200808-201705@SUBARU.ahead000066400000000000000000000114321417631501300236550ustar00rootroot00000000000000CRPIX1 = -3.330803672509E+03 / Reference pixel on this axis CRPIX2 = -9.770738156799E+01 / Reference pixel on this axis CD1_1 = -6.691272059443E-08 / Linear projection matrix CD1_2 = 5.533124675375E-05 / Linear projection matrix CD2_1 = 5.479591774902E-05 / Linear projection matrix CD2_2 = -6.669375109819E-07 / Linear projection matrix END CRPIX1 = -1.153519216915E+03 / Reference pixel on this axis CRPIX2 = -7.761871820721E+01 / Reference pixel on this axis CD1_1 = 1.327660235748E-07 / Linear projection matrix CD1_2 = 5.560718017478E-05 / Linear projection matrix CD2_1 = 5.563100099641E-05 / Linear projection matrix CD2_2 = -5.091808114098E-07 / Linear projection matrix END CRPIX1 = 9.836942823802E+02 / Reference pixel on this axis CRPIX2 = -7.414249408790E+01 / Reference pixel on this axis CD1_1 = 2.794732950877E-07 / Linear projection matrix CD1_2 = 5.570856509574E-05 / Linear projection matrix CD2_1 = 5.593952240952E-05 / Linear projection matrix CD2_2 = -3.213760713370E-07 / Linear projection matrix END CRPIX1 = -3.328433561221E+03 / Reference pixel on this axis CRPIX2 = 4.265228839672E+03 / Reference pixel on this axis CD1_1 = 5.862374125299E-07 / Linear projection matrix CD1_2 = 5.533837035973E-05 / Linear projection matrix CD2_1 = 5.482098016260E-05 / Linear projection matrix CD2_2 = 5.772795872934E-08 / Linear projection matrix END CRPIX1 = -1.158361635138E+03 / Reference pixel on this axis CRPIX2 = 4.245518832520E+03 / Reference pixel on this axis CD1_1 = 4.318617109361E-07 / Linear projection matrix CD1_2 = 5.561069068788E-05 / Linear projection matrix CD2_1 = 5.562151956478E-05 / Linear projection matrix CD2_2 = -9.539424711968E-08 / Linear projection matrix END CRPIX1 = 9.859016551937E+02 / Reference pixel on this axis CRPIX2 = 4.245568347660E+03 / Reference pixel on this axis CD1_1 = 2.115548034620E-07 / Linear projection matrix CD1_2 = 5.571383253141E-05 / Linear projection matrix CD2_1 = 5.592032905656E-05 / Linear projection matrix CD2_2 = -3.034840347590E-07 / Linear projection matrix END CRPIX1 = 5.303565979060E+03 / Reference pixel on this axis CRPIX2 = -1.043790441377E+02 / Reference pixel on this axis CD1_1 = 6.777083939588E-07 / Linear projection matrix CD1_2 = 5.529163291674E-05 / Linear projection matrix CD2_1 = 5.474664665624E-05 / Linear projection matrix CD2_2 = 8.120214679465E-08 / Linear projection matrix END CRPIX1 = 3.121877426051E+03 / Reference pixel on this axis CRPIX2 = -8.027974000006E+01 / Reference pixel on this axis CD1_1 = 4.485976716802E-07 / Linear projection matrix CD1_2 = 5.559778378440E-05 / Linear projection matrix CD2_1 = 5.562862945868E-05 / Linear projection matrix CD2_2 = -9.566587084420E-08 / Linear projection matrix END CRPIX1 = 5.301188879440E+03 / Reference pixel on this axis CRPIX2 = 4.266258996359E+03 / Reference pixel on this axis CD1_1 = -9.172994205278E-08 / Linear projection matrix CD1_2 = 5.531800822608E-05 / Linear projection matrix CD2_1 = 5.474805441138E-05 / Linear projection matrix CD2_2 = -6.602898927828E-07 / Linear projection matrix END CRPIX1 = 3.121876400255E+03 / Reference pixel on this axis CRPIX2 = 4.244750576479E+03 / Reference pixel on this axis CD1_1 = 1.032119063595E-07 / Linear projection matrix CD1_2 = 5.563369205601E-05 / Linear projection matrix CD2_1 = 5.563282757072E-05 / Linear projection matrix CD2_2 = -5.015125350432E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/SuprimeCam_200808-201705@SUBARU.ini000066400000000000000000000025561417631501300234010ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SuprimeCam_200808-201705@SUBARU INSTSHORT=SUP # Number of chips NCHIPS=10 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.202 GAIN=3.25 # Overscan regions. (set internally) OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. #PLACEHOLDERS! These are set internally CUTX=([1]=20 [2]=20 [3]=20 [4]=20 [5]=20 [6]=20 [7]=20 [8]=20 [9]=20 [10]=20) CUTY=([1]=70 [2]=70 [3]=70 [4]=20 [5]=20 [6]=20 [7]=70 [8]=70 [9]=20 [10]=20) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048 [9]=2048 [10]=2048) SIZEY=([1]=4224 [2]=4224 [3]=4224 [4]=4224 [5]=4224 [6]=4224 [7]=4224 [8]=4224 [9]=4224 [10]=4224) # Reference pixels for each chip. REFPIXX=([1]=-3130 [2]=-1032 [3]=1068 [4]=-3153 [5]=-1068 [6]=1055 [7]=5276 [8]=3184 [9]=5252 [10]=3162) REFPIXY=([1]=-37 [2]=-38 [3]=-40 [4]=4167 [5]=4189 [6]=4214 [7]=25 [8]=-14 [9]=4213 [10]=4212) TYPE=OPT THELI-3.1.3/config/instruments/SuprimeCam_200808-201705@SUBARU.reg000066400000000000000000000002111417631501300233610ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in polygon(11.650591,4216.3237,2036.4404,4213.763,2034.2022,14.77798,17.088035,17.022748) THELI-3.1.3/config/instruments/SuprimeCam_200808-201705_SDFRED@SUBARU.ahead000066400000000000000000000114321417631501300247040ustar00rootroot00000000000000CRPIX1 = -3.285138206E+03 / Reference pixel on this axis CRPIX2 = -3.016340220E+01 / Reference pixel on this axis CD1_1 = -5.490365910E-05 / Linear projection matrix CD1_2 = 3.785612602E-07 / Linear projection matrix CD2_1 = -1.189446282E-07 / Linear projection matrix CD2_2 = 5.532122808E-05 / Linear projection matrix END CRPIX1 = -1.112302070E+03 / Reference pixel on this axis CRPIX2 = -2.665698606E+01 / Reference pixel on this axis CD1_1 = -5.570303591E-05 / Linear projection matrix CD1_2 = 2.021706643E-07 / Linear projection matrix CD2_1 = -1.455763727E-07 / Linear projection matrix CD2_2 = 5.567854532E-05 / Linear projection matrix END CRPIX1 = 1.023200351E+03 / Reference pixel on this axis CRPIX2 = -2.226076765E+01 / Reference pixel on this axis CD1_1 = -5.600267697E-05 / Linear projection matrix CD1_2 = 1.944486156E-08 / Linear projection matrix CD2_1 = 1.695752848E-08 / Linear projection matrix CD2_2 = 5.578758285E-05 / Linear projection matrix END CRPIX1 = -3.282978697E+03 / Reference pixel on this axis CRPIX2 = 4.253186531E+03 / Reference pixel on this axis CD1_1 = -5.493929779E-05 / Linear projection matrix CD1_2 = -3.248298745E-07 / Linear projection matrix CD2_1 = 1.444968402E-07 / Linear projection matrix CD2_2 = 5.533773042E-05 / Linear projection matrix END CRPIX1 = -1.118124006E+03 / Reference pixel on this axis CRPIX2 = 4.244922041E+03 / Reference pixel on this axis CD1_1 = -5.567770817E-05 / Linear projection matrix CD1_2 = -1.617325006E-07 / Linear projection matrix CD2_1 = 1.705047409E-07 / Linear projection matrix CD2_2 = 5.570062896E-05 / Linear projection matrix END CRPIX1 = 1.024702535E+03 / Reference pixel on this axis CRPIX2 = 4.245063557E+03 / Reference pixel on this axis CD1_1 = -5.598843411E-05 / Linear projection matrix CD1_2 = 1.405714641E-08 / Linear projection matrix CD2_1 = -5.864390986E-09 / Linear projection matrix CD2_2 = 5.576954945E-05 / Linear projection matrix END CRPIX1 = 5.334615489E+03 / Reference pixel on this axis CRPIX2 = -2.728818678E+01 / Reference pixel on this axis CD1_1 = -5.486686578E-05 / Linear projection matrix CD1_2 = -3.574234093E-07 / Linear projection matrix CD2_1 = 7.159027104E-08 / Linear projection matrix CD2_2 = 5.524285444E-05 / Linear projection matrix END CRPIX1 = 3.159269569E+03 / Reference pixel on this axis CRPIX2 = -2.712173124E+01 / Reference pixel on this axis CD1_1 = -5.567864520E-05 / Linear projection matrix CD1_2 = -1.474867409E-07 / Linear projection matrix CD2_1 = 1.408378760E-07 / Linear projection matrix CD2_2 = 5.566844892E-05 / Linear projection matrix END CRPIX1 = 5.326523059E+03 / Reference pixel on this axis CRPIX2 = 4.254596248E+03 / Reference pixel on this axis CD1_1 = -5.496584581E-05 / Linear projection matrix CD1_2 = 3.761014689E-07 / Linear projection matrix CD2_1 = -1.682907105E-07 / Linear projection matrix CD2_2 = 5.533013111E-05 / Linear projection matrix END CRPIX1 = 3.159442793E+03 / Reference pixel on this axis CRPIX2 = 4.243294479E+03 / Reference pixel on this axis CD1_1 = -5.568635830E-05 / Linear projection matrix CD1_2 = 1.957188539E-07 / Linear projection matrix CD2_1 = -1.248397343E-07 / Linear projection matrix CD2_2 = 5.569223278E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/SuprimeCam_200808-201705_SDFRED@SUBARU.ini000066400000000000000000000024371417631501300244260ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=SuprimeCam_200808-201705_SDFRED@SUBARU INSTSHORT=SUP # Number of chips NCHIPS=10 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.202 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048 [9]=2048 [10]=2048) SIZEY=([1]=4177 [2]=4177 [3]=4177 [4]=4177 [5]=4177 [6]=4177 [7]=4177 [8]=4177 [9]=4177 [10]=4177) # Reference pixels for each chip. REFPIXX=([1]=-3138 [2]=-1040 [3]=1060 [4]=-3161 [5]=-1076 [6]=1047 [7]=5268 [8]=3176 [9]=5244 [10]=3154) REFPIXY=([1]=-85 [2]=-86 [3]=-88 [4]=4119 [5]=4141 [6]=4166 [7]=-23 [8]=-62 [9]=4165 [10]=4164) TYPE=OPT THELI-3.1.3/config/instruments/TRECS@GEMINI.ini000066400000000000000000000013511417631501300205760ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=TRECS@GEMINI INSTSHORT=TRECS # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.24 OBSLONG=-70.74 # Pixel scale in arcsec PIXSCALE=0.089 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=320) SIZEY=([1]=240) # Reference pixels for each chip. REFPIXX=([1]=160) REFPIXY=([1]=120) TYPE=MIR THELI-3.1.3/config/instruments/TRIPOL_1x1@SAAO.ini000066400000000000000000000013421417631501300211730ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=TRIPOL_1x1@SAAO INSTSHORT=TRIPOL # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-32.37 OBSLONG=20.80 # Pixel scale in arcsec PIXSCALE=0.334 GAIN=1.8 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=512) SIZEY=([1]=512) # Reference pixels for each chip. REFPIXX=([1]=256) REFPIXY=([1]=256) TYPE=OPT THELI-3.1.3/config/instruments/TRIPOL_2x2@SAAO.ini000066400000000000000000000013441417631501300211770ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=TRIPOL_2x2@SAAO INSTSHORT=TRIPOL # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-32.37 OBSLONG=20.80 # Pixel scale in arcsec PIXSCALE=0.6685 GAIN=1.8 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=256) SIZEY=([1]=256) # Reference pixels for each chip. REFPIXX=([1]=128) REFPIXY=([1]=128) TYPE=OPT THELI-3.1.3/config/instruments/Tek2K@CTIO.ini000066400000000000000000000013541417631501300204270ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=Tek2K@CTIO INSTSHORT=Tek2K # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.401 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2046) SIZEY=([1]=2046) # Reference pixels for each chip. REFPIXX=([1]=1023) REFPIXY=([1]=1023) TYPE=OPT THELI-3.1.3/config/instruments/VIMOS@VLT.ahead000066400000000000000000000036441417631501300206020ustar00rootroot00000000000000CRPIX1 = -2.315743171719E+02 / Reference pixel on this axis CRPIX2 = -2.912382328312E+02 / Reference pixel on this axis CD1_1 = -2.803372501533E-07 / Linear projection matrix CD1_2 = 5.725535035392E-05 / Linear projection matrix CD2_1 = -5.727214749088E-05 / Linear projection matrix CD2_2 = -6.973759824134E-08 / Linear projection matrix END CRPIX1 = 2.145272980283E+03 / Reference pixel on this axis CRPIX2 = -3.177648696922E+02 / Reference pixel on this axis CD1_1 = 7.212523456698E-07 / Linear projection matrix CD1_2 = 5.744318229950E-05 / Linear projection matrix CD2_1 = -5.747001515226E-05 / Linear projection matrix CD2_2 = 4.696973663298E-07 / Linear projection matrix END CRPIX1 = 2.285150703508E+03 / Reference pixel on this axis CRPIX2 = 2.695987608450E+03 / Reference pixel on this axis CD1_1 = -1.047767295804E-07 / Linear projection matrix CD1_2 = 5.719313516968E-05 / Linear projection matrix CD2_1 = -5.721306139478E-05 / Linear projection matrix CD2_2 = 1.439046571836E-07 / Linear projection matrix END CRPIX1 = -3.026681301861E+02 / Reference pixel on this axis CRPIX2 = 2.676675334990E+03 / Reference pixel on this axis CD1_1 = -1.177541855678E-07 / Linear projection matrix CD1_2 = 5.718464305846E-05 / Linear projection matrix CD2_1 = -5.723447357721E-05 / Linear projection matrix CD2_2 = -3.618296114656E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/VIMOS@VLT.ini000066400000000000000000000016441417631501300203150ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=VIMOS@VLT INSTSHORT=VIMOS # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.205 GAIN=3.0 # Overscan regions. OVSCANX1=([1]=2 [2]=2 [3]=2 [4]=2) OVSCANX2=([1]=40 [2]=40 [3]=40 [4]=40) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=51 [2]=51 [3]=51 [4]=51) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2046 [2]=2046 [3]=2046 [4]=2046) SIZEY=([1]=2400 [2]=2400 [3]=2400 [4]=2400) # Reference pixels for each chip. REFPIXX=([1]=-232 [2]=2145 [3]=2285 [4]=-303) REFPIXY=([1]=-291 [2]=-318 [3]=2696 [4]=2677) TYPE=OPT THELI-3.1.3/config/instruments/VIMOS@VLT_1.reg000066400000000000000000000003001417631501300205170ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(123.21103,2174.6469,384.83724,2353.48,1885.0483,2356.7917,2037.3876,2244.1931,2035.8035,195.70325,132.57182,192.44986) THELI-3.1.3/config/instruments/VIMOS@VLT_2.reg000066400000000000000000000002771417631501300205350ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(3.9889655,2224.3228,202.69241,2340.2331,1696.28,2320.3628,1944.6593,2138.2179,1924.0779,195.71545,7.148374,202.22222) THELI-3.1.3/config/instruments/VIMOS@VLT_3.reg000066400000000000000000000003011417631501300205220ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(13.924138,2277.3103,2030.7641,2277.3103,2034.0759,237.28828,1818.8138,98.195862,318.60276,88.26069,10.612414,273.71724) THELI-3.1.3/config/instruments/VIMOS@VLT_4.reg000066400000000000000000000002751417631501300205350ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and polygon(53.664828,2240.8814,2037.2305,2234.1009,2030.7641,260.47034,1798.9434,71.702069,331.84966,75.013793,63.6,286.96414) THELI-3.1.3/config/instruments/VIRCAM@VISTA.ahead000066400000000000000000000172201417631501300211020ustar00rootroot00000000000000CRPIX1 = 5.421914911E+03 / Reference pixel on this axis CRPIX2 = 6.926746793E+03 / Reference pixel on this axis CD1_1 = -4.186813415E-08 / Linear projection matrix CD1_2 = 9.351230350E-05 / Linear projection matrix CD2_1 = -9.379984271E-05 / Linear projection matrix CD2_2 = 8.348332657E-07 / Linear projection matrix END CRPIX1 = 2.457292480E+03 / Reference pixel on this axis CRPIX2 = 6.912066633E+03 / Reference pixel on this axis CD1_1 = 1.413405373E-07 / Linear projection matrix CD1_2 = 9.376064223E-05 / Linear projection matrix CD2_1 = -9.437199921E-05 / Linear projection matrix CD2_2 = 4.373177649E-07 / Linear projection matrix END CRPIX1 = -4.809318472E+02 / Reference pixel on this axis CRPIX2 = 6.909605933E+03 / Reference pixel on this axis CD1_1 = 3.832641336E-07 / Linear projection matrix CD1_2 = 9.376821307E-05 / Linear projection matrix CD2_1 = -9.437662723E-05 / Linear projection matrix CD2_2 = 1.115992955E-07 / Linear projection matrix END CRPIX1 = -3.437710804E+03 / Reference pixel on this axis CRPIX2 = 6.929763470E+03 / Reference pixel on this axis CD1_1 = 7.080351578E-07 / Linear projection matrix CD1_2 = 9.358970197E-05 / Linear projection matrix CD2_1 = -9.384557429E-05 / Linear projection matrix CD2_2 = -1.534043607E-07 / Linear projection matrix END CRPIX1 = 5.387507625E+03 / Reference pixel on this axis CRPIX2 = 2.982709204E+03 / Reference pixel on this axis CD1_1 = 1.021106389E-07 / Linear projection matrix CD1_2 = 9.450666268E-05 / Linear projection matrix CD2_1 = -9.417085516E-05 / Linear projection matrix CD2_2 = 4.391145167E-07 / Linear projection matrix END CRPIX1 = 2.448997962E+03 / Reference pixel on this axis CRPIX2 = 2.976819797E+03 / Reference pixel on this axis CD1_1 = 2.027419639E-07 / Linear projection matrix CD1_2 = 9.468094169E-05 / Linear projection matrix CD2_1 = -9.471870782E-05 / Linear projection matrix CD2_2 = 3.506068880E-07 / Linear projection matrix END CRPIX1 = -4.744851178E+02 / Reference pixel on this axis CRPIX2 = 2.977005293E+03 / Reference pixel on this axis CD1_1 = 3.419862115E-07 / Linear projection matrix CD1_2 = 9.467270624E-05 / Linear projection matrix CD2_1 = -9.469836884E-05 / Linear projection matrix CD2_2 = 2.331557235E-07 / Linear projection matrix END CRPIX1 = -3.413947079E+03 / Reference pixel on this axis CRPIX2 = 2.984307127E+03 / Reference pixel on this axis CD1_1 = 4.558707374E-07 / Linear projection matrix CD1_2 = 9.452741764E-05 / Linear projection matrix CD2_1 = -9.417147002E-05 / Linear projection matrix CD2_2 = 7.809101238E-08 / Linear projection matrix END CRPIX1 = 5.387803713E+03 / Reference pixel on this axis CRPIX2 = -9.270550613E+02 / Reference pixel on this axis CD1_1 = 4.310530081E-07 / Linear projection matrix CD1_2 = 9.453114427E-05 / Linear projection matrix CD2_1 = -9.417175572E-05 / Linear projection matrix CD2_2 = 1.301930400E-07 / Linear projection matrix END CRPIX1 = 2.449603332E+03 / Reference pixel on this axis CRPIX2 = -9.199220752E+02 / Reference pixel on this axis CD1_1 = 2.302633580E-07 / Linear projection matrix CD1_2 = 9.470355341E-05 / Linear projection matrix CD2_1 = -9.472371872E-05 / Linear projection matrix CD2_2 = 8.491548377E-08 / Linear projection matrix END CRPIX1 = -4.749639751E+02 / Reference pixel on this axis CRPIX2 = -9.199175024E+02 / Reference pixel on this axis CD1_1 = 2.010966374E-07 / Linear projection matrix CD1_2 = 9.469213911E-05 / Linear projection matrix CD2_1 = -9.471623895E-05 / Linear projection matrix CD2_2 = 3.666060009E-07 / Linear projection matrix END CRPIX1 = -3.414262939E+03 / Reference pixel on this axis CRPIX2 = -9.275512571E+02 / Reference pixel on this axis CD1_1 = 1.024202493E-07 / Linear projection matrix CD1_2 = 9.451321795E-05 / Linear projection matrix CD2_1 = -9.416648438E-05 / Linear projection matrix CD2_2 = 4.613513159E-07 / Linear projection matrix END CRPIX1 = 5.411799542E+03 / Reference pixel on this axis CRPIX2 = -4.857162278E+03 / Reference pixel on this axis CD1_1 = 5.321543666E-07 / Linear projection matrix CD1_2 = 9.376278527E-05 / Linear projection matrix CD2_1 = -9.393573240E-05 / Linear projection matrix CD2_2 = -2.635802507E-07 / Linear projection matrix END CRPIX1 = 2.456304942E+03 / Reference pixel on this axis CRPIX2 = -4.855289183E+03 / Reference pixel on this axis CD1_1 = 4.430175236E-07 / Linear projection matrix CD1_2 = 9.375943370E-05 / Linear projection matrix CD2_1 = -9.435991926E-05 / Linear projection matrix CD2_2 = 1.501465955E-07 / Linear projection matrix END CRPIX1 = -4.820920947E+02 / Reference pixel on this axis CRPIX2 = -4.854272422E+03 / Reference pixel on this axis CD1_1 = 1.391029482E-07 / Linear projection matrix CD1_2 = 9.377117613E-05 / Linear projection matrix CD2_1 = -9.437324791E-05 / Linear projection matrix CD2_2 = 4.160719662E-07 / Linear projection matrix END CRPIX1 = -3.431864471E+03 / Reference pixel on this axis CRPIX2 = -4.868048808E+03 / Reference pixel on this axis CD1_1 = -1.954105894E-07 / Linear projection matrix CD1_2 = 9.370136371E-05 / Linear projection matrix CD2_1 = -9.392484734E-05 / Linear projection matrix CD2_2 = 6.636805144E-07 / Linear projection matrix END THELI-3.1.3/config/instruments/VIRCAM@VISTA.ini000066400000000000000000000032671417631501300206250ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=VIRCAM@VISTA INSTSHORT=VIRCAM # Number of chips NCHIPS=16 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.341 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1 [11]=1 [12]=1 [13]=1 [14]=1 [15]=1 [16]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1 [5]=1 [6]=1 [7]=1 [8]=1 [9]=1 [10]=1 [11]=1 [12]=1 [13]=1 [14]=1 [15]=1 [16]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048 [9]=2048 [10]=2048 [11]=2048 [12]=2048 [13]=2048 [14]=2048 [15]=2048 [16]=2048) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048 [5]=2048 [6]=2048 [7]=2048 [8]=2048 [9]=2048 [10]=2048 [11]=2048 [12]=2048 [13]=2048 [14]=2048 [15]=2048 [16]=2048) # Reference pixels for each chip. REFPIXX=([1]=5385 [2]=2467 [3]=-452 [4]=-3370 [5]=5385 [6]=2467 [7]=-452 [8]=-3370 [9]=5385 [10]=2467 [11]=-452 [12]=-3370 [13]=5385 [14]=2467 [15]=-452 [16]=-3370) REFPIXY=([1]=6849 [2]=6849 [3]=6849 [4]=6849 [5]=2958 [6]=2958 [7]=2958 [8]=2958 [9]=-933 [10]=-933 [11]=-933 [12]=-933 [13]=-4824 [14]=-4824 [15]=-4824 [16]=-4824) TYPE=NIR THELI-3.1.3/config/instruments/VISIR@VLT.ini000066400000000000000000000013521417631501300203100ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=VISIR@VLT INSTSHORT=VISIR # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-24.67 OBSLONG=-70.42 # Pixel scale in arcsec PIXSCALE=0.075 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=254) SIZEY=([1]=256) # Reference pixels for each chip. REFPIXX=([1]=128) REFPIXY=([1]=128) TYPE=MIR THELI-3.1.3/config/instruments/WFC@INT.ahead000066400000000000000000000036201417631501300203030ustar00rootroot00000000000000CRPIX1 = -8.139938403733E+02 / Reference pixel on this axis CRPIX2 = 2.855008253219E+03 / Reference pixel on this axis CD1_1 = -1.192383315789E-06 / Linear projection matrix CD1_2 = -9.207862477014E-05 / Linear projection matrix CD2_1 = -9.202126359802E-05 / Linear projection matrix CD2_2 = 9.332464097260E-07 / Linear projection matrix END CRPIX1 = 3.384811177069E+03 / Reference pixel on this axis CRPIX2 = 1.251769207354E+03 / Reference pixel on this axis CD1_1 = 9.159675829205E-05 / Linear projection matrix CD1_2 = 8.801461476163E-08 / Linear projection matrix CD2_1 = -5.053132105178E-08 / Linear projection matrix CD2_2 = -9.204818915422E-05 / Linear projection matrix END CRPIX1 = 3.417390739260E+03 / Reference pixel on this axis CRPIX2 = 2.802920347843E+03 / Reference pixel on this axis CD1_1 = -1.035686878637E-06 / Linear projection matrix CD1_2 = -9.182718102732E-05 / Linear projection matrix CD2_1 = -9.111763066388E-05 / Linear projection matrix CD2_2 = 1.421712266771E-06 / Linear projection matrix END CRPIX1 = 1.305768750589E+03 / Reference pixel on this axis CRPIX2 = 2.832447169474E+03 / Reference pixel on this axis CD1_1 = -9.661023770768E-07 / Linear projection matrix CD1_2 = -9.217649988447E-05 / Linear projection matrix CD2_1 = -9.222473664038E-05 / Linear projection matrix CD2_2 = 1.087002564325E-06 / Linear projection matrix END THELI-3.1.3/config/instruments/WFC@INT.ini000066400000000000000000000020021417631501300200110ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFC@INT INSTSHORT=WFC # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.331 GAIN=3.0 # Overscan regions. OVSCANX1=([1]=10 [2]=10 [3]=10 [4]=10) OVSCANX2=([1]=45 [2]=45 [3]=45 [4]=45) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=53 [2]=53 [3]=53 [4]=53) CUTY=([1]=4 [2]=4 [3]=4 [4]=4) SIZEX=([1]=2042 [2]=2042 [3]=2042 [4]=2042) SIZEY=([1]=4092 [2]=4092 [3]=4092 [4]=4092) # Reference pixels for each chip. #REFPIXX=([1]=-1110 [2]=2692 [3]=3120 [4]=1010) #REFPIXY=([1]=3549 [2]=945 [3]=3497 [4]=3524) REFPIXX=([1]=-829 [2]=3368 [3]=3396 [4]=1284) REFPIXY=([1]=2879 [2]=1222 [3]=2832 [4]=2862) TYPE=OPT THELI-3.1.3/config/instruments/WFC@INT.nldat000066400000000000000000000001271417631501300203420ustar00rootroot000000000000000.0 1.0 -7.0E-07 2.0E-12 0.0 1.0 -1.5E-07 0.0 0.0 1.0 0.0 0.0 0.0 1.0 -2.5E-07 4.0E-12 THELI-3.1.3/config/instruments/WFC@INT_1.reg000066400000000000000000000002531417631501300202350ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(1390,2004,1394,2005,1394,1446,1389,1446) polygon(1971,1743,2063,1743,2051,-8,1903,-12,1915,1269) THELI-3.1.3/config/instruments/WFC@INT_3.reg000066400000000000000000000006161417631501300202420ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: in # Combine: and image polygon(0,4093,350,4093,351,2089,358,2089,359,4093,460,4093,460,3081,465,3081,465,4093,1221,4093,1221,2798,1221,1699,1218,1693,1225,1680,1233,1680,1240,1691,1240,1699,1235,1703,1235,2778,1253,2785,1262,2805,1261,2853,1262,2884,1258,2896,1256,2904,1253,2956,1248,2963,1248,2996,1245,3000,1246,4093,2043,4093,2043,0,440,0,0,520) THELI-3.1.3/config/instruments/WFC@INT_4.reg000066400000000000000000000011651417631501300202430ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # Sense: out # Combine: and polygon(1743.0717,4096.928,1747.9991,4094.9994,1747,1943.9996,1743.0004,1943.0008,1743.5002,2645.5002,1721.2495,2645.4999,1715.0001,2631.2492,1701,2634.7493,1685.5001,2616.9982,1661.4988,2624.4986,1652.7508,2646.2505,1657.2508,2658.2483,1663.7508,2666.75,1679.0007,2663.4989,1690.2494,2655.2512,1694.7491,2668.0014,1707.2494,2666.2496,1714.9987,2659.7481,1721.2495,2645.4999,1743.5002,2645.5002) polygon(1893.3726,3730.6274,1912.0009,3734.0005,1939.001,3706.0019,1957.9999,3708.0017,1958.001,3697.0008,1931.9992,3676.0004,1899.9987,3701.0019,1894.0014,3715.0003) THELI-3.1.3/config/instruments/WFCCD_WF4K_DUPONT@LCO.ini000066400000000000000000000007231417631501300220770ustar00rootroot00000000000000INSTRUMENT=WFCCD_WF4K_DUPONT@LCO INSTSHORT=WFCCD NCHIPS=1 # Geographic location OBSLAT=-29.00730 OBSLONG=-70.70384 # Plate scale PIXSCALE=0.4855 # Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image) # Detector geometries OVSCANX1=([1]=4070) OVSCANX2=([1]=4190) OVSCANY1=([1]=0) OVSCANY2=([1]=0) CUTX=([1]=920) CUTY=([1]=1401) SIZEX=([1]=2261) SIZEY=([1]=1250) REFPIXX=([1]=1130) REFPIXY=([1]=625) # Camera type TYPE=OPT FLIP=NOFLIP THELI-3.1.3/config/instruments/WFC_2x2@INT.ahead000066400000000000000000000036441417631501300210040ustar00rootroot00000000000000CRPIX1 = 1.393200171049E+03 / Reference pixel on this axis CRPIX2 = 1.448257262501E+03 / Reference pixel on this axis CD1_1 = -1.843912612928E-04 / Linear projection matrix CD1_2 = 2.431460228009E-06 / Linear projection matrix CD2_1 = 2.274930139641E-06 / Linear projection matrix CD2_2 = 1.842641226545E-04 / Linear projection matrix END CRPIX1 = -6.751533846078E+02 / Reference pixel on this axis CRPIX2 = 1.462624423249E+03 / Reference pixel on this axis CD1_1 = -1.832938406547E-04 / Linear projection matrix CD1_2 = 1.441583686992E-07 / Linear projection matrix CD2_1 = 2.575845052964E-07 / Linear projection matrix CD2_2 = 1.841951769670E-04 / Linear projection matrix END CRPIX1 = 1.368077438541E+03 / Reference pixel on this axis CRPIX2 = -6.626496520011E+02 / Reference pixel on this axis CD1_1 = -1.840826973450E-04 / Linear projection matrix CD1_2 = 2.435720605124E-06 / Linear projection matrix CD2_1 = 3.154389908649E-06 / Linear projection matrix CD2_2 = 1.831761086876E-04 / Linear projection matrix END CRPIX1 = 1.383989850844E+03 / Reference pixel on this axis CRPIX2 = 3.889560676446E+02 / Reference pixel on this axis CD1_1 = -1.844460001091E-04 / Linear projection matrix CD1_2 = 2.141518232401E-06 / Linear projection matrix CD2_1 = 2.457885080913E-06 / Linear projection matrix CD2_2 = 1.845072951344E-04 / Linear projection matrix END THELI-3.1.3/config/instruments/WFC_2x2@INT.ini000066400000000000000000000016371417631501300205210ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFC_2x2@INT INSTSHORT=WFC # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.662 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2075 [2]=2 [3]=2075 [4]=2075) OVSCANX2=([1]=2095 [2]=25 [3]=2095 [4]=2095) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=3 [2]=30 [3]=3 [4]=3) CUTY=([1]=30 [2]=50 [3]=30 [4]=30) SIZEX=([1]=2045 [2]=1020 [3]=2045 [4]=2045) SIZEY=([1]=1020 [2]=2045 [3]=1020 [4]=1020) # Reference pixels for each chip. REFPIXX=([1]=1 [2]=1 [3]=1 [4]=1) REFPIXY=([1]=1 [2]=1 [3]=1 [4]=1) TYPE=OPT THELI-3.1.3/config/instruments/WFC_IPHAS@INT.ahead000066400000000000000000000036201417631501300212270ustar00rootroot00000000000000CRPIX1 = -8.149392733558E+02 / Reference pixel on this axis CRPIX2 = 2.851412628324E+03 / Reference pixel on this axis CD1_1 = -1.355398154095E-06 / Linear projection matrix CD1_2 = -9.202268197036E-05 / Linear projection matrix CD2_1 = -9.195500016884E-05 / Linear projection matrix CD2_2 = 1.186845671320E-06 / Linear projection matrix END CRPIX1 = 3.390301254254E+03 / Reference pixel on this axis CRPIX2 = 1.253123640783E+03 / Reference pixel on this axis CD1_1 = 9.158249878888E-05 / Linear projection matrix CD1_2 = -1.753639402592E-07 / Linear projection matrix CD2_1 = -2.670665224091E-07 / Linear projection matrix CD2_2 = -9.199842158849E-05 / Linear projection matrix END CRPIX1 = 3.415758580588E+03 / Reference pixel on this axis CRPIX2 = 2.799781500213E+03 / Reference pixel on this axis CD1_1 = -1.387514874435E-06 / Linear projection matrix CD1_2 = -9.180917403450E-05 / Linear projection matrix CD2_1 = -9.112357055570E-05 / Linear projection matrix CD2_2 = 1.653926303552E-06 / Linear projection matrix END CRPIX1 = 1.304804017726E+03 / Reference pixel on this axis CRPIX2 = 2.833105943880E+03 / Reference pixel on this axis CD1_1 = -1.182766622549E-06 / Linear projection matrix CD1_2 = -9.209146543230E-05 / Linear projection matrix CD2_1 = -9.214974009149E-05 / Linear projection matrix CD2_2 = 1.318200548508E-06 / Linear projection matrix END THELI-3.1.3/config/instruments/WFC_IPHAS@INT.ini000066400000000000000000000016421417631501300207460ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFC_IPHAS@INT INSTSHORT=WFC # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=28.76 OBSLONG=-17.89 # Pixel scale in arcsec PIXSCALE=0.331 GAIN=3.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=4096 [2]=4096 [3]=4096 [4]=4096) # Reference pixels for each chip REFPIXX=([1]=-335 [2]=3177 [3]=3881 [4]=1777) REFPIXY=([1]=3039 [2]=1734 [3]=2996 [4]=3031) TYPE=OPT THELI-3.1.3/config/instruments/WFI@AAT.ini000066400000000000000000000022621417631501300200020ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFI@AAT INSTSHORT=WFI # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-31.28 OBSLONG=149.07 # Pixel scale in arcsec PIXSCALE=0.2295 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2070 [2]=2070 [3]=2070 [4]=2070 [5]=10 [6]=10 [7]=10 [8]=10) OVSCANX2=([1]=2090 [2]=2090 [3]=2090 [4]=2090 [5]=25 [6]=25 [7]=25 [8]=25) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=15 [2]=15 [3]=15 [4]=15 [5]=40 [6]=40 [7]=40 [8]=40) CUTY=([1]=5 [2]=5 [3]=5 [4]=5 [5]=40 [6]=40 [7]=40 [8]=40) SIZEX=([1]=2044 [2]=2044 [3]=2044 [4]=2044 [5]=2044 [6]=2044 [7]=2044 [8]=2044) SIZEY=([1]=4091 [2]=4091 [3]=4091 [4]=4091 [5]=4091 [6]=4091 [7]=4091 [8]=4091) # Reference pixels for each chip. REFPIXX=([1]=-2143 [2]=-51 [3]=2043 [4]=4140 [5]=4161 [6]=2062 [7]=-25 [8]=-2123) REFPIXY=([1]=4099 [2]=4088 [3]=4088 [4]=4090 [5]=-2 [6]=4 [7]=1 [8]=-1) TYPE=OPT THELI-3.1.3/config/instruments/WFI@MPGESO.ahead000066400000000000000000000075101417631501300206530ustar00rootroot00000000000000CRPIX1 = 4.439255727E+03 / Reference pixel on this axis CRPIX2 = 6.989453826E+01 / Reference pixel on this axis CD1_1 = -6.597880429E-05 / Linear projection matrix CD1_2 = -2.255760366E-07 / Linear projection matrix CD2_1 = -1.352802827E-07 / Linear projection matrix CD2_2 = 6.606281393E-05 / Linear projection matrix END CRPIX1 = 2.287210595E+03 / Reference pixel on this axis CRPIX2 = 7.832820552E+01 / Reference pixel on this axis CD1_1 = -6.608740829E-05 / Linear projection matrix CD1_2 = -1.466216481E-07 / Linear projection matrix CD2_1 = -3.798056078E-07 / Linear projection matrix CD2_2 = 6.596397319E-05 / Linear projection matrix END CRPIX1 = 1.497389780E+02 / Reference pixel on this axis CRPIX2 = 7.853218333E+01 / Reference pixel on this axis CD1_1 = -6.597587800E-05 / Linear projection matrix CD1_2 = -3.026237521E-07 / Linear projection matrix CD2_1 = -2.915676375E-07 / Linear projection matrix CD2_2 = 6.600752831E-05 / Linear projection matrix END CRPIX1 = -1.990494878E+03 / Reference pixel on this axis CRPIX2 = 7.856634534E+01 / Reference pixel on this axis CD1_1 = -6.602227970E-05 / Linear projection matrix CD1_2 = -3.357453231E-07 / Linear projection matrix CD2_1 = -2.736949671E-07 / Linear projection matrix CD2_2 = 6.603720819E-05 / Linear projection matrix END CRPIX1 = -1.988489310E+03 / Reference pixel on this axis CRPIX2 = 4.228822136E+03 / Reference pixel on this axis CD1_1 = -6.604096483E-05 / Linear projection matrix CD1_2 = -2.591072808E-07 / Linear projection matrix CD2_1 = -3.104885737E-07 / Linear projection matrix CD2_2 = 6.604617003E-05 / Linear projection matrix END CRPIX1 = 1.520144304E+02 / Reference pixel on this axis CRPIX2 = 4.231801285E+03 / Reference pixel on this axis CD1_1 = -6.595745611E-05 / Linear projection matrix CD1_2 = -2.411552169E-07 / Linear projection matrix CD2_1 = -2.592800529E-07 / Linear projection matrix CD2_2 = 6.600824348E-05 / Linear projection matrix END CRPIX1 = 2.292255344E+03 / Reference pixel on this axis CRPIX2 = 4.231450698E+03 / Reference pixel on this axis CD1_1 = -6.599481032E-05 / Linear projection matrix CD1_2 = -2.967017767E-07 / Linear projection matrix CD2_1 = -2.876472187E-07 / Linear projection matrix CD2_2 = 6.603768740E-05 / Linear projection matrix END CRPIX1 = 4.434926135E+03 / Reference pixel on this axis CRPIX2 = 4.223471262E+03 / Reference pixel on this axis CD1_1 = -6.606722316E-05 / Linear projection matrix CD1_2 = -2.199314633E-07 / Linear projection matrix CD2_1 = -1.575976598E-07 / Linear projection matrix CD2_2 = 6.597158988E-05 / Linear projection matrix END THELI-3.1.3/config/instruments/WFI@MPGESO.ini000066400000000000000000000022751417631501300203730ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFI@MPGESO INSTSHORT=WFI # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.238 GAIN=2.0 # Overscan regions. OVSCANX1=([1]=10 [2]=10 [3]=10 [4]=10 [5]=2105 [6]=2105 [7]=2105 [8]=10) OVSCANX2=([1]=40 [2]=40 [3]=40 [4]=40 [5]=2135 [6]=2135 [7]=2135 [8]=40) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=51 [2]=51 [3]=51 [4]=51 [5]=51 [6]=51 [7]=51 [8]=51) CUTY=([1]=31 [2]=31 [3]=31 [4]=31 [5]=2 [6]=2 [7]=2 [8]=2) SIZEX=([1]=2032 [2]=2032 [3]=2032 [4]=2032 [5]=2032 [6]=2032 [7]=2032 [8]=2032) SIZEY=([1]=4092 [2]=4092 [3]=4092 [4]=4092 [5]=4092 [6]=4092 [7]=4092 [8]=4092) # Reference pixels for each chip. REFPIXX=([1]=3867 [2]=1721 [3]=-416 [4]=-2551 [5]=-2552 [6]=-412 [7]=1725 [8]=3864) REFPIXY=([1]=-233 [2]=-231 [3]=-224 [4]=-225 [5]=3893 [6]=3888 [7]=3885 [8]=3886) TYPE=OPT THELI-3.1.3/config/instruments/WFI@SSO_40inch.ahead000066400000000000000000000065371417631501300215020ustar00rootroot00000000000000CRPIX1 = -1.911526927963E+03 / Reference pixel on this axis CRPIX2 = 4.073281055934E+03 / Reference pixel on this axis CD1_1 = -2.009819354878E-06 / Linear projection matrix CD1_2 = -1.041554941581E-04 / Linear projection matrix CD2_1 = 1.040620057398E-04 / Linear projection matrix CD2_2 = -1.496071999598E-06 / Linear projection matrix END CRPIX1 = 1.814932862098E+02 / Reference pixel on this axis CRPIX2 = 4.062307082834E+03 / Reference pixel on this axis CD1_1 = -1.671081113051E-06 / Linear projection matrix CD1_2 = -1.043067174175E-04 / Linear projection matrix CD2_1 = 1.045222115621E-04 / Linear projection matrix CD2_2 = -1.444419161088E-06 / Linear projection matrix END CRPIX1 = 2.275977198837E+03 / Reference pixel on this axis CRPIX2 = 4.062293363642E+03 / Reference pixel on this axis CD1_1 = -1.785320909971E-06 / Linear projection matrix CD1_2 = -1.043190170711E-04 / Linear projection matrix CD2_1 = 1.044909810670E-04 / Linear projection matrix CD2_2 = -1.842438807271E-06 / Linear projection matrix END CRPIX1 = 4.376312059920E+03 / Reference pixel on this axis CRPIX2 = 4.067931269585E+03 / Reference pixel on this axis CD1_1 = -1.553519740832E-06 / Linear projection matrix CD1_2 = -1.041802720179E-04 / Linear projection matrix CD2_1 = 1.040001023378E-04 / Linear projection matrix CD2_2 = -1.915748521746E-06 / Linear projection matrix END CRPIX1 = 4.372793259818E+03 / Reference pixel on this axis CRPIX2 = -6.543686511278E+01 / Reference pixel on this axis CD1_1 = -1.922881833751E-06 / Linear projection matrix CD1_2 = -1.042146561141E-04 / Linear projection matrix CD2_1 = 1.039533225109E-04 / Linear projection matrix CD2_2 = -1.529789246560E-06 / Linear projection matrix END CRPIX1 = 2.271560470453E+03 / Reference pixel on this axis CRPIX2 = -5.742204516709E+01 / Reference pixel on this axis CD1_1 = -1.630590823872E-06 / Linear projection matrix CD1_2 = -1.043371188524E-04 / Linear projection matrix CD2_1 = 1.045232014164E-04 / Linear projection matrix CD2_2 = -1.510782166724E-06 / Linear projection matrix END CRPIX1 = -1.914085618914E+03 / Reference pixel on this axis CRPIX2 = -5.898107475518E+01 / Reference pixel on this axis CD1_1 = -1.653982080790E-06 / Linear projection matrix CD1_2 = -1.041556528454E-04 / Linear projection matrix CD2_1 = 1.040609260743E-04 / Linear projection matrix CD2_2 = -2.101761389620E-06 / Linear projection matrix END THELI-3.1.3/config/instruments/WFI@SSO_40inch.ini000066400000000000000000000021501417631501300212020ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFI@SSO_40inch INSTSHORT=WFI # Number of chips NCHIPS=7 # Geographical location of the observatory OBSLAT=-31.27 OBSLONG=149.07 # Pixel scale in arcsec PIXSCALE=0.3748 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=2 [2]=2 [3]=2 [4]=2 [5]=2 [6]=2 [7]=2) OVSCANX2=([1]=13 [2]=13 [3]=13 [4]=13 [5]=35 [6]=35 [7]=35) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=17 [2]=17 [3]=17 [4]=17 [5]=41 [6]=41 [7]=41) CUTY=([1]=6 [2]=6 [3]=6 [4]=6 [5]=41 [6]=41 [7]=41) SIZEX=([1]=2042 [2]=2042 [3]=2042 [4]=2042 [5]=2042 [6]=2042 [7]=2042) SIZEY=([1]=4090 [2]=4090 [3]=4090 [4]=4090 [5]=4090 [6]=4090 [7]=4090) # Reference pixels for each chip. REFPIXX=([1]=-2257 [2]=-165 [3]=1930 [4]=4027 [5]=4022 [6]=1924 [7]=-2262) REFPIXY=([1]=4393 [2]=4384 [3]=4384 [4]=4388 [5]=260 [6]=265 [7]=262) TYPE=OPT THELI-3.1.3/config/instruments/WFI_2x2_2006@MPGESO.ahead000066400000000000000000000075101417631501300220150ustar00rootroot00000000000000CRPIX1 = 1.866044778788E+03 / Reference pixel on this axis CRPIX2 = -1.682738452129E+02 / Reference pixel on this axis CD1_1 = -1.320163786001E-04 / Linear projection matrix CD1_2 = -1.041995153585E-07 / Linear projection matrix CD2_1 = -1.672719995716E-07 / Linear projection matrix CD2_2 = 1.319890358990E-04 / Linear projection matrix END CRPIX1 = 7.970695059327E+02 / Reference pixel on this axis CRPIX2 = -1.655139536805E+02 / Reference pixel on this axis CD1_1 = -1.318455550613E-04 / Linear projection matrix CD1_2 = -3.732590432192E-07 / Linear projection matrix CD2_1 = -4.934454727546E-07 / Linear projection matrix CD2_2 = 1.319518754219E-04 / Linear projection matrix END CRPIX1 = -2.742866907197E+02 / Reference pixel on this axis CRPIX2 = -1.647677755279E+02 / Reference pixel on this axis CD1_1 = -1.319350177622E-04 / Linear projection matrix CD1_2 = -3.721953531011E-07 / Linear projection matrix CD2_1 = -3.230275763270E-07 / Linear projection matrix CD2_2 = 1.319691620287E-04 / Linear projection matrix END CRPIX1 = -1.343908002402E+03 / Reference pixel on this axis CRPIX2 = -1.651613895603E+02 / Reference pixel on this axis CD1_1 = -1.320253293808E-04 / Linear projection matrix CD1_2 = -4.141683595818E-07 / Linear projection matrix CD2_1 = -3.262241144553E-07 / Linear projection matrix CD2_2 = 1.320027932398E-04 / Linear projection matrix END CRPIX1 = -1.343599803786E+03 / Reference pixel on this axis CRPIX2 = 1.908232800315E+03 / Reference pixel on this axis CD1_1 = -1.319989630889E-04 / Linear projection matrix CD1_2 = -3.243432804058E-07 / Linear projection matrix CD2_1 = -4.593184456497E-07 / Linear projection matrix CD2_2 = 1.320031556262E-04 / Linear projection matrix END CRPIX1 = -2.734798679899E+02 / Reference pixel on this axis CRPIX2 = 1.909827967460E+03 / Reference pixel on this axis CD1_1 = -1.318947361835E-04 / Linear projection matrix CD1_2 = -2.918499504924E-07 / Linear projection matrix CD2_1 = -3.626428832326E-07 / Linear projection matrix CD2_2 = 1.320034784577E-04 / Linear projection matrix END CRPIX1 = 7.966141746235E+02 / Reference pixel on this axis CRPIX2 = 1.909991955016E+03 / Reference pixel on this axis CD1_1 = -1.318896835362E-04 / Linear projection matrix CD1_2 = -3.768763727567E-07 / Linear projection matrix CD2_1 = -3.209193049429E-07 / Linear projection matrix CD2_2 = 1.319700803671E-04 / Linear projection matrix END CRPIX1 = 1.868297760746E+03 / Reference pixel on this axis CRPIX2 = 1.908208744664E+03 / Reference pixel on this axis CD1_1 = -1.320306637241E-04 / Linear projection matrix CD1_2 = -2.264388319942E-07 / Linear projection matrix CD2_1 = -2.002757506959E-07 / Linear projection matrix CD2_2 = 1.319493055831E-04 / Linear projection matrix END THELI-3.1.3/config/instruments/WFI_2x2_2006@MPGESO.ini000066400000000000000000000022771417631501300215370ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFI_2x2_2006@MPGESO INSTSHORT=WFI # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.476 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=10 [2]=10 [3]=10 [4]=10 [5]=2105 [6]=2105 [7]=2105 [8]=10) OVSCANX2=([1]=40 [2]=40 [3]=40 [4]=40 [5]=2135 [6]=2135 [7]=2135 [8]=40) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=51 [2]=51 [3]=51 [4]=51 [5]=51 [6]=51 [7]=51 [8]=51) CUTY=([1]=31 [2]=31 [3]=31 [4]=31 [5]=2 [6]=2 [7]=2 [8]=2) SIZEX=([1]=1020 [2]=1020 [3]=1020 [4]=1020 [5]=1020 [6]=1020 [7]=1020 [8]=1020) SIZEY=([1]=2044 [2]=2044 [3]=2044 [4]=2044 [5]=2044 [6]=2044 [7]=2044 [8]=2044) # Reference pixels for each chip. REFPIXX=([1]=1866 [2]=797 [3]=-274 [4]=-1343 [5]=-1343 [6]=-273 [7]=796 [8]=1868) REFPIXY=([1]=-168 [2]=-165 [3]=-164 [4]=-165 [5]=1908 [6]=1909 [7]=1909 [8]=1908) TYPE=OPT THELI-3.1.3/config/instruments/WFI_2x2_2017@MPGESO.ini000066400000000000000000000022511417631501300215310ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WFI_2x2_2017@MPGESO INSTSHORT=WFI # Number of chips NCHIPS=8 # Geographical location of the observatory OBSLAT=-29.257 OBSLONG=-70.73 # Pixel scale in arcsec PIXSCALE=0.476 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=3 [2]=3 [3]=3 [4]=3 [5]=3 [6]=3 [7]=3 [8]=3) OVSCANX2=([1]=23 [2]=23 [3]=23 [4]=23 [5]=23 [6]=23 [7]=23 [8]=23) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=25 [2]=25 [3]=25 [4]=25 [5]=25 [6]=25 [7]=25 [8]=25) CUTY=([1]=16 [2]=16 [3]=16 [4]=16 [5]=2 [6]=2 [7]=2 [8]=2) SIZEX=([1]=1020 [2]=1020 [3]=1020 [4]=1020 [5]=1020 [6]=1020 [7]=1020 [8]=1020) SIZEY=([1]=2044 [2]=2044 [3]=2044 [4]=2044 [5]=2044 [6]=2044 [7]=2044 [8]=2044) # Reference pixels for each chip. REFPIXX=([1]=1866 [2]=797 [3]=-274 [4]=-1343 [5]=-1343 [6]=-273 [7]=796 [8]=1868) REFPIXY=([1]=-168 [2]=-165 [3]=-164 [4]=-165 [5]=1908 [6]=1909 [7]=1909 [8]=1908) TYPE=OPT THELI-3.1.3/config/instruments/WHIRC@WIYN.ini000066400000000000000000000013361417631501300204130ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WHIRC@WIYN INSTSHORT=WHIRC # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=31.95 OBSLONG=-111.6 # Pixel scale in arcsec PIXSCALE=0.0986 GAIN=3.4 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=2048) SIZEY=([1]=2048) # Reference pixels for each chip. REFPIXX=([1]=1028) REFPIXY=([1]=1028) TYPE=NIR THELI-3.1.3/config/instruments/WIRC@Hale.ini000066400000000000000000000013721417631501300203660ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WIRC@Hale INSTSHORT=WIRC # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=33.36 OBSLONG=-116.87 # Pixel scale in arcsec PIXSCALE=0.2487 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=4) CUTY=([1]=31) SIZEX=([1]=2042) SIZEY=([1]=2014) # Reference pixels for each chip. REFPIXX=([1]=1024) REFPIXY=([1]=1024) # Camera type TYPE=NIR THELI-3.1.3/config/instruments/WIRC@Hale.reg000066400000000000000000000002641417631501300203630ustar00rootroot00000000000000# Region file format: DS9 version 4.1 # image # Sense: out polygon(1022.4337,1281.3419,2050,1282,2052,1151,1022.4337,1148.61,1024,1218.25,607.75,1218.5,607.75,1219.5,1024,1219.75) THELI-3.1.3/config/instruments/WIRCam@CFHT.ini000066400000000000000000000016441417631501300205610ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=WIRCam@CFHT INSTSHORT=WIRCam # Number of chips NCHIPS=4 # Geographical location of the observatory OBSLAT=19.82 OBSLONG=-155.47 # Pixel scale in arcsec PIXSCALE=0.300 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0 [2]=0 [3]=0 [4]=0) OVSCANX2=([1]=0 [2]=0 [3]=0 [4]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1 [2]=1 [3]=1 [4]=1) CUTY=([1]=1 [2]=1 [3]=1 [4]=1) SIZEX=([1]=2048 [2]=2048 [3]=2048 [4]=2048) SIZEY=([1]=2048 [2]=2048 [3]=2048 [4]=2048) # Reference pixels for each chip. REFPIXX=([1]=-250 [2]=-250 [3]=1948 [4]=1948) REFPIXY=([1]=100 [2]=2298 [3]=2298 [4]=100) TYPE=NIR THELI-3.1.3/config/instruments/Y4KCam@CTIO.ini000066400000000000000000000013561417631501300205410ustar00rootroot00000000000000# ************************************************************** # Instrument config file created by THELI # ************************************************************** # Name of the instrument (must be unique!) INSTRUMENT=Y4KCam@CTIO INSTSHORT=Y4KCam # Number of chips NCHIPS=1 # Geographical location of the observatory OBSLAT=-30.17 OBSLONG=-70.81 # Pixel scale in arcsec PIXSCALE=0.289 GAIN=1.0 # Overscan regions. OVSCANX1=([1]=0) OVSCANX2=([1]=0) # Sections for the cutting. Select those pixels that receive light. # Give min values for x and y, and the extent in x and y. CUTX=([1]=1) CUTY=([1]=1) SIZEX=([1]=4064) SIZEY=([1]=4064) # Reference pixels for each chip. REFPIXX=([1]=2032) REFPIXY=([1]=2032) TYPE=OPT THELI-3.1.3/man/000077500000000000000000000000001417631501300131375ustar00rootroot00000000000000THELI-3.1.3/man/theli.1000066400000000000000000000007661417631501300143370ustar00rootroot00000000000000.\" Manpage for theli. .\" Contact schirmer@mpia.de to correct errors or typos. .TH theli 1 "May 2020" "theli 3.0.0" "theli man page" .SH NAME theli \- A pipeline for astronomical image data reduction .SH SYNOPSIS .B theli .SH DESCRIPTION A pipeline for astronomical image data reduction. See https://github.com/schirmermischa/THELI for more details. .SH OPTIONS No options. .SH REPORTING BUGS Report bugs to or to the github repository .SH AUTHOR Mischa Schirmer (schirmer@mpia.de) THELI-3.1.3/python/000077500000000000000000000000001417631501300137055ustar00rootroot00000000000000THELI-3.1.3/python/mpc_query.py000066400000000000000000000003631417631501300162650ustar00rootroot00000000000000import sys from astroquery.mpc import MPC name=sys.argv[1] dateobs=sys.argv[2] geolon=sys.argv[3] geolat=sys.argv[4] eph = MPC.get_ephemeris(name, start=dateobs, location=(geolon, geolat, '1000m'), number=1) print(eph['RA'][0], eph['Dec'][0]) THELI-3.1.3/python/resolvetargets.py000066400000000000000000000002331417631501300173260ustar00rootroot00000000000000import sys import astropy.coordinates name = sys.argv[1] coords = astropy.coordinates.get_icrs_coordinates(name) print (coords.ra.value, coords.dec.value) THELI-3.1.3/python/vizquery.py000066400000000000000000000334521417631501300161640ustar00rootroot00000000000000# License: BSD License 2.0 # # Copyright (c) , # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #!/usr/bin/env python """ CDS package to query VizieR big catalogues G.Landais (27/10/2017) VizieRClient.py [-h] [-l] [-i] [-mime=output_format] [-source=..] [asu_params] -h: this help -l: list large catalogues -d: debug -i: table information (table given by -source) -mime: csv|votable|ascii -source: table/catalogue name --file : query with a list asu_params : the ASU parameters ex: -out.max: max number of records -c: center -c.rs: radius in arcsec "Jmag>10" constraint on column Jmag Licensed under a BSD license - see LICENSE.txt for details, reproduced above """ import sys import re import requests try: import numpy from astropy.table import * from astropy.io import ascii from astropy import log log.setLevel('ERROR') use_astropy = True except ImportError: use_astropy = False sys.stderr.write("(WARNING) astropy is not installed\n") if int(sys.version[0]) < 3: import urllib2 as ulib else: import urllib.request as ulib import urllib DEFAULT_RADIUS=2. # arcsec DEFAULT_LIMIT=100 DEBUG = False VIZIER_URL = "http://vizier.u-strasbg.fr/viz-bin/" TAPVIZIER = "http://tapvizier.u-strasbg.fr/TAPVizieR/" FORMAT_TSV = "tsv" FORMAT_VOTABLE = "votable" FORMAT_ASCII = "ascii" def debug(obj): if DEBUG is True: sys.stderr.write("(debug)"+str(obj)+"\n") def error(obj): sys.stderr.write("(error)"+str(obj)+"\n") def std_name(name): if isinstance(name, bytes): return name.decode('utf8').strip() else: return name.strip() class TAP: """Execute TAP queries """ def __init__(self, server): """Constructor :param server: the TAP server root URL """ self.__server = server def __tapurl(self, adql, fmt): query = "/tap/sync?request=doQuery&phase=RUN&lang=ADQL" query += "&format="+fmt #query += "&query="+adql.replace(" ", "+").replace("%","%25") query += "&query="+adql.replace(" ", "+") return query def get_table(self, adql, fmt="votable"): """Execute Synchronous query and bufferise the result :param adql: ADQL query :param fmt: output format :return: astropy.table.Table """ if use_astropy is False: raise Exception("unavailable option - needs to install astropy") query = self.__tapurl(adql, fmt) debug("TAP(GET): " + self.__server + query) return Table.read(self.__server+query) class METAdata: """ Cache METAdata serialize the metadata into a local file with catalogues description (catalogue_name, table_name, column_name) """ def __init__(self): if use_astropy is False: raise Exception("unavailable option - needs to install astropy") self.__tap = TAP(TAPVIZIER) self.__columns = None def info_columns(self, name=None): """get the column info :param name: the table or catalogue name :returns: columns """ if name is None: adql = "SELECT column_name, table_name, col.unit, datatype, description, indexed, std" adql+= " FROM TAP_SCHEMA.columns col" adql+= " JOIN METAtab t on (col.table_name = t.name)" adql+= " JOIN METAdba d on (t.dbaid=d.dbaid)" adql+= " JOIN METAcat c on (c.catid=t.catid)" adql+= " WHERE d.login like 'vizls%'" else: adql = "SELECT column_name, table_name, unit, datatype, description, indexed, std" adql+= " FROM TAP_SCHEMA.columns where table_name like '{0}%'".format(name) table = self.__tap.get_table(adql, FORMAT_VOTABLE) try: table.convert_bytestring_to_unicode() except: sys.stderr("--byte is not converted") for col in table.columns: table[col] = table[col].astype(str) return table def info_table(self, name): """get the table info :param name: search name: data_collection(=catalogue), acronym, table_name :return: astropy table """ if name is None: raise Exception("name is null") adql = "SELECT t.name as table_name, t.explain as description, t.records" adql+= " FROM METAtab t WHERE t.name like '{0}%'".format(name) table = self.__tap.get_table(adql, FORMAT_VOTABLE) for col in table.columns: table[col] = table[col].astype(str) return table def __std_table(self, table): """(Update) standardize an astropy table :param table: table in input """ re_v1 = re.compile("^ *!ext/([^ ]+) .*$") re_v2 = re.compile(".* *-source[= ]+([^ ]*).*") sz = len(table["table_id"]) columnt = Column([0] * sz, dtype=int, name="type") for i in range(sz): value = std_name(table["table_id"][i]) mo = re_v1.match(value) if mo: table["table_id"][i] = mo.group(1).replace(".exe","") columnt[i] = 1 else: mo = re_v2.match(value) if mo: table["table_id"][i] = mo.group(1) columnt[i] = 2 else: columnt[i] = 0 for col in table.columns: table[col] = table[col].astype(str) table.add_column(columnt) def list_large_table(self, catalogue_name=None): """list the large VizieR table :param catalogue_name: catalogue name (VizieR id name) :return: astropy table with large table description """ adql = "SELECT c.name as data_collection, t.name as table_name, t.explain as description, t.records, t.filename as table_id" adql+= " FROM METAtab t join METAdba d on (t.dbaid=d.dbaid)" adql+= " join METAcat c on (c.catid=t.catid)" adql+= " WHERE d.login like 'vizls%'" if catalogue_name is not None: adql += " AND t.name like '{0}/%'".format(catalogue_name) table = self.__tap.get_table(adql, FORMAT_VOTABLE) self.__std_table(table) return table USER_AGENT = "python-vizquery" class CDSClient: """ VizieR client """ def __init__(self, default_format=FORMAT_ASCII, default_radius=DEFAULT_RADIUS, default_limit=DEFAULT_LIMIT): """ Constructor. :param default_format: default output format :param default_radius: default radius :param default_limit: default limit of records returned """ self.format = default_format self.radius = default_radius self.limit = default_limit self.__source = None self.__parameters = None self.__filename = None def __service(self, format): if format == FORMAT_TSV: return "asu-tsv" elif format == FORMAT_VOTABLE: return "votable" else : return "asu-txt" def __url(self, format = None): if format is None: out = self.format else: out = format url = "{0}/{1}?".format(VIZIER_URL, self.__service(out)) if self.__source is None: raise Exception("source is required") url +="&-source="+self.__source if self.__parameters is None: return url for param in self.__parameters: url += "&"+param return url def query(self, name, params, filename=None): """ Prepare the query :param name: table designation :param params: asu parameters :param filename: constraint filename submitted :return: url/adql """ self.__source= name self.__parameters = params if filename is not None: self.__filename = filename return self.__url() def get(self): """get the data in an astropy table :return: result in astropy table """ if use_astropy is False: raise Exception("unavailable option - needs to install astropy") url = self.__url(FORMAT_TSV) debug("url:" + url) return ascii.read(url, comment='^#', format='fixed_width_no_header', delimiter='\t') def post(self): """get the data in an astropy table usinf a file list :return: result in astropy table """ if self.__filename is None: fd = self.__get_http() else: fd = self.__post_http() return ascii.read(fd.text) def __get_http(self): url = self.__url() debug("url:"+url) request = ulib.Request(url) request.add_header("User-Agent", USER_AGENT) return ulib.urlopen(request) def __post_http(self): self.__parameters.append("-source="+self.__source) url = "{0}/{1}?".format(VIZIER_URL, self.__service(self.format)) debug("url(post):"+url) sort_list = None params = [] for parameter in self.__parameters: p = parameter.split('=') if len(p) != 2: raise Exception("unrecognized parameter {0} in file upload".format(parameter)) if p[0] == "-sort": sort_list = p[1] params.append((p[0],p[1])) if sort_list: return requests.post(url, headers={"User-Agent": USER_AGENT}, data=params, files={'*-sort': open(self.__filename, 'r')}) else: return requests.post(url, headers={"User-Agent": USER_AGENT}, data=params, files={'-c': open(self.__filename, 'r')}) def print_stdout(self): """ print result into stdout """ if self.__filename is None: fd = self.__get_http() else: fd = self.__post_http() for line in fd: sys.stdout.write(line.decode('utf8')) if __name__ == "__main__": __info = False __params = [] __mime = None __source = None __filename = None reg_constraint = re.compile("^(.*)([<>])([^<>]*)$") for __o in sys.argv[1:]: if __o in ("-h", "--help"): help("__main__") sys.exit(1) elif __o in ("-i", "--info"): __info = True elif __o in ("-d", "--debug"): DEBUG = True elif __o in ("-l", "--list"): meta = METAdata() tables = meta.list_large_table() for table in tables: if table[4].find(".dat") > 0: continue print ("{1} ({3} records) id={4}\n {2}".format(table[0], table[1], table[2], table[3], table[4])) sys.exit(0) elif __o.find("--file=") == 0: __filename = __o[7:] continue else: """asu params""" mo = re.match("^-source=(.*)$", __o) if mo: __source = mo.group(1) else: mo = re.match("-mime=(.*)$", __o) if mo: __mime = mo.group(1) continue if __o[0] == '-': __params.append(__o) continue if __o.find("=") > 0: __params.append(__o) continue m = reg_constraint.match(__o) if m is None: raise Exception("unavailable parameter " + __o) __params.append("{0}={1}{2}".format(m.group(1), m.group(2), m.group(3))) if __source is None: help("__main__") sys.exit(1) if __info is True: meta = METAdata() tables = meta.info_table(__source) for table in tables: print("{0} ({2} records)\t{1}".format(table[0], table[1], table[2])) columns = meta.info_columns(table[0]) for column in columns: opt = "" if (column[4] == '1'): opt += "(i)" if (column[5] == '1'): opt += "(p)" print("{0:32s} {1:10s} {2:6s} {3}".format(column[0], column[1], opt, column[3])) print() print ("(i) : indexed column\n(p) default column") sys.exit(0) client = CDSClient() if __mime is not None: if __mime in (FORMAT_TSV, FORMAT_VOTABLE, FORMAT_ASCII): client.format = __mime #print(__params) client.query(__source, __params, __filename) client.print_stdout() THELI-3.1.3/src/000077500000000000000000000000001417631501300131535ustar00rootroot00000000000000THELI-3.1.3/src/THELI.pro000066400000000000000000000216171417631501300145510ustar00rootroot00000000000000#------------------------------------------------- # # Project created by QtCreator 2018-02-18T10:31:22 # #------------------------------------------------- QT += core gui printsupport testlib widgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = theli TEMPLATE = app # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ main.cc \ abszp/absphot.cc \ abszp/abszeropoint.cc \ colorpicture/colorpicture.cc \ colorpicture/refcatdata.cc \ colorpicture/subtaskColorcalib.cc \ colorpicture/subtaskCropcoadd.cc \ colorpicture/subtaskbbnb.cc \ colorpicture/subtaskfits2tiff.cc \ consistencychecks.cc \ datadir.cc \ datamodel/datamodel.cc \ deepmessages.cc \ dockwidgets/confdockwidget.cc \ dockwidgets/defaults.cc \ dockwidgets/memoryviewer.cc \ dockwidgets/monitor.cc \ dockwidgets/validate_confdock.cc \ functions.cc \ imagestatistics/imagestatistics.cc \ imagestatistics/imagestatistics_events.cc \ imagestatistics/imagestatistics_plotting.cc \ instrumentdefinition.cc \ iview/actions.cc \ iview/constructors.cc \ iview/dockwidgets/ivcolordockwidget.cc \ iview/dockwidgets/ivconfdockwidget.cc \ iview/dockwidgets/ivscampdockwidget.cc \ iview/dockwidgets/ivwcsdockwidget.cc \ iview/events.cc \ iview/iview.cc \ iview/mygraphicsellipseitem.cc \ iview/mygraphicsscene.cc \ iview/mygraphicsview.cc \ iview/mybinnedgraphicsview.cc \ iview/mymagnifiedgraphicsview.cc \ iview/dockwidgets/ivstatisticsdockwidget.cc \ iview/transformations.cc \ iview/myqgraphicsrectitem.cc \ iview/dockwidgets/ivfinderdockwidget.cc \ iview/dockwidgets/ivredshiftdockwidget.cc \ iview/myaxis.cc \ iview/redshift.cc \ mainwindow.cc \ myimage/astrometrynet.cc \ myimage/background.cc \ myimage/fitsinterface.cc \ myimage/memoryoperations.cc \ myimage/myimage.cc \ myimage/segmentation.cc \ myimage/skysub.cc \ myimage/sourceextractor.cc \ myimage/tifftools.cc \ myimage/weighting.cc \ myimage/writefits.cc \ preferences.cc \ processingExternal/errordialog.cc \ processingInternal/controller.cc \ processingInternal/data.cc \ processingInternal/displayconfig.cc \ processingInternal/dictionaries.cc \ processingInternal/mask.cc \ processingInternal/photinst.cc \ processingInternal/processingAncillary.cc \ processingInternal/processingAstrometry.cc \ processingInternal/processingBackground.cc \ processingInternal/processingCalibration.cc \ processingInternal/processingCoadd.cc \ processingInternal/processingCollapse.cc \ processingInternal/processingSkysub.cc \ processingInternal/processingSplitter.cc \ processingInternal/processingWeight.cc \ processingInternal/processingCreateSourceCat.cc \ processingStatus/processingStatus.cc \ qcustomplot.cpp \ query/query.cc \ readmes/imstatsreadme.cc \ readmes/multidirreadme.cc \ readmes/scampreadme.cc \ readmes/swarpreadme.cc \ readmes/license.cc \ readmes/acknowledging.cc \ settings.cc \ status.cc \ taskinfrastructure.cc \ tasks.cc \ threading/abszpworker.cc \ threading/colorpictureworker.cc \ threading/mainguiworker.cc \ threading/memoryworker.cc \ threading/scampworker.cc \ threading/sourceextractorworker.cc \ threading/swarpworker.cc \ threading/worker.cc \ threading/anetworker.cc \ tools/cfitsioerrorcodes.cc \ tools/correlator.cc \ tools/cpu.cc \ tools/debayer.cc \ tools/detectedobject.cc \ tools/fileprogresscounter.cc \ tools/fitgauss1d.cc \ tools/fitting.cc \ tools/imagequality.cc \ tools/polygon.cc \ tools/ram.cc \ tools/splitter.cc \ tools/splitter_RAW.cc \ tools/splitter_buildHeader.cc \ tools/splitter_processingGeneric.cc \ tools/splitter_processingSpecific.cc \ tools/splitter_queryHeaderLists.cc \ tools/splitter_multiport.cc \ tools/swarpfilter.cc \ tools/tools.cc \ tools/xcorr.cc \ validators.cc \ readmes/tutorials.cc HEADERS += \ abszp/absphot.h \ abszp/abszeropoint.h \ colorpicture/colorpicture.h \ colorpicture/refcatdata.h \ datadir.h \ datamodel/datamodel.h \ dockwidgets/confdockwidget.h \ dockwidgets/memoryviewer.h \ dockwidgets/monitor.h \ functions.h \ imagestatistics/imagestatistics.h \ instrumentdata.h \ instrumentdefinition.h \ iview/dockwidgets/ivcolordockwidget.h \ iview/dockwidgets/ivconfdockwidget.h \ iview/dockwidgets/ivscampdockwidget.h \ iview/dockwidgets/ivwcsdockwidget.h \ iview/iview.h \ iview/mygraphicsellipseitem.h \ iview/mygraphicsscene.h \ iview/mygraphicsview.h \ iview/mybinnedgraphicsview.h \ iview/mymagnifiedgraphicsview.h \ iview/dockwidgets/ivstatisticsdockwidget.h \ iview/myqgraphicsrectitem.h \ iview/dockwidgets/ivfinderdockwidget.h \ iview/dockwidgets/ivredshiftdockwidget.h \ iview/myaxis.h \ mainwindow.h \ myimage/myimage.h \ preferences.h \ processingExternal/errordialog.h \ processingInternal/controller.h \ processingInternal/data.h \ processingInternal/mask.h \ processingInternal/photinst.h \ processingStatus/processingStatus.h \ qcustomplot.h \ query/query.h \ readmes/acknowledging.h \ readmes/imstatsreadme.h \ readmes/license.h \ readmes/multidirreadme.h \ readmes/scampreadme.h \ readmes/swarpreadme.h \ status.h \ threading/abszpworker.h \ threading/anetworker.h \ threading/colorpictureworker.h \ threading/mainguiworker.h \ threading/memoryworker.h \ threading/scampworker.h \ threading/sourceextractorworker.h \ threading/swarpworker.h \ threading/worker.h \ tools/cfitsioerrorcodes.h \ tools/correlator.h \ tools/cpu.h \ tools/detectedobject.h \ tools/fileprogresscounter.h \ tools/fitgauss1d.h \ tools/fitting.h \ tools/imagequality.h \ tools/polygon.h \ tools/ram.h \ tools/splitter.h \ tools/swarpfilter.h \ tools/tools.h \ readmes/tutorials.h FORMS += \ mainwindow.ui \ abszp/abszeropoint.ui \ colorpicture/colorpicture.ui \ dockwidgets/confdockwidget.ui \ dockwidgets/monitor.ui \ dockwidgets/memoryviewer.ui \ imagestatistics/imagestatistics.ui \ instrumentdefinition.ui \ iview/iview.ui \ iview/dockwidgets/ivconfdockwidget.ui \ iview/dockwidgets/ivscampdockwidget.ui \ iview/dockwidgets/ivcolordockwidget.ui \ iview/dockwidgets/ivwcsdockwidget.ui \ iview/dockwidgets/ivstatisticsdockwidget.ui \ preferences.ui \ processingExternal/errordialog.ui \ readmes/imstatsreadme.ui \ readmes/multidirreadme.ui \ readmes/scampreadme.ui \ readmes/swarpreadme.ui \ readmes/license.ui \ readmes/acknowledging.ui \ iview/dockwidgets/ivfinderdockwidget.ui \ iview/dockwidgets/ivredshiftdockwidget.ui \ readmes/tutorials.ui RESOURCES = resources.qrc installfiles.files = theli installfiles.path = /usr/bin INSTALLS += installfiles configfiles.files += ../config/default.conv configfiles.files += ../config/default.nnw configfiles.files += ../config/default.param configfiles.path = /usr/share/theli/config/ INSTALLS += configfiles instrumentfiles.files = ../config/instruments/* instrumentfiles.path = /usr/share/theli/config/instruments INSTALLS += instrumentfiles python.files += ../python/* python.path = /usr/share/theli/python INSTALLS += python CONFIG += c++11 # QMAKE_CXXFLAGS += -g unix:!macx { QMAKE_CXXFLAGS += -fopenmp QMAKE_LFLAGS += -fopenmp LIBS += -lcfitsio -lcurl -lfftw3_omp -lfftw3 -lm -lgsl -lgslcblas -lwcs -ltiff -lraw } macx: { QMAKE_CXXFLAGS += -Xpreprocessor -fopenmp QMAKE_LFLAGS += -Xpreprocessor -fopenmp LIBS += -L/usr/local/lib -lcfitsio -lcurl -lfftw3_omp -lfftw3 -lm -lgsl -lgslcblas -lwcs -ltiff -lraw -lomp } QMAKE_CXXFLAGS += -Wall CONFIG(release, debug|release) { CONFIG += optimize_full } # suppress a larger number of harmless warnings (because of QMetaObject use which requires identical arguments # in the functions it invokes, even though these functions don't need all arguments) QMAKE_CXXFLAGS_WARN_ON += -Wno-unused-parameter INCLUDEPATH += /usr/include/wcslib/ INCLUDEPATH += /usr/local/include/wcslib/ DISTFILES += \ ../man/theli.1 THELI-3.1.3/src/THELI.pro.user000066400000000000000000000567101417631501300155300ustar00rootroot00000000000000 EnvironmentId {aaef6f40-b7e5-4da0-9fbe-38b50c9bbf78} ProjectExplorer.Project.ActiveTarget 0 ProjectExplorer.Project.EditorSettings true false true Cpp CppGlobal QmlJS QmlJSGlobal 2 UTF-8 false 4 false 80 true true 1 true false 0 true true 0 8 true 1 true true true false ProjectExplorer.Project.PluginSettings ProjectExplorer.Project.Target.0 Desktop Desktop {16fdfd03-62c4-442a-b13a-1b34672408b1} 1 0 0 /home/mischa/devel/THELI/build-THELI-Desktop-Debug true qmake QtProjectManager.QMakeBuildStep true false false false true Make Qt4ProjectManager.MakeStep -w -r false 2 Build ProjectExplorer.BuildSteps.Build true Make Qt4ProjectManager.MakeStep -w -r true clean 1 Clean ProjectExplorer.BuildSteps.Clean 2 false Debug Qt4ProjectManager.Qt4BuildConfiguration 2 true /home/mischa/devel/THELI/build-THELI-Desktop-Release true qmake QtProjectManager.QMakeBuildStep false false false false true Make Qt4ProjectManager.MakeStep -w -r false 2 Build ProjectExplorer.BuildSteps.Build true Make Qt4ProjectManager.MakeStep -w -r true clean 1 Clean ProjectExplorer.BuildSteps.Clean 2 false Release Qt4ProjectManager.Qt4BuildConfiguration 0 true /home/mischa/devel/THELI/build-THELI-Desktop-Profile true qmake QtProjectManager.QMakeBuildStep true false true false true Make Qt4ProjectManager.MakeStep -w -r false 2 Build ProjectExplorer.BuildSteps.Build true Make Qt4ProjectManager.MakeStep -w -r true clean 1 Clean ProjectExplorer.BuildSteps.Clean 2 false Profile Qt4ProjectManager.Qt4BuildConfiguration 0 true 3 0 Deploy ProjectExplorer.BuildSteps.Deploy 1 Deploy locally ProjectExplorer.DefaultDeployConfiguration 1 false false 1000 true false false false false true 0.01 10 true 1 25 1 true false true valgrind 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 THELI Qt4ProjectManager.Qt4RunConfiguration:/home/mischa/devel/THELI/src/THELI.pro true THELI.pro false /home/mischa/devel/THELI/build-THELI-Desktop-Release 3768 false true false false true 1 ProjectExplorer.Project.TargetCount 1 ProjectExplorer.Project.Updater.FileVersion 18 Version 18 THELI-3.1.3/src/abszp/000077500000000000000000000000001417631501300142725ustar00rootroot00000000000000THELI-3.1.3/src/abszp/absphot.cc000066400000000000000000000237451417631501300162540ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "absphot.h" #include "../functions.h" #include "../instrumentdata.h" #include #include #include AbsPhot::AbsPhot() { } void AbsPhot::clear() { qv_ZP.clear(); qv_mag1ref.clear(); qv_mag2ref.clear(); qv_mag1errref.clear(); qv_mag2errref.clear(); qv_colorIndividual.clear(); qv_colorErrIndividual.clear(); qv_ZPIndividual.clear(); qv_ZPerrIndividual.clear(); qv_colorIndividualOutlier.clear(); qv_ZPIndividualOutlier.clear(); qv_colorManualOutlier.clear(); qv_ZPManualOutlier.clear(); qv_magauto.clear(); qv_magerrauto.clear(); qv_magaper.clear(); qv_magerraper.clear(); qv_apertures.clear(); qv_fitMask.clear(); qv_fitMask_old.clear(); qv_ManualMask.clear(); qv_ManualMask_old.clear(); filter = ""; colorfilter = ""; color = ""; initialized = false; numAper = 0; numObj = 0; ZPauto = 0.; ZPautoerr = 0.; ZPSelected = ""; ZPerrSelected = ""; Color1Selected = ""; Color2Selected = ""; Color3Selected = ""; } void AbsPhot::getColor() { QString filter1 = color.split("-").at(0); QString filter2 = color.split("-").at(1); qv_colorIndividual.clear(); qv_colorErrIndividual.clear(); qv_ZPIndividual.clear(); for (int i=0; i dummyZPaper; for (int i=0; i 0) { double tmperr = rmsMask_T(qv_ZPerrIndividual, qv_fitMask) / sqrt(numObj); tmp_mederr = sqrt(tmp_mederr*tmp_mederr + tmperr*tmperr); } qv_ZP.append(medianMask_T(dummyZPaper, qv_fitMask)); qv_ZPerr.append(tmp_mederr); dummyZPaper.clear(); } // Calculate the ZP for MAG_AUTO QVector dummyZPauto; for (int j=0; j 0) { double tmperr = rmsMask_T(qv_ZPerrIndividual, qv_fitMask) / sqrt(numObj); ZPautoerr = sqrt(ZPautoerr*ZPautoerr + tmperr*tmperr); } } long AbsPhot::setupFitMask() { // Initially, allow all objects to enter the fit; // Also initializes qv_fitMask for the first time; qv_fitMask.fill(false, numObj); qv_fitMask_old.fill(false, numObj); // Exclude objects which have been manually rejected long count = 0; for (long i=0; i residuals = QVector(); for (long i=0; i kappa*rmsval) qv_fitMask[i] = true; else qv_fitMask[i] = false; } // Compare with previous flag set int check = 1; for (long i=0; isize; ++i) { gsl_vector_set(w, i, gsl_vector_get(w_orig, i)); } // 3 sigma outlier rejection (setting the weights to zero for the next fit) for (size_t i=0; isize; ++i) { if (gsl_vector_get(r, i) > 3.*gsl_vector_get(yerr, i)) { gsl_vector_set(w, i, 0.); } } ++iter; } gsl_multifit_linear_free(work); // Store the result, after resetting all parameters (un-used params for a lower order fit are explicitly set to 0) for (int k=0; k class AbsPhot { public: AbsPhot(); QVector qv_RA = QVector(); QVector qv_DEC = QVector(); QVector qv_ZP = QVector(); // the median ZP per aperture QVector qv_ZPerr = QVector(); // the median ZP err per aperture QVector qv_mag1ref = QVector(); // the reference magnitude per object QVector qv_mag2ref = QVector(); // the reference magnitude to construct the color term per object QVector qv_mag1errref = QVector(); // the reference magnitude error per object QVector qv_mag2errref = QVector(); // the reference magnitude error to construct the color term per object QVector qv_colorIndividual = QVector(); // individual color index per object QVector qv_colorErrIndividual = QVector(); // individual color index error per object QVector qv_ZPIndividual = QVector(); // individual ZP per object (magref - magobj) QVector qv_ZPerrIndividual = QVector(); // individual ZP error per object (magref - magobj) QVector qv_colorIndividualOutlier = QVector(); // individual color term per object that did not survive the fit QVector qv_ZPIndividualOutlier = QVector(); // individual ZP per object (magref - magobj) that did not survive the fit QVector qv_colorManualOutlier = QVector(); // individual color term per object that was manually rejected QVector qv_ZPManualOutlier = QVector(); // individual ZP per object (magref - magobj) that was manually rejected QVector qv_magauto = QVector(); // MAG_AUTO per object QVector qv_magerrauto = QVector(); // MAGERR_AUTO per object QVector qv_apertures = QVector(); // aperture sizes QVector qv_fitMask = QVector(); // whether an individual object is masked for a fit iteration QVector qv_fitMask_old = QVector(); // whether an individual object is masked for a fit iteration previously QVector qv_ManualMask = QVector(); // whether an individual object was manually selected for exclusion QVector qv_ManualMask_old = QVector(); // whether an individual object was previously manually selected for exclusion // dims of magaper: numObj vectors, each vector conaining numAper apertures QVector< QVector > qv_magaper = QVector< QVector >(); // contains all individual apertures per object, per aperture QVector< QVector > qv_magerraper = QVector< QVector >(); // contains all individual apertures per object, per aperture QString filter = ""; QString colorfilter = ""; QString color = ""; double slope = 0.; double cutoff = 0.; int numAper = 0; int numObj = 0; int num_outliers = 0; int num_ManualOutliers = 0; QVector fitParams = QVector(4,0.); QVector fitParamsErr = QVector(4,0.); bool initialized = false; double ZPauto = 0.; double ZPautoerr = 0.; QString ZPSelected; QString ZPerrSelected; QString Color1Selected; QString Color2Selected; QString Color3Selected; QString ColorErr1Selected; QString ColorErr2Selected; QString ColorErr3Selected; void regressionLinfit(); // using an iterative linear fit bool regression(int fitOrder); // Using a GSL polynomial fit void clear(); void getColor(); void getZP(); private: long setupFitMask(); }; #endif // ABSPHOT_H THELI-3.1.3/src/abszp/abszeropoint.cc000066400000000000000000001446531417631501300173350ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "abszeropoint.h" #include "ui_abszeropoint.h" #include "../functions.h" #include "../instrumentdata.h" #include "../qcustomplot.h" #include "../query/query.h" #include "../myimage/myimage.h" #include "../threading/memoryworker.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "fitsio2.h" #include #include #include #include #include #include #include AbsZeroPoint::AbsZeroPoint(QString image, QWidget *parent) : QMainWindow(parent), startImage(image), ui(new Ui::AbsZeroPoint) { ui->setupUi(this); initEnvironment(thelidir, userdir); initGUI(); if (!startImage.isEmpty()) { ui->zpImageLineEdit->setText(startImage); } performingStartup = false; connect(this, &AbsZeroPoint::messageAvailable, this, &AbsZeroPoint::displayMessage); connect(this, &AbsZeroPoint::readyForPlotting, this, &AbsZeroPoint::buildAbsPhot); // connect(this, &AbsZeroPoint::progressUpdate, this, &AbsZeroPoint::progressUpdateReceived); // connect(this, &AbsZeroPoint::resetProgressBar, this, &AbsZeroPoint::resetProgressBarReceived); } void AbsZeroPoint::closeEvent(QCloseEvent *event) { emit abszpClosed(); event->accept(); } AbsZeroPoint::~AbsZeroPoint() { delete absPhot; absPhot = nullptr; delete ui; } void AbsZeroPoint::displayMessage(QString message, QString type) { if (type == "error") ui->zpPlainTextEdit->appendHtml(""+message+""); else if (type == "info") ui->zpPlainTextEdit->appendHtml(""+message+""); else ui->zpPlainTextEdit->appendHtml(message); } void AbsZeroPoint::initGUI() { clearText(); // Fill in defaults on_zpRefcatComboBox_currentTextChanged("ATLAS-REFCAT2"); on_zpFilterComboBox_currentTextChanged("g"); defaults_if_empty(); // Crashes the GUI upon launch // ui->topDockWidget->titleBarWidget()->setFixedHeight(1); // Connections // For the GUI connect(ui->zpSaturationLineEdit, &QLineEdit::textChanged, this, &AbsZeroPoint::validate); connect(ui->zpPhoterrorLineEdit, &QLineEdit::textChanged, this, &AbsZeroPoint::validate); connect(ui->zpApertureLineEdit, &QLineEdit::textChanged, this, &AbsZeroPoint::validate); // For a mouse-click in the plot connect(ui->zpPlot, &QCustomPlot::plottableClick, this, &AbsZeroPoint::showData); // Deactivate UKIDSS for the time being // very inhomogeneous sky coverage in various epochs const QStandardItemModel* model = dynamic_cast< QStandardItemModel * >( ui->zpRefcatComboBox->model() ); model->item(7,0)->setEnabled(false); // Provide a roughly log range of apertures ui->zpApertureLineEdit->setText("10,15,20,25,30,40,50,75,100"); // Initialize the plot ui->zpPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); ui->zpPlot->plotLayout()->clear(); // clear default axis rect so we can start from scratch setWindowIcon(QIcon(":/icons/abszp.png")); loadPreferences(); } // UNUSED slot void AbsZeroPoint::updateVerbosity(int verbosityLevel) { verbosity = verbosityLevel; } void AbsZeroPoint::clearText() { QFont notoFont("Noto Sans", 10, QFont::Normal); ui->zpHeaderLabel->setText("System output"); ui->zpPlainTextEdit->clear(); ui->zpPlainTextEdit->setFont(notoFont); } void AbsZeroPoint::validate() { // Validators QRegExp rfloat( "[0-9]*[.]{0,1}[0-9]+" ); QValidator* validator_float = new QRegExpValidator(rfloat, this); QRegExp rintcomma( "[0-9, ]+" ); QValidator* validator_intcomma = new QRegExpValidator(rintcomma, this); QRegExp rint( "^[-]{0,1}[0-9]+" ); QValidator* validator_int = new QRegExpValidator(rint, this); ui->zpSaturationLineEdit->setValidator(validator_float); ui->zpPhoterrorLineEdit->setValidator(validator_float); ui->zpApertureLineEdit->setValidator(validator_intcomma); ui->zpDTLineEdit->setValidator(validator_float); ui->zpDMINLineEdit->setValidator(validator_int); } void AbsZeroPoint::defaults_if_empty() { if (ui->zpPhoterrorLineEdit->text().isEmpty()) ui->zpPhoterrorLineEdit->setText("0.05"); if (ui->zpSaturationLineEdit->text().isEmpty()) ui->zpSaturationLineEdit->setText("100"); if (ui->zpApertureLineEdit->text().isEmpty()) ui->zpApertureLineEdit->setText("20"); } void AbsZeroPoint::loadPreferences() { QSettings settings("THELI", "PREFERENCES"); maxCPU = settings.value("prefCPUSpinBox").toInt(); verbosity = settings.value("prefVerbosityComboBox").toInt(); } void AbsZeroPoint::on_startPushButton_clicked() { if (ui->zpImageLineEdit->text().isEmpty()) { QMessageBox::information(this, tr("Missing image."), tr("You have not specified an image to be calibrated."), QMessageBox::Ok); return; } on_zpClearPushButton_clicked(); absPhot->clear(); plot(); QTest::qWait(50); // Launch the thread ui->startPushButton->setText("Running ..."); ui->startPushButton->setDisabled(true); ui->zpColorComboBox->setDisabled(true); ui->zpFilterComboBox->setDisabled(true); ui->zpRefcatComboBox->setDisabled(true); workerThread = new QThread(); abszpWorker = new AbszpWorker(this); //workerInit = true; //workerThreadInit = true; abszpWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, abszpWorker, &AbszpWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(abszpWorker, &AbszpWorker::finished, this, &AbsZeroPoint::finishedCalculations); connect(abszpWorker, &AbszpWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(abszpWorker, &AbszpWorker::finished, abszpWorker, &QObject::deleteLater, Qt::DirectConnection); connect(abszpWorker, &AbszpWorker::messageAvailable, this, &AbsZeroPoint::displayMessage); workerThread->start(); } void AbsZeroPoint::criticalReceived() { emit finished(); } void AbsZeroPoint::updateSaturationValue(float value) { // use 90% of the highest measured value as a limit ui->zpSaturationLineEdit->setText(QString::number(0.9*value, 'f', 2)); } // Running in separate thread! // Here is where the actual work happens void AbsZeroPoint::taskInternalAbszeropoint() { myImage = new MyImage(ui->zpImageLineEdit->text(), QVector(), &verbosity); connect(myImage, &MyImage::messageAvailable, this, &AbsZeroPoint::displayMessage); connect(myImage, &MyImage::critical, this, &AbsZeroPoint::criticalReceived); myImage->globalMaskAvailable = false; myImage->maxCPU = maxCPU; myImage->loadHeader(); bool successQuery = true; bool successDetection = true; // executing catalog query and source detection in parallel #pragma omp parallel sections { #pragma omp section { emit messageAvailable("Querying " + ui->zpRefcatComboBox->currentText() + " ...", "ignore"); queryRefCat(); if (numRefSources == 0) { emit messageAvailable("AbsZP: Aborting, could not find any reference sources.", "error"); emit finished(); successQuery = false; } } #pragma omp section { emit messageAvailable("Detecting objects in image ...", "ignore"); QString DT = ui->zpDTLineEdit->text(); QString DMIN = ui->zpDMINLineEdit->text(); if (DT.isEmpty()) { DT = "10"; ui->zpDTLineEdit->setText("10"); } if (DMIN.isEmpty()) { DMIN = "10"; ui->zpDMINLineEdit->setText("10"); } // Collect apertures and pass them on QString ap = ui->zpApertureLineEdit->text(); ap = ap.replace(","," ").simplified(); QStringList apList = ap.split(" "); QVector apertures; for (auto &val : apList) { apertures << val.toFloat(); } myImage->apertures = apertures; // Detect objects myImage->readImage(ui->zpImageLineEdit->text()); if (!myImage->successProcessing) successDetection = false; myImage->readWeight(); myImage->successProcessing = true; myImage->apertures = apertures; myImage->backgroundModel(100, "interpolate"); myImage->segmentImage(DT, DMIN, true, false); long ngood = 0; for (auto &it : myImage->objectList) if (it->FLAGS == 0) ++ngood; emit messageAvailable(QString::number(myImage->objectList.length()) + " sources detected, "+QString::number(ngood) + " selected", "info"); } } if (!successDetection || !successQuery) return; emit messageAvailable("Matching objects with reference sources ...", "ignore"); refDat.clear(); objDat.clear(); // DEC comes first in the catalogs, because the matching alg sorts the vectors for DEC for (auto &object : myImage->objectList) { QVector objdata; if (object->FLAGS == 0) { objdata << object->DELTA_J2000 << object->ALPHA_J2000 << object->MAG_AUTO << object->MAGERR_AUTO << object->MAG_APER << object->MAGERR_APER; objDat.append(objdata); // qDebug() << qSetRealNumberPrecision(12) << object->ALPHA_J2000 << object->DELTA_J2000; } } // Estimate the matching tolerance myImage->estimateMatchingTolerance(); // qDebug() << "matching tolerance: " << myImage->matchingTolerance; // qDebug() << " " ; // spacer between object and reference catalog output // Iterate the matching once to get a sensible upper limit for the refcat download // (and thus a cleaner process in extreme cases where the refcat is MUCH deeper than the image) refCatUpperMagLimit = 40.; int multiple1 = 0; int multiple2 = 0; int loop = 0; while (loop <= 1) { // Collect suitable reference sources refDat.clear(); for (int i=0; i refdata; // only propagate reference sources inside the image area and brighter than the upper mag limit if (myImage->containsRaDec(raRefCat[i], deRefCat[i]) && mag1RefCat[i] < refCatUpperMagLimit) { refdata << deRefCat[i] << raRefCat[i] << mag1RefCat[i] << mag2RefCat[i] << mag1errRefCat[i] << mag2errRefCat[i]; refDat.append(refdata); } // qDebug() << qSetRealNumberPrecision(12) << raRefCat[i] << deRefCat[i]; } // Now do the matching multiple1 = 0; multiple2 = 0; matched.clear(); // Otherwise, multiple runs will append to previous data if (ui->zpRefcatComboBox->currentText().contains("2MASS")) { // simple way to accomodate accumulated proper motions for 2MASS (adding 1" matching radius) match2D_refcoords(objDat, refDat, matched, myImage->matchingTolerance + 1./3600., multiple1, multiple2, maxCPU); } else { match2D_refcoords(objDat, refDat, matched, myImage->matchingTolerance, multiple1, multiple2, maxCPU); } // Update upper refcat mag limit and repeat once refCatUpperMagLimit = getFirstZPestimate(); // qDebug() << "upper limit:" << refCatUpperMagLimit << refDat.length(); ++loop; } // debugging: output catalogs QFile outcat_detected(myImage->path+"/detected.cat"); QFile outcat_downloaded(myImage->path+"/downloaded.cat"); QTextStream stream_detected(&outcat_detected); QTextStream stream_downloaded(&outcat_downloaded); outcat_detected.open(QIODevice::WriteOnly); outcat_downloaded.open(QIODevice::WriteOnly); long i = 0; for (auto &it : raRefCat) { stream_downloaded << QString::number(it, 'f', 9) << " " << QString::number(deRefCat[i], 'f', 9) << " " << QString::number(mag1RefCat[i], 'f', 3) << "\n"; ++i; } outcat_downloaded.close(); outcat_downloaded.setPermissions(QFile::ReadUser | QFile::WriteUser); for (auto &it : objDat) { stream_detected << QString::number(it[1], 'f', 9) << " " << QString::number(it[0], 'f', 9) << " " << QString::number(it[2], 'f', 3) << "\n"; } outcat_detected.close(); outcat_detected.setPermissions(QFile::ReadUser | QFile::WriteUser); if (matched.length() == 0) { emit messageAvailable("No matches found!", "error"); emit finished(); return; } else { emit messageAvailable(QString::number(matched.length()) + " clean matches found.", "ignore"); // for (auto &it : matched) qDebug() << qSetRealNumberPrecision(10) << it[0] << it[1]; } if (multiple1 > 1) emit messageAvailable("Multiply matched objects (ignored): " + QString::number(multiple1), "ignore"); if (multiple2 > 1) emit messageAvailable("Multiply matched reference sources (ignored): " + QString::number(multiple2), "ignore"); // The plotting makes changes to the GUI, and therefore has been done from within the main thread! emit readyForPlotting(); // update the catalog display if iview is open writeAbsPhotRefcat(); if (iViewOpen) on_showAbsphotPushButton_clicked(); getFirstZPestimate(); } double AbsZeroPoint::getFirstZPestimate() { // if the reference catalog is much deeper than the image, we should apply a magnitude cut before matching. // Hence, do a rough ZP estimate (without color term) and then rematch QVector magdiff; QVector magDetected; magdiff.resize(matched.length()); magDetected.resize(matched.length()); long i = 0; for (auto &it : matched) { magdiff[i] = it[2] - it[6]; magDetected[i] = it[6]; ++i; } double medianZP = straightMedian_T(magdiff); // double rms = madMask_T(magdiff); // return the faintest detected magnitude estimate, and add 0.3 mag as a margin return maxVec_T(magDetected) + medianZP + 0.3; } void AbsZeroPoint::queryRefCat() { Query *query = new Query(&verbosity); query->photomDir = myImage->path; query->photomImageName = myImage->name; query->refcatName = ui->zpRefcatComboBox->currentText(); QString filter1 = ui->zpFilterComboBox->currentText(); QString filter2 = ui->zpColorComboBox->currentText().remove('-').remove(filter1); query->refcatFilter1 = filter1; query->refcatFilter2 = filter2; query->doPhotomQueryFromWeb(); raRefCat.swap(query->ra_out); deRefCat.swap(query->de_out); mag1RefCat.swap(query->mag1_out); mag2RefCat.swap(query->mag2_out); mag1errRefCat.swap(query->mag1err_out); mag2errRefCat.swap(query->mag2err_out); numRefSources = query->numSources; // Conversion to AB mag if not yet done // Convert APASS VEGA mags to AB mags // http://www.astronomy.ohio-state.edu/~martini/usefuldata.html if (query->refcatName.contains("APASS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "B") corr1 = -0.09; else if (filter1 == "V") corr1 = 0.02; if (filter2 == "B") corr2 = -0.09; else if (filter2 == "V") corr2 = 0.02; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } // Convert 2MASS VEGA mags to AB mags // http://www.astronomy.ohio-state.edu/~martini/usefuldata.html if (query->refcatName.contains("2MASS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "J") corr1 = 0.91; else if (filter1 == "H") corr1 = 1.39; else if (filter1 == "Ks") corr1 = 1.85; if (filter2 == "J") corr2 = 0.91; else if (filter2 == "H") corr2 = 1.39; else if (filter2 == "Ks") corr2 = 1.85; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } // Convert VHS VEGA mags to AB mags // Pons et al. 2019, MNRAS, 484, 5142: https://academic.oup.com/mnras/article/484/4/5142/5303744 // http://www.astronomy.ohio-state.edu/~martini/usefuldata.html (for Y-band) if (query->refcatName.contains("VHS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "Y") corr1 = 0.634; else if (filter1 == "J") corr1 = 0.937; else if (filter1 == "H") corr1 = 1.384; else if (filter1 == "Ks") corr1 = 1.839; if (filter2 == "Y") corr2 = 0.634; else if (filter2 == "J") corr2 = 0.937; else if (filter2 == "H") corr2 = 1.384; else if (filter2 == "Ks") corr2 = 1.839; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } // Convert UKIDSS VEGA mags to AB mags // Hewett et al. 2006, MNRAS, 367, 454 if (query->refcatName.contains("UKIDSS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "J") corr1 = 0.938; else if (filter1 == "H") corr1 = 1.379; else if (filter1 == "Ks") corr1 = 1.900; if (filter2 == "J") corr2 = 0.938; else if (filter2 == "H") corr2 = 1.379; else if (filter2 == "Ks") corr2 = 1.900; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } delete query; query = nullptr; // Count how many inside image long ngood = 0; for (int i=0; icontainsRaDec(raRefCat[i], deRefCat[i])) ++ngood; } emit messageAvailable(QString::number(numRefSources) + " reference sources found, "+QString::number(ngood)+" inside image", "info"); emit messageAvailable("Please wait for object detection to finish ...", "ignore"); } void AbsZeroPoint::writeAbsPhotRefcat() { // The iView catalog (ASCII) QString outpath = myImage->path; QDir outdir(outpath); if (!outdir.exists()) { emit messageAvailable(QString(__func__) + " : " + myImage->path +" directory does not exist to write AbsPhot reference catalogs", "error"); emit criticalReceived(); return; } QFile outcat_iview_matched(outpath+"/ABSPHOT_sources_matched.iview"); QTextStream stream_iview_matched(&outcat_iview_matched); if( !outcat_iview_matched.open(QIODevice::WriteOnly)) { emit messageAvailable(QString(__func__) + " : ERROR writing "+outpath+outcat_iview_matched.fileName()+" : "+outcat_iview_matched.errorString(), "error"); emit criticalReceived(); return; } QFile outcat_iview_down(outpath+"/ABSPHOT_sources_downloaded.iview"); QTextStream stream_iview_down(&outcat_iview_down); if( !outcat_iview_down.open(QIODevice::WriteOnly)) { emit messageAvailable(QString(__func__) + " : ERROR writing "+outpath+outcat_iview_down.fileName()+" : "+outcat_iview_down.errorString(), "error"); emit criticalReceived(); return; } // Write downloaded iView catalog for (auto &it : refDat) { stream_iview_down << QString::number(it[1], 'f', 9) << " " << QString::number(it[0], 'f', 9) << " " << QString::number(it[2], 'f', 3) << "\n"; } outcat_iview_down.close(); outcat_iview_down.setPermissions(QFile::ReadUser | QFile::WriteUser); // Write matched iView catalog for (auto &it : matched) { stream_iview_matched << QString::number(it[1], 'f', 9) << " " << QString::number(it[0], 'f', 9) << " " << QString::number(it[2], 'f', 3) << "\n"; } outcat_iview_matched.close(); outcat_iview_matched.setPermissions(QFile::ReadUser | QFile::WriteUser); } void AbsZeroPoint::buildAbsPhot() { QString apertures = ui->zpApertureLineEdit->text(); apertures = apertures.replace(",", " "); apertures = apertures.simplified(); QStringList aperList = apertures.split(" "); int numAper = aperList.length(); absPhot->numAper += numAper; for (int i=0; iqv_apertures.append(ap.toDouble()); } // We need to know which color term was used so that we can // calculate the color correctly absPhot->color = ui->zpColorComboBox->currentText(); absPhot->filter = ui->zpFilterComboBox->currentText(); QString colorfilter = ui->zpColorComboBox->currentText(); absPhot->colorfilter = colorfilter.remove("-").remove(ui->zpFilterComboBox->currentText()); // Each matched entry contains // RA DEC Mag1REF Mag2REF Mag1ERR_REF Mag2ERR_REF MAG_AUTO MAGERR_AUTO MAG_APER(vector) MAGERR_APER(vector) // Object magnitudes are calculated for a fiducial ZP = 0, and need to be exposure time normalized // CHECK: this would go wrong if someone calibrates an image that is not normalized to one second! // float normalization = 2.5*log10(myImage->exptime); float normalization = 0.; // additive, in mag-space for (auto &match : matched) { absPhot->qv_RA.append(match[1]); absPhot->qv_DEC.append(match[0]); absPhot->qv_mag1ref.append(match[2]); absPhot->qv_mag2ref.append(match[3]); absPhot->qv_mag1errref.append(match[4]); absPhot->qv_mag2errref.append(match[5]); absPhot->qv_magauto.append(match[6] + normalization); absPhot->qv_magerrauto.append(match[7]); QVector dummy1; QVector dummy2; for (int i=0; iqv_magaper.append(dummy1); absPhot->qv_magerraper.append(dummy2); absPhot->qv_ManualMask.append(false); absPhot->numObj += 1; } // Calculations absPhot->initialized = true; // Individual color indices absPhot->getColor(); // Calculate the ZP dependence on the color term // absPhot->regressionLinfit(absPhot->slope, absPhot->cutoff); if (!doColortermFit()) return; // Calculate the ZPs per aperture absPhot->getZP(); plot(); emit finished(); } void AbsZeroPoint::finishedCalculations() { ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); ui->zpColorComboBox->setEnabled(true); ui->zpFilterComboBox->setEnabled(true); ui->zpRefcatComboBox->setEnabled(true); } void AbsZeroPoint::on_abortPushButton_clicked() { if (!ui->startPushButton->isEnabled()) { workerThread->quit(); workerThread->wait(); finishedCalculations(); } } void AbsZeroPoint::on_zpLoadPushButton_clicked() { QString currentFileName = QFileDialog::getOpenFileName(this, tr("Select astrometrically calibrated image"), QDir::homePath(), tr("Images (*.fits *.fit *.fts *.FIT *.FITS *.FTS);; All (*.*)")); ui->zpImageLineEdit->setText(currentFileName); paintPathLineEdit(ui->zpImageLineEdit, currentFileName, "file"); } void AbsZeroPoint::on_zpImageLineEdit_textChanged(const QString &arg1) { paintPathLineEdit(ui->zpImageLineEdit, arg1, "file"); fileInfo.setFile(arg1); // Clear the plot on_zpClearPushButton_clicked(); } void AbsZeroPoint::on_zpRefcatComboBox_currentTextChanged(const QString &arg1) { if (arg1.contains("ATLAS-REFCAT2")) { fill_combobox(ui->zpFilterComboBox, "g r i z"); fill_combobox(ui->zpColorComboBox, "g-r g-i r-i i-z"); } if (arg1.contains("PANSTARRS")) { fill_combobox(ui->zpFilterComboBox, "g r i z y"); fill_combobox(ui->zpColorComboBox, "g-r g-i r-i i-z z-y"); } else if (arg1.contains("SDSS")) { fill_combobox(ui->zpFilterComboBox, "u g r i z"); fill_combobox(ui->zpColorComboBox, "u-g g-r g-i r-i i-z"); } else if (arg1.contains("SKYMAPPER")) { fill_combobox(ui->zpFilterComboBox, "u v g r i z"); fill_combobox(ui->zpColorComboBox, "u-g u-v g-r v-r g-i v-i r-i i-z"); } else if (arg1.contains("APASS")) { fill_combobox(ui->zpFilterComboBox, "B V g r i"); fill_combobox(ui->zpColorComboBox, "B-V g-r g-i r-i"); } else if (arg1.contains("2MASS")) { fill_combobox(ui->zpFilterComboBox, "J H Ks"); fill_combobox(ui->zpColorComboBox, "J-H J-Ks H-Ks"); } else if (arg1.contains("VHS")) { fill_combobox(ui->zpFilterComboBox, "Y J H Ks"); fill_combobox(ui->zpColorComboBox, "Y-J J-H J-Ks H-Ks"); } // currently not implemented because of very patchy photometric coverage else if (arg1.contains("UKIDSS")) { fill_combobox(ui->zpFilterComboBox, "Y J H K"); fill_combobox(ui->zpFilterComboBox, "Y-J J-H J-K H-K"); } on_zpFilterComboBox_currentTextChanged(ui->zpFilterComboBox->currentText()); } void AbsZeroPoint::on_zpClearPushButton_clicked() { if (absPhot->numObj > 0) { clearText(); absPhot->clear(); ui->zpPlot->clearGraphs(); ui->zpPlot->clearItems(); ui->zpPlot->plotLayout()->clear(); plot(); } } void AbsZeroPoint::on_zpExportPushButton_clicked() { if (absPhot->numObj == 0) return; QString path = fileInfo.absolutePath(); QString base = fileInfo.completeBaseName(); /* PDSF output is extremely slow, freezes the GUI for 1 minute; * deactivated for the time being QString saveFileName = QFileDialog::getSaveFileName(this, tr("Save Image"), base+".png", tr("Graphics file (*.png *.pdf)")); if ( saveFileName.isEmpty() ) return; QFileInfo graphicsInfo(saveFileName); if (! (graphicsInfo.suffix() == "png" || graphicsInfo.suffix() == "pdf")) { QMessageBox::information(this, tr("Invalid graphics type"), tr("Only graphics formats .png and .pdf are allowed."), QMessageBox::Ok); return; } if (graphicsInfo.suffix() == "pdf") ui->zpPlot->savePdf(saveFileName); else if (graphicsInfo.suffix() == "png") ui->zpPlot->savePng(saveFileName); */ QString saveFileName = QFileDialog::getSaveFileName(this, tr("Save .png Image"), path+"/"+base+"_ZPcurve.png", tr("Graphics file (*.png)")); if ( saveFileName.isEmpty() ) return; QFileInfo graphicsInfo(saveFileName); if (graphicsInfo.suffix() != "png") { QMessageBox::information(this, tr("Invalid graphics type"), tr("Only .png format is currently allowed."), QMessageBox::Ok); return; } else { ui->zpPlot->savePng(saveFileName,0,0,1.25); } } void AbsZeroPoint::on_zpFilterComboBox_currentTextChanged(const QString &arg1) { // Mask color terms that do not contain the primary filter: const QStandardItemModel* model = dynamic_cast< QStandardItemModel * >( ui->zpColorComboBox->model() ); int length = ui->zpColorComboBox->count(); bool updated = false; for (int i=0; iitem(i,0)->text(); if (!(model->item(i,0)->text()).contains(arg1)) { model->item(i,0)->setEnabled(false); } else { model->item(i,0)->setEnabled(true); if (!updated) { ui->zpColorComboBox->setCurrentIndex(i); updated = true; } } } on_zpClearPushButton_clicked(); } /* void AbsZeroPoint::endScript() { // Process the result table QString image = ui->zpImageLineEdit->text(); QFileInfo fileInfo(image); QString catalogName = fileInfo.path()+"/"+fileInfo.completeBaseName()+".absphot.cat"; // The file contains Ra Dec Mag1REF Mag2REF MagAUTO MagerrAUTO MagAPER(vector) QString apertures = ui->zpApertureLineEdit->text(); apertures = apertures.replace(",", " "); apertures = apertures.simplified(); QStringList aperList = apertures.split(" "); int numAper = aperList.length(); absPhot->numAper += numAper; for (int i=0; iqv_apertures.append(ap.toDouble()); } // We need to know which color term was used so that we can // calculate the color correctly absPhot->color = ui->zpColorComboBox->currentText(); absPhot->filter = ui->zpFilterComboBox->currentText(); QString colorfilter = ui->zpColorComboBox->currentText(); absPhot->colorfilter = colorfilter.remove("-").remove(ui->zpFilterComboBox->currentText()); QFile catalog(catalogName); QString line; QStringList lineList; // Read all the magnitudes into the absPhot class if ( catalog.open(QIODevice::ReadOnly)) { QTextStream stream( &catalog ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); // skip header lines if (line.contains("#")) continue; lineList = line.split(" "); absPhot->qv_RA.append(lineList.at(0).toDouble()); absPhot->qv_DEC.append(lineList.at(1).toDouble()); absPhot->qv_mag1ref.append(lineList.at(2).toDouble()); absPhot->qv_mag1errref.append(lineList.at(3).toDouble()); absPhot->qv_mag2ref.append(lineList.at(4).toDouble()); absPhot->qv_mag2errref.append(lineList.at(5).toDouble()); absPhot->qv_magauto.append(lineList.at(6).toDouble()); absPhot->qv_magerrauto.append(lineList.at(7).toDouble()); QVector dummy = QVector(); for (int i=0; iqv_magaper.append(dummy); absPhot->qv_ManualMask.append(false); absPhot->numObj += 1; } catalog.close(); } // Calculations absPhot->initialized = true; // Individual color indices absPhot->getColor(); // Calculate the ZP dependence on the color term // absPhot->regressionLinfit(absPhot->slope, absPhot->cutoff); if (!doColortermFit()) return; // Calculate the ZPs per aperture absPhot->getZP(); plot(); ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); ui->zpColorComboBox->setEnabled(true); ui->zpFilterComboBox->setEnabled(true); ui->zpRefcatComboBox->setEnabled(true); } */ // void AbsZeroPoint::showData(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) void AbsZeroPoint::showData(QCPAbstractPlottable *plottable, int dataIndex) { if (plottable->parentLayerable()->objectName() == "aperRect") { absPhot->ZPSelected = QString::number(absPhot->qv_ZP[dataIndex], 'f', 3); absPhot->ZPerrSelected = QString::number(absPhot->qv_ZPerr[dataIndex], 'f', 3); absPhot->Color1Selected = QString::number(absPhot->fitParams[1], 'f', 4); absPhot->Color2Selected = QString::number(absPhot->fitParams[2], 'f', 4); absPhot->Color3Selected = QString::number(absPhot->fitParams[3], 'f', 4); absPhot->ColorErr1Selected = QString::number(absPhot->fitParamsErr[1], 'f', 4); absPhot->ColorErr2Selected = QString::number(absPhot->fitParamsErr[2], 'f', 4); absPhot->ColorErr3Selected = QString::number(absPhot->fitParamsErr[3], 'f', 4); updateCoaddHeader(); } /* * * NOT WORKING! for some reason dataIndex does not select the object clicked, but some random other object. * It appears that data points plotted start with index 0 at left and have highest index at right. */ else if (plottable->parentLayerable()->objectName() == "colorRect") { // Select only clicks on data points // if (QCPGraph *graph = qobject_cast(plottable)) { // set or unset the flag for this data point // if (absPhot->qv_ManualFlag[dataIndex]) absPhot->qv_ManualFlag[dataIndex] = false; // else absPhot->qv_ManualFlag[dataIndex] = true; // qDebug() << qSetRealNumberPrecision(12) << dataIndex << "AA" << absPhot->qv_colorIndividual[dataIndex] << absPhot->qv_ZPIndividual[dataIndex] << absPhot->qv_RA[dataIndex] << absPhot->qv_DEC[dataIndex]; // absPhot->regression(absPhot->slope, absPhot->cutoff); // absPhot->getZP(); // plot(); // } } } void AbsZeroPoint::plot() { if (absPhot->numAper == 0) { ui->zpPlot->replot(); ui->zpPlot->update(); return; } ui->zpPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); ui->zpPlot->plotLayout()->clear(); // clear default axis rect so we can start from scratch // The axes box for the ZP Growth curve QCPAxisRect *AxisRectAper = new QCPAxisRect(ui->zpPlot); AxisRectAper->setObjectName("aperRect"); AxisRectAper->setupFullAxesBox(true); AxisRectAper->axis(QCPAxis::atBottom)->setLabel("Aperture diameter [pixel]"); AxisRectAper->axis(QCPAxis::atLeft)->setLabel("ZP "+ui->zpFilterComboBox->currentText()+" [ mag ]"); AxisRectAper->axis(QCPAxis::atBottom)->setRange(0,100); AxisRectAper->axis(QCPAxis::atLeft)->setRange(24,28); // The axes box for the ZP color dependence QCPAxisRect *AxisRectColor = new QCPAxisRect(ui->zpPlot); AxisRectColor->setObjectName("colorRect"); AxisRectColor->setupFullAxesBox(true); AxisRectColor->axis(QCPAxis::atBottom)->setLabel(ui->zpColorComboBox->currentText()+" [ mag ]"); AxisRectColor->axis(QCPAxis::atLeft)->setLabel("Ref - Inst [ mag ]"); AxisRectColor->axis(QCPAxis::atBottom)->setRange(-1,3); AxisRectColor->axis(QCPAxis::atLeft)->setRange(24,28); // Space for the title bar QString imagename = fileInfo.fileName(); QCPTextElement *title = new QCPTextElement(ui->zpPlot, imagename, QFont("sans", 12)); ui->zpPlot->plotLayout()->addElement(0, 0, title); ui->zpPlot->plotLayout()->addElement(1, 0, AxisRectAper); ui->zpPlot->plotLayout()->addElement(2, 0, AxisRectColor); /* // The Auto mag Rectangle in the growth curve. Must plot first, so other clickable data points end up on top QCPItemRect *magAuto = new QCPItemRect(ui->zpPlot); magAuto->topLeft->setType(QCPItemPosition::PositionType::ptPlotCoords); magAuto->bottomRight->setType(QCPItemPosition::PositionType::ptPlotCoords); magAuto->topLeft->setCoords(QPointF(minVec_T(absPhot->qv_apertures), absPhot->ZPauto + absPhot->ZPautoerr)); magAuto->bottomRight->setCoords(QPointF(maxVec_T(absPhot->qv_apertures), absPhot->ZPauto - absPhot->ZPautoerr)); magAuto->setClipToAxisRect(true); magAuto->setPen(QPen(Qt::red)); magAuto->setSelectable(false); QBrush boxBrush(QColor(255, 0, 0, 100)); magAuto->setBrush(boxBrush); double maxAp = maxVec_T(absPhot->qv_apertures); double minAp = minVec_T(absPhot->qv_apertures); // Add label for magAuto QCPItemText *magAutoText = new QCPItemText(ui->zpPlot); magAutoText->position->setType(QCPItemPosition::ptPlotCoords); magAutoText->setPositionAlignment(Qt::AlignLeft|Qt::AlignCenter); magAutoText->position->setCoords(0.5*(minAp+maxAp), absPhot->ZPauto); magAutoText->setSelectable(false); magAutoText->setText("MAG_AUTO"); magAutoText->setTextAlignment(Qt::AlignLeft); magAutoText->setFont(QFont(font().family(), 9)); magAutoText->setPadding(QMargins(4, 0, 4, 0)); magAutoText->setPen(QPen(Qt::black)); */ // The graph for the ZP growth curve QCPGraph *aperZPGraph = ui->zpPlot->addGraph(AxisRectAper->axis(QCPAxis::atBottom), AxisRectAper->axis(QCPAxis::atLeft)); aperZPGraph->setSelectable(QCP::stSingleData); aperZPGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(Qt::blue), QBrush(Qt::blue), 6)); aperZPGraph->setLineStyle(QCPGraph::lsLine); aperZPGraph->setData(absPhot->qv_apertures,absPhot->qv_ZP); QCPSelectionDecorator *decorator = new QCPSelectionDecorator(); QCPScatterStyle scatterstyle(QCPScatterStyle::ScatterShape::ssSquare, QColor("#009988"), QColor("#009988"), 12); decorator->setPen(QPen(QColor("#000000"))); decorator->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); aperZPGraph->setSelectionDecorator(decorator); double xmin = minVec_T(absPhot->qv_apertures); double xmax = maxVec_T(absPhot->qv_apertures); double ymin = minVec_T(absPhot->qv_ZP) - absPhot->qv_ZPerr[0]; double ymax = maxVec_T(absPhot->qv_ZP) + absPhot->qv_ZPerr[absPhot->qv_ZPerr.size()-1]; double dx = (xmax - xmin) * 0.05; double dy = (ymax - ymin) * 0.05; aperZPGraph->keyAxis()->setRange(xmin-dx, xmax+dx); aperZPGraph->valueAxis()->setRange(ymin-dy, ymax+dy); // Error bars QCPErrorBars *errorBarsZP = new QCPErrorBars(aperZPGraph->keyAxis(), aperZPGraph->valueAxis()); errorBarsZP->setDataPlottable(aperZPGraph); errorBarsZP->setSelectable(QCP::SelectionType::stNone); errorBarsZP->setData(absPhot->qv_ZPerr); // The graph for the color dependence QCPGraph *colorZPGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorZPGraph->setSelectable(QCP::stSingleData); // colorZPGraph->setSelectable(QCP::SelectionType::stNone); colorZPGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(QColor("#096169")), QBrush(QColor("#096169")), 6)); colorZPGraph->setLineStyle(QCPGraph::lsNone); colorZPGraph->rescaleKeyAxis(); colorZPGraph->rescaleValueAxis(); colorZPGraph->setData(absPhot->qv_colorIndividual,absPhot->qv_ZPIndividual); // vertical error bars QCPErrorBars *errorValueBarsColor = new QCPErrorBars(colorZPGraph->keyAxis(), colorZPGraph->valueAxis()); errorValueBarsColor->setDataPlottable(colorZPGraph); errorValueBarsColor->setSelectable(QCP::SelectionType::stNone); errorValueBarsColor->setData(absPhot->qv_ZPerrIndividual); errorValueBarsColor->setPen(QPen(QColor("#1eb7ce"))); errorValueBarsColor->setErrorType(QCPErrorBars::etValueError); // horizontal error bars QCPErrorBars *errorKeyBarsColor = new QCPErrorBars(colorZPGraph->keyAxis(), colorZPGraph->valueAxis()); errorKeyBarsColor->setDataPlottable(colorZPGraph); errorKeyBarsColor->setSelectable(QCP::SelectionType::stNone); errorKeyBarsColor->setData(absPhot->qv_colorErrIndividual); errorKeyBarsColor->setPen(QPen(QColor("#1eb7ce"))); errorKeyBarsColor->setErrorType(QCPErrorBars::etKeyError); xmin = minVec_T(absPhot->qv_colorIndividual); xmax = maxVec_T(absPhot->qv_colorIndividual); ymin = minVec_T(absPhot->qv_ZPIndividual); ymax = maxVec_T(absPhot->qv_ZPIndividual); // we always want to see the origin: if (xmin > 0.) xmin = -0.1; dx = (xmax - xmin) * 0.08; dy = (ymax - ymin) * 0.08; colorZPGraph->keyAxis()->setRange(xmin-dx, xmax+dx); colorZPGraph->valueAxis()->setRange(ymin-dy, ymax+dy); // The graph for the color dependence outliers if (absPhot->num_outliers > 0) { QCPGraph *colorOutlierZPGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorOutlierZPGraph->setSelectable(QCP::SelectionType::stNone); colorOutlierZPGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCrossCircle, 12)); colorOutlierZPGraph->setPen(QPen(QColor(Qt::red))); colorOutlierZPGraph->setLineStyle(QCPGraph::lsNone); colorOutlierZPGraph->rescaleKeyAxis(); colorOutlierZPGraph->rescaleValueAxis(); colorOutlierZPGraph->setData(absPhot->qv_colorIndividualOutlier,absPhot->qv_ZPIndividualOutlier); } // Show LINEAR line fit to the color dependence /* QVector dataFit(2); dataFit[0].key = xmin - 0.5; dataFit[1].key = xmax + 0.5; dataFit[0].value = absPhot->cutoff + absPhot->slope * dataFit[0].key; dataFit[1].value = absPhot->cutoff + absPhot->slope * dataFit[1].key; QCPGraph *fitGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); fitGraph->data()->set(dataFit); fitGraph->setSelectable(QCP::stNone); fitGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black), QBrush(Qt::white), 6)); fitGraph->setPen(QPen(QColor(Qt::black), 2)); */ // Show GSL fit to the color dependence QVector dataFit; float step = (xmax - xmin + 2.*dx) / 100; // plot at 100 intervals for (int i=0; i<=100; ++i) { double xval = xmin - dx + i*step; double yval = 0.; for (int k=0; k<4; ++k) { // polynomial degree is hardcoded to three (higher order coeffs might be zero if a lower order was requested) yval += absPhot->fitParams[k]*pow(xval, double(k)); } QCPGraphData dataPoint(xval, yval); dataFit.append(dataPoint); } QCPGraph *fitGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); fitGraph->data()->set(dataFit); fitGraph->setSelectable(QCP::stNone); // fitGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black), QBrush(Qt::white), 6)); fitGraph->setPen(QPen(QColor(Qt::red), 2)); // The graph for the color dependence (replot because of cluttering by the error bars) QCPGraph *colorZPGraph2 = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorZPGraph2->setSelectable(QCP::SelectionType::stMultipleDataRanges); colorZPGraph2->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(QColor("#096169")), QBrush(QColor("#096169")), 6)); colorZPGraph2->setLineStyle(QCPGraph::lsNone); colorZPGraph2->rescaleKeyAxis(); colorZPGraph2->rescaleValueAxis(); colorZPGraph2->setData(absPhot->qv_colorIndividual,absPhot->qv_ZPIndividual); /* // The graph for manual outliers (if any) if (absPhot->num_ManualOutliers > 0) { QCPGraph *colorZPGraphManualOutlier = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorZPGraphManualOutlier->setSelectable(QCP::SelectionType::stMultipleDataRanges); colorZPGraphManualOutlier->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(QColor("#ff0000")), QBrush(QColor("#ff0000")), 9)); colorZPGraphManualOutlier->setLineStyle(QCPGraph::lsNone); colorZPGraphManualOutlier->rescaleKeyAxis(); colorZPGraphManualOutlier->rescaleValueAxis(); colorZPGraphManualOutlier->setData(absPhot->qv_colorManualOutlier,absPhot->qv_ZPManualOutlier); // void AbsZeroPoint::showData(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) } */ // Place data points in the topmost layer // QCPLayer *zpLayer = aperZPGraph->layer(); // ui->zpPlot->moveLayer(zpLayer,ui->zpPlot->layer("main")); // QCPLayer *colorLayer = colorZPGraph->layer(); // colorLayer->setMode(QCPLayer::lmBuffered); ui->zpPlot->replot(); ui->zpPlot->update(); } void AbsZeroPoint::on_actionClose_triggered() { emit abszpClosed(); this->close(); } bool AbsZeroPoint::doColortermFit() { /* int fitOrder = ui->zpFitOrderSpinBox->value(); if (!absPhot->regression(fitOrder)) { QMessageBox::information( this, "Ill-constrainend fit", "There are not enough photometric reference stars to perform a fit of order "+QString::number(fitOrder), QMessageBox::Ok); return false; } */ absPhot->regressionLinfit(); return true; } void AbsZeroPoint::on_zpFitOrderSpinBox_valueChanged(int arg1) { if (performingStartup) return; // This slot is triggered by the GUI setp when data are still unavailable if (!doColortermFit()) return; ui->zpPlot->clearGraphs(); ui->zpPlot->clearItems(); ui->zpPlot->plotLayout()->clear(); plot(); updateCoaddHeader(); } void AbsZeroPoint::updateCoaddHeader() { absPhot->Color1Selected = QString::number(absPhot->fitParams[1], 'f', 4); absPhot->Color2Selected = QString::number(absPhot->fitParams[2], 'f', 4); absPhot->Color3Selected = QString::number(absPhot->fitParams[3], 'f', 4); absPhot->ColorErr1Selected = QString::number(absPhot->fitParamsErr[1], 'f', 4); absPhot->ColorErr2Selected = QString::number(absPhot->fitParamsErr[2], 'f', 4); absPhot->ColorErr3Selected = QString::number(absPhot->fitParamsErr[3], 'f', 4); float fluxConv = 0.0; if (!absPhot->ZPSelected.isEmpty()) { fluxConv = 1.e6 * pow(10, -0.4 * (absPhot->ZPSelected.toFloat() - 8.90)); // Converting ZP to microJy } // The coadded FITS file fitsfile *fptr; int status = 0; QString name = ui->zpImageLineEdit->text(); fits_open_file(&fptr, name.toUtf8().data(), READWRITE, &status); fits_update_key_flt(fptr, "ZPD", absPhot->ZPSelected.toFloat(), 6, "Photometric ZP in ZPD_FILT", &status); fits_update_key_flt(fptr, "ZPD_ERR", absPhot->ZPerrSelected.toFloat(), 6, "Error of ZPD", &status); fits_update_key_str(fptr, "ZPD_FILT", ui->zpFilterComboBox->currentText().toUtf8().data(), "Filter for ZPD", &status); fits_update_key_flt(fptr, "ZPD_C1", absPhot->Color1Selected.toFloat(), 6, "Linear color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_C2", absPhot->Color2Selected.toFloat(), 6, "Quadratic color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_C3", absPhot->Color3Selected.toFloat(), 6, "Cubic color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_CER1", absPhot->ColorErr1Selected.toFloat(), 6, "Error linear color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_CER2", absPhot->ColorErr2Selected.toFloat(), 6, "Error quadratic color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_CER3", absPhot->ColorErr3Selected.toFloat(), 6, "Error cubic color term in ZPD_SURV", &status); fits_update_key_str(fptr, "ZPD_INDX", ui->zpColorComboBox->currentText().toUtf8().data(), "Color index in ZPD_SURV", &status); if (ui->zpRefcatComboBox->currentText().contains("2MASS")) { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Mag. system (converted from 2MASS VEGA mags)", &status); } else if (ui->zpRefcatComboBox->currentText().contains("UKIDSS")) { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Mag. system (converted from 2MASS UKIDSS mags)", &status); } else if (ui->zpRefcatComboBox->currentText().contains("APASS")) { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Mag. system (B and V VEGA mags converted to AB)", &status); } else { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Magnitude system", &status); } fits_update_key_str(fptr, "ZPD_SURV", ui->zpRefcatComboBox->currentText().toUtf8().data(), "Survey and filter system", &status); fits_update_key_flt(fptr, "FLUXCONV", fluxConv, 6, "Factor to convert image to microJansky", &status); fits_close_file(fptr, &status); ui->zpHeaderLabel->setText("FITS header entries were updated:"); ui->zpPlainTextEdit->clear(); if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); QString code = errorCodes->errorKeyMap.value(status); ui->zpPlainTextEdit->appendHtml("Cfitsio error while updating header: " + code + ""); } QFont notoFontMono("Noto Sans Mono CJK JP", 8, QFont::Normal); ui->zpPlainTextEdit->setFont(notoFontMono); ui->zpPlainTextEdit->appendHtml("ZPD     = "+absPhot->ZPSelected+""); ui->zpPlainTextEdit->appendHtml("ZPD_ERR = "+absPhot->ZPerrSelected+""); ui->zpPlainTextEdit->appendHtml("ZPD_FILT= '"+ui->zpFilterComboBox->currentText()+"'"); ui->zpPlainTextEdit->appendHtml("ZPD_C1  = "+absPhot->Color1Selected+""); ui->zpPlainTextEdit->appendHtml("ZPD_C2  = "+absPhot->Color2Selected+""); ui->zpPlainTextEdit->appendHtml("ZPD_C3  = "+absPhot->Color3Selected+""); ui->zpPlainTextEdit->appendHtml("ZPD_CER1= "+absPhot->ColorErr1Selected+""); ui->zpPlainTextEdit->appendHtml("ZPD_CER2= "+absPhot->ColorErr2Selected+""); ui->zpPlainTextEdit->appendHtml("ZPD_CER3= "+absPhot->ColorErr3Selected+""); ui->zpPlainTextEdit->appendHtml("ZPD_INDX= '"+ui->zpColorComboBox->currentText()+"'"); // CHECK: everytime we add new reference catalogs if (ui->zpRefcatComboBox->currentText().contains("2MASS")) { ui->zpPlainTextEdit->appendHtml("ZPD_SYST= 'ABmag' (converted from 2MASS VEGA mags)"); } else if (ui->zpRefcatComboBox->currentText().contains("UKIDSS")) { ui->zpPlainTextEdit->appendHtml("ZPD_SYST= 'ABmag' (converted from UKIDSS VEGA mags)"); } else if (ui->zpRefcatComboBox->currentText().contains("APASS")) { ui->zpPlainTextEdit->appendHtml("ZPD_SYST= 'ABmag' (B and V VEGA mags converted to AB mag)"); } else if (ui->zpRefcatComboBox->currentText().contains("VHS")) { ui->zpPlainTextEdit->appendHtml("ZPD_SYST= 'ABmag' (converted from VEGA mags)"); } else { ui->zpPlainTextEdit->appendHtml("ZPD_SYST= 'ABmag'"); } ui->zpPlainTextEdit->appendHtml("ZPD_SURV= '"+ui->zpRefcatComboBox->currentText()+"'"); ui->zpPlainTextEdit->appendHtml("FLUXCONV= "+QString::number(fluxConv, 'f', 4)+" (conversion factor to microJy)"); } void AbsZeroPoint::on_closePushButton_clicked() { emit abszpClosed(); this->close(); } void AbsZeroPoint::on_showAbsphotPushButton_clicked() { // TODO: show sources that are kept after the fit in yet another color if (!iViewOpen) { iView = new IView("FITSmonochrome", ui->zpImageLineEdit->text(), this); connect(iView, &IView::closed, this, &AbsZeroPoint::iViewClosed); connect(this, &AbsZeroPoint::updateAbsPhotPlot, iView, &IView::showAbsPhotReferences); iView->show(); iView->AbsPhotReferencePathName = myImage->path; iView->showAbsPhotReferences(true); iViewOpen = true; } else { iView->show(); iView->AbsPhotReferencePathName = myImage->path; emit updateAbsPhotPlot(true); } } void AbsZeroPoint::iViewClosed() { iViewOpen = false; } THELI-3.1.3/src/abszp/abszeropoint.h000066400000000000000000000073441417631501300171720ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef ABSZEROPOINT_H #define ABSZEROPOINT_H #include "../threading/abszpworker.h" #include "../qcustomplot.h" #include "../myimage/myimage.h" #include "../iview/iview.h" #include #include #include #include #include "absphot.h" class AbszpWorker; namespace Ui { class AbsZeroPoint; } class AbsZeroPoint : public QMainWindow { Q_OBJECT public: explicit AbsZeroPoint(QString image, QWidget *parent = nullptr); ~AbsZeroPoint(); void plot(); QString startImage = ""; AbsPhot *absPhot = new AbsPhot(); QThread *workerThread; AbszpWorker *abszpWorker; float autoMaxVal = 100.; // determined by the coadd task on the coadded image int verbosity = 0; int maxCPU = 1; void taskInternalAbszeropoint(); void updateSaturationValue(float value); signals: void messageAvailable(QString message, QString type); void progressUpdate(float progress); void resetProgressBar(); void finished(); void readyForPlotting(); void abszpClosed(); void updateAbsPhotPlot(bool checked); public slots: void updateVerbosity(int verbosityLevel); void iViewClosed(); private slots: void on_actionClose_triggered(); void on_closePushButton_clicked(); void on_showAbsphotPushButton_clicked(); void on_zpImageLineEdit_textChanged(const QString &arg1); void on_zpRefcatComboBox_currentTextChanged(const QString &arg1); void on_zpLoadPushButton_clicked(); void on_abortPushButton_clicked(); void on_startPushButton_clicked(); void on_zpClearPushButton_clicked(); void on_zpExportPushButton_clicked(); void on_zpFilterComboBox_currentTextChanged(const QString &arg1); void showData(QCPAbstractPlottable *plottable, int dataIndex); void on_zpFitOrderSpinBox_valueChanged(int arg1); void displayMessage(QString message, QString type); void finishedCalculations(); void buildAbsPhot(); void criticalReceived(); private: void defaults_if_empty(); void initGUI(); void updateHeader(); void validate(); bool doColortermFit(); void updateCoaddHeader(); void pushBeginMessage(); void pushEndMessage(); void queryRefCat(); void loadPreferences(); void closeEvent(QCloseEvent *event); void writeAbsPhotRefcat(); void clearText(); double getFirstZPestimate(); Ui::AbsZeroPoint *ui; QString taskBasename = "AbsZeropoint"; QString thelidir; QString userdir; QFileInfo fileInfo; QStringList totalCommandList; bool performingStartup = true; QVector raRefCat; QVector deRefCat; QVector mag1RefCat; QVector mag2RefCat; QVector mag1errRefCat; QVector mag2errRefCat; long numRefSources = 0; double refCatUpperMagLimit = 40.; QVector> refDat; QVector> objDat; QVector> matched; MyImage *myImage; bool workerInit = false; bool workerThreadInit = false; IView *iView; bool iViewOpen = false; }; #endif // ABSZEROPOINT_H THELI-3.1.3/src/abszp/abszeropoint.ui000066400000000000000000001527111417631501300173570ustar00rootroot00000000000000 AbsZeroPoint 0 0 879 750 Absolute photometric calibration true 0 0 Qt::NoFocus Select an image with valid WCS for photometric calibration. Select image ... Qt::Horizontal QSizePolicy::Preferred 40 20 0 0 The full path to the image that is to be calibrated. Any image with valid WCS will work. 170 0 0 170 0 0 119 120 120 75 true Click on a zeropoint to update the FITS header 0 0 252 252 252 195 195 195 252 252 252 195 195 195 195 195 195 195 195 195 true QFrame::Panel QFrame::Sunken 2 0 0 0 0 0 0 400 300 Click on a zeropoint in the upper panel to update the FITS header true 0 0 879 23 File 252 252 252 219 219 220 252 252 252 219 219 220 219 219 220 219 219 220 true QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Configuration 1 0 0 true QFrame::Panel QFrame::Sunken 2 0 0 0 0 0 0 Qt::NoFocus This window displays the keywords with the photometric solution written to the FITS header. true 0 0 252 252 252 199 199 200 252 252 252 199 199 200 199 199 200 199 199 200 true QFrame::StyledPanel QFrame::Raised Saturation / nonlinearity limit Aperture diameters [ pixel ] false The order of the polynomial fit for the ZP / color term dependence 1 3 The filter in which you observed. false Polynomial fit order 0 0 0 0 The maximum photometric error allowed for sources in the image. The upper limit to the measured photometric error in your data. Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 0 0 A comma-separated list of aperture diameters used for the growth curve. Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Max phot error [ mag ] 0 0 0 0 The level above which non-linearity (or saturation) occurs. The level at which nonlinearity or saturation occurs. Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter A photometric reference catalog matching the filter of your observations. PANSTARRS queries can take several minutes. ATLAS-REFCAT2 PANSTARRS-DR1 SDSS-DR12 SKYMAPPER-DR1 APASS-DR9 2MASS VHS-DR4 UKIDSS The color term is determined from the reference catalog. Ideally, choose one that matches other filters you have for this target. Color term you want to use Photometric reference catalog Filter in which you observed DT DMIN 0 0 Detection threshold per pixel 10 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 Minimum number of connected pixels above the detection threshold 10 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Show AbsPhot references Qt::Vertical QSizePolicy::Fixed 17 17 75 true Setup 80 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 50 false Qt::NoFocus false Start false 80 0 80 16777215 0 0 0 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 0 0 0 255 255 255 0 0 0 255 255 255 223 77 123 0 0 0 239 166 189 255 255 220 0 0 0 0 0 0 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 0 0 0 255 255 255 0 0 0 255 255 255 223 77 123 0 0 0 239 166 189 255 255 220 0 0 0 111 38 61 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 111 38 61 255 255 255 111 38 61 223 77 123 223 77 123 0 0 0 223 77 123 255 255 220 0 0 0 50 false Qt::NoFocus Lets the current task finish gracefully, then stops before executing further tasks in the queue. Abort Qt::NoFocus Clear plot Qt::NoFocus Export plot Qt::Horizontal 17 25 75 true System output Qt::Vertical QSizePolicy::Fixed 20 20 80 0 80 16777215 Close Close QCustomPlot QWidget
qcustomplot.h
1
zpImageLineEdit zpRefcatComboBox zpFilterComboBox zpColorComboBox zpFitOrderSpinBox zpSaturationLineEdit zpPhoterrorLineEdit zpDTLineEdit zpDMINLineEdit zpApertureLineEdit
THELI-3.1.3/src/colorpicture/000077500000000000000000000000001417631501300156655ustar00rootroot00000000000000THELI-3.1.3/src/colorpicture/colorpicture.cc000066400000000000000000000563531417631501300207220ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../instrumentdata.h" #include "../preferences.h" #include "../iview/iview.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include #include #include #include #include #include #include #include ColorPicture::ColorPicture(QString main, QWidget *parent) : QMainWindow(parent), mainDir(main), ui(new Ui::ColorPicture) { ui->setupUi(this); initEnvironment(thelidir, userdir); // Model views coaddDirModel = new QStringListModel(this); coaddImageModel = new QStringListModel(this); ui->coaddDirListView->setModel(coaddDirModel); ui->coaddImageListView->setModel(coaddImageModel); ui->redComboBox->setModel(coaddImageModel); ui->greenComboBox->setModel(coaddImageModel); ui->blueComboBox->setModel(coaddImageModel); ui->broadbandComboBox ->setModel(coaddImageModel); ui->narrowbandComboBox->setModel(coaddImageModel); ui->dirLineEdit->setText(mainDir); paintPathLineEdit(ui->dirLineEdit, mainDir, "dir"); addDirectories(); connect(ui->blueFactorLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->redFactorLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->filterRatioLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->narrowbandWeightLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->resultSDSSPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultPANSTARRSPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultSKYMAPPERPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultATLASPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultAVGWHITEPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->redFactorLineEdit, &QLineEdit::textEdited, this, &ColorPicture::sendColorFactors); connect(ui->blueFactorLineEdit, &QLineEdit::textEdited, this, &ColorPicture::sendColorFactors); connect(ui->resultSDSSPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultPANSTARRSPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultSKYMAPPERPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultATLASPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultAVGWHITEPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->getStatisticsPushButton, &QPushButton::clicked, this, &ColorPicture::on_previewCalibPushButton_clicked); connect(this, &ColorPicture::messageAvailable, this, &ColorPicture::displayMessage); connect(this, &ColorPicture::updateNrefStars, this, &ColorPicture::updateNrefStarsReceived); connect(this, &ColorPicture::addCombinedImage, this, &ColorPicture::addCombinedImageReceived); ui->tabWidget->setCurrentIndex(0); resultButtonGroup->setExclusive(true); resultButtonGroup->addButton(ui->resultPANSTARRSPushButton); resultButtonGroup->addButton(ui->resultSDSSPushButton); resultButtonGroup->addButton(ui->resultSKYMAPPERPushButton); resultButtonGroup->addButton(ui->resultATLASPushButton); resultButtonGroup->addButton(ui->resultAVGWHITEPushButton); QPalette palette; palette.setColor(QPalette::Background, QColor("#c6c6c6")); ui->statusbar->setPalette(palette); setWindowIcon(QIcon(":/icons/color.png")); loadPreferences(); // Init queries PANSTARRSquery->refcatName = "PANSTARRS"; SDSSquery->refcatName = "SDSS"; SKYMAPPERquery->refcatName = "SKYMAPPER"; ATLASquery->refcatName = "ATLAS-REFCAT2"; connect(PANSTARRSquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); connect(SDSSquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); connect(SKYMAPPERquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); connect(ATLASquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); } ColorPicture::~ColorPicture() { delete PANSTARRSquery; delete SDSSquery; delete SKYMAPPERquery; delete ATLASquery; PANSTARRSquery = nullptr; SDSSquery = nullptr; SKYMAPPERquery = nullptr; ATLASquery = nullptr; delete ui; } void ColorPicture::updateVerbosity(int verbosityLevel) { verbosity = verbosityLevel; } void ColorPicture::loadPreferences() { QSettings settings("THELI", "PREFERENCES"); maxCPU = settings.value("prefCPUSpinBox").toInt(); // verbosity = settings.value("prefVerbosityComboBox").toInt(); verbosity = 0; } // Receiving end from setWCSLock call void ColorPicture::setWCSLockReceived(bool locked) { if (locked) omp_set_lock(&wcsLock); else omp_unset_lock(&wcsLock); } void ColorPicture::displayMessage(QString message, QString type) { if (type == "error") { ui->processingTextEdit->appendHtml("ERROR: " + message + ""); } else if (type == "warning") { ui->processingTextEdit->appendHtml("" + message + ""); } else if (type == "info") { ui->processingTextEdit->appendHtml("" + message + ""); } else if (type == "note") { ui->processingTextEdit->appendHtml("" + message + ""); } else if (type == "append") { ui->processingTextEdit->moveCursor(QTextCursor::End); ui->processingTextEdit->appendHtml(" "+message); ui->processingTextEdit->moveCursor(QTextCursor::End); } else ui->processingTextEdit->appendHtml(message); } void ColorPicture::criticalReceived() { emit finished(); } void ColorPicture::checkCalibrationFactor(QLineEdit *le) { if (le->text().isEmpty()) le->setText("1.000"); } void ColorPicture::sendColorFactors() { checkCalibrationFactor(ui->redFactorLineEdit); checkCalibrationFactor(ui->blueFactorLineEdit); // green is always 1.0 float redFactor = ui->redFactorLineEdit->text().toFloat(); float blueFactor = ui->blueFactorLineEdit->text().toFloat(); emit colorFactorChanged(redFactor, blueFactor); } void ColorPicture::on_selectDirPushButton_clicked() { // get parent directory QFileDialog qfd(this); qfd.setFileMode(QFileDialog::DirectoryOnly); qfd.setOption(QFileDialog::ShowDirsOnly); qfd.setDirectory(mainDir); qfd.setWindowTitle(tr("Select directory")); QString dirName; if (qfd.exec()) dirName = qfd.selectedFiles().at(0); ui->dirLineEdit->setText(dirName); paintPathLineEdit(ui->dirLineEdit, dirName, "dir"); addDirectories(); } void ColorPicture::addDirectories() { QString dirName = ui->dirLineEdit->text(); if (!QDir(dirName).exists()) return; mainDir = ui->dirLineEdit->text(); // find all coadd_xxx subdirectories QStringList subDirList; findRecursion(dirName, &subDirList); QStringList coaddList; // Keep coadd_xxx only for (auto &it : subDirList) { QString tmp = it.remove(0, dirName.length()); if (tmp.startsWith('/')) tmp = tmp.remove(0,1); if (tmp.startsWith("coadd_") || tmp.contains("/coadd_")) { QFile coaddedImage(dirName+"/"+tmp+"/coadd.fits"); if (coaddedImage.exists()) coaddList.append(tmp); } } coaddDirModel->setStringList(coaddList); } void ColorPicture::findRecursion(const QString &path, QStringList *result) { // recursive QDir currentDir(path); const QString prefix = path + QLatin1Char('/'); foreach (const QString &match, currentDir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)) result->append(prefix + match); foreach (const QString &dir, currentDir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)) findRecursion(prefix + dir, result); } void ColorPicture::refreshComboBoxes() { QStringList filters; filters << "*cropped.fits"; QString dirName = ui->dirLineEdit->text(); QStringList fileList = QDir(dirName+"/color_theli/").entryList(filters); coaddImageModel->setStringList(fileList); coaddImageModel->sort(0); ui->redComboBox->setCurrentIndex(0); ui->greenComboBox->setCurrentIndex(0); ui->blueComboBox->setCurrentIndex(0); ui->broadbandComboBox->setCurrentIndex(0); ui->narrowbandComboBox->setCurrentIndex(0); } void ColorPicture::taskFinished(QString taskname) { if (taskname == "CropCoadds") updateImageListView(); if (taskname == "ColorCalib") updateCalibFactors(); if (taskname == "BBNBratio") updateFilterRatio(); if (taskname == "BBNBcombine") updateBBNBcombine(); if (taskname == "Fits2Tiff") updateTiff(); } void ColorPicture::updateTiff() { ui->createTiffPushButton->setEnabled(true); showDone(ui->createTiffPushButton, "(4) Create TIFFs"); emit messageAvailable("Done.", "info"); } void ColorPicture::updateImageListView() { // Repopulate the comboboxes refreshComboBoxes(); buttonPalette.setColor(QPalette::Button, QColor("#44d8cc")); ui->getCoaddsPushButton->setPalette(buttonPalette); ui->getCoaddsPushButton->setEnabled(true); showDone(ui->getCoaddsPushButton, "Get selected coadded images"); } void ColorPicture::on_clearCoaddsPushButton_clicked() { coaddImageModel->removeRows(0, coaddImageModel->rowCount()); } void ColorPicture::validate() { // Floating point validators QRegExp rf( "^[-]{0,1}[0-9]+[.]{0,1}[0-9]+" ); QValidator* validator = new QRegExpValidator( rf, this ); ui->blueFactorLineEdit->setValidator( validator ); ui->redFactorLineEdit->setValidator( validator ); ui->filterRatioLineEdit->setValidator( validator ); ui->narrowbandWeightLineEdit->setValidator( validator ); ui->DTLineEdit->setValidator( validator ); // Positive integer validator QRegExp ri( "^[0-9]+" ); QValidator* validator_int_pos = new QRegExpValidator( ri, this ); ui->DMINLineEdit->setValidator( validator_int_pos ); } void ColorPicture::showDone(QPushButton *pushButton, QString text) { // pushButton->setText("Done"); // QTest::qWait(1000); pushButton->setText(text); } void ColorPicture::updateCalibFactors() { int nrefcat = 4; // Select the best result (the ones with the most matches, other than AVGWHITE int maxStars = 0; int maxIndex = -1; for (int i=0; i maxStars) { maxStars = photcatresult[i].nstars.toInt(); maxIndex = i; } } if (maxIndex == 0) ui->resultPANSTARRSPushButton->setChecked(true); else if (maxIndex == 1) ui->resultSDSSPushButton->setChecked(true); else if (maxIndex == 2) ui->resultSKYMAPPERPushButton->setChecked(true); else if (maxIndex == 3) ui->resultATLASPushButton->setChecked(true); else { // Fallback onto AVGWHITE solution maxIndex = nrefcat; ui->resultAVGWHITEPushButton->setChecked(true); } toggleCalibResult(); buttonPalette.setColor(QPalette::Button, QColor("#44d8cc")); ui->calibratePushButton->setPalette(buttonPalette); ui->calibratePushButton->setEnabled(true); showDone(ui->calibratePushButton, "(1) Calibrate"); emit messageAvailable("Done.", "info"); ui->redComboBox->setEnabled(true); ui->greenComboBox->setEnabled(true); ui->blueComboBox->setEnabled(true); // send the new color factors to iview (if opened) sendColorFactors(); // If no reference stars were retrieved if (photcatresult[maxIndex].nstars.toInt() == 0 || maxIndex == nrefcat) { emit messageAvailable("No G2-type references could be matched for this field. Falling back on 'average white'.", "warning"); } } // Given a name, find the corresponding MyImage* in memory MyImage* ColorPicture::identifyCroppedMyImage(QString name) { for (auto &myImage : croppedList) { if (myImage->name == name) return myImage; } emit messageAvailable("Could not identify "+name+"
in the list of cropped images!", "error"); return nullptr; } QVector> ColorPicture::getObjectData(MyImage *myImage) { QVector> objData; objData.reserve(myImage->objectList.length()); if (myImage->objectList.length() == 0) { emit messageAvailable("No objects detected in "+myImage->baseName+" !", "error"); } else { for (auto &object : myImage->objectList) { QVector tmp; if (object->FLAGS == 0 && object->FLUX_AUTO > 0.) { // DEC comes first in the catalogs, because the matching alg sorts the vectors for DEC tmp << object->DELTA_J2000 << object->ALPHA_J2000 << object->FLUX_AUTO; objData.append(tmp); } } } return objData; } void ColorPicture::updateFilterRatio() { // Read results QString ratio = QString::number(bbnbFluxRatio, 'f', 3); QString ratioError = QString::number(bbnbFluxRatioError, 'f', 3); ui->filterRatioLineEdit->setText(ratio+" +/- "+ratioError); ui->getRatioPushButton->setText("(1) Estimate flux ratio"); ui->getRatioPushButton->setEnabled(true); ui->narrowbandComboBox->setEnabled(true); ui->broadbandComboBox->setEnabled(true); ui->BBNBcombinePushButton->setEnabled(true); } void ColorPicture::updateBBNBcombine() { QString oldBB = ui->broadbandComboBox->currentText(); QString oldNB = ui->narrowbandComboBox->currentText(); // Update the model (which refreshes all combo boxes) refreshComboBoxes(); // Restore previous combobox selection ui->broadbandComboBox->setCurrentText(oldBB); ui->narrowbandComboBox->setCurrentText(oldNB); ui->BBNBcombinePushButton->setEnabled(true); ui->BBNBcombinePushButton->setText("(2) Combine images"); } void ColorPicture::toggleCalibResult() { int i = 4; int nrefcat = 4; if (ui->resultPANSTARRSPushButton->isChecked()) i = 0; else if (ui->resultSDSSPushButton->isChecked()) i = 1; else if (ui->resultSKYMAPPERPushButton->isChecked()) i = 2; else if (ui->resultATLASPushButton->isChecked()) i = 3; else if (ui->resultAVGWHITEPushButton->isChecked()) i = 4; if (i<=nrefcat) { ui->redFactorLineEdit->setText(photcatresult[i].rfac); ui->redErrorLineEdit->setText(photcatresult[i].rfacerr); ui->greenFactorLineEdit->setText("1.000"); ui->greenErrorLineEdit->setText("0.000"); ui->blueFactorLineEdit->setText(photcatresult[i].bfac); ui->blueErrorLineEdit->setText(photcatresult[i].bfacerr); } else { emit messageAvailable("BUG: code should never enter here", "error"); ui->redFactorLineEdit->clear(); ui->redErrorLineEdit->clear(); ui->greenFactorLineEdit->setText("1.000"); ui->greenErrorLineEdit->setText("0.000"); ui->blueFactorLineEdit->clear(); ui->blueErrorLineEdit->clear(); } } void ColorPicture::readFilterRatioResults(QString filename) { QString path = mainDir+"/color_theli/PHOTCAT_calibration/"; QFile file(path+"/"+filename); QStringList list; QString line; QString ratio = ""; QString ratio_error = ""; if ( file.open(QIODevice::ReadOnly)) { QTextStream stream( &file ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); list = line.split(" "); if (!line.isEmpty() && list.length() == 2) { ratio = list.at(0); ratio_error = list.at(1); } } file.close(); if (!ratio.isEmpty() && !ratio_error.isEmpty()) { ui->filterRatioLineEdit->setText(ratio+" +/- "+ratio_error); } else { ui->filterRatioLineEdit->clear(); } } else { QMessageBox::warning(this, tr("Could not read filter ratio result."), tr("The file ")+path+"/"+filename+tr(" could not be opened."), QMessageBox::Ok); } } void ColorPicture::updateColorFactorsExternal(QString redFactor, QString blueFactor) { ui->redFactorLineEdit->setText(redFactor); ui->blueFactorLineEdit->setText(blueFactor); resetResultButtonGroup(); } // Invoked by the preview button, as well as by the "get statistics" push button void ColorPicture::on_previewCalibPushButton_clicked() { if (iViewOpen) { iView->raise(); QMessageBox msgBox; msgBox.setText("Left-click into a blank region of the image to obtain image statistics. " "Ideally, this should be the darkest region of the image with few stars.\n\n" "Statistics will be measured in a 9x9 pixel area."); msgBox.exec(); return; } // Load the image viewer checkCalibrationFactor(ui->redFactorLineEdit); checkCalibrationFactor(ui->blueFactorLineEdit); iView = new IView("FITScolor", mainDir+"/color_theli/", ui->redComboBox->currentText(), ui->greenComboBox->currentText(), ui->blueComboBox->currentText(), ui->redFactorLineEdit->text().toFloat(), ui->blueFactorLineEdit->text().toFloat(), this); connect(this, &ColorPicture::colorFactorChanged, iView, &IView::updateColorViewExternal); connect(iView, &IView::colorFactorChanged, this, &ColorPicture::updateColorFactorsExternal); connect(iView, &IView::closed, this, &ColorPicture::updateIviewStatus); connect(iView, &IView::statisticsRequested, this, &ColorPicture::measureStatistics); iViewOpen = true; iView->G2referencePathName = mainDir+"/color_theli/PHOTCAT_calibration/"; iView->show(); if (sender() == ui->getStatisticsPushButton) { QMessageBox msgBox; msgBox.setText("Left-click into a blank region of the image to obtain image statistics. " "Ideally, this should be the darkest region of the image with few stars.\n\n" "Statistics will be measured in a 9x9 pixel area."); msgBox.exec(); } } void ColorPicture::updateIviewStatus() { iViewOpen = false; } void ColorPicture::addCombinedImageReceived(MyImage *combinedImage) { croppedList.append(combinedImage); } void ColorPicture::measureStatistics(long x, long y) { ui->statisticsTableWidget->clear(); int nrows = coaddImageModel->rowCount(); int ncols = 5; ui->statisticsTableWidget->setRowCount(nrows); ui->statisticsTableWidget->setColumnCount(ncols); QStringList header; header << "Image" << "median" << "rms" << "min (black point)" << "max (white point)"; ui->statisticsTableWidget->setHorizontalHeaderLabels(header); // Get the min and max values first QVector minValues; QVector maxValues; for (int i=0; iindex(i,0).data().toString(); for (auto &myImage : croppedList) { if (myImage->name == name) { long xmin = x - 1 - 4; long xmax = x - 1 + 4; long ymin = y - 1 - 4; long ymax = y - 1 + 4; QVector data = myImage->extractPixelValues(xmin, xmax, ymin, ymax); float medVal = medianMask_T(data); float rmsVal = madMask_T(data)*1.486; float minVal = medVal - 6.*rmsVal; // an estimate for the black point float maxVal = medVal + 250.*rmsVal; // an estimate for the white point minValues.append(minVal); maxValues.append(maxVal); QTableWidgetItem *item0 = new QTableWidgetItem(name); QTableWidgetItem *item1 = new QTableWidgetItem(QString::number(medVal, 'f', 3)); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(rmsVal, 'f', 2)); item0->setFlags(item0->flags() ^ Qt::ItemIsEditable); item1->setFlags(item1->flags() ^ Qt::ItemIsEditable); item2->setFlags(item2->flags() ^ Qt::ItemIsEditable); ui->statisticsTableWidget->setItem(i, 0, item0); ui->statisticsTableWidget->setItem(i, 1, item1); ui->statisticsTableWidget->setItem(i, 2, item2); } } } // Black and white points should be the same for all images to preserve colors float commonMin = minVec_T(minValues); float commonMax = maxVec_T(maxValues); for (int i=0; istatisticsTableWidget->setItem(i, 3, item3); ui->statisticsTableWidget->setItem(i, 4, item4); } ui->statisticsTableWidget->resizeColumnsToContents(); statisticsRetrieved = true; } void ColorPicture::resetResultButtonGroup(QString resetLabels) { resultButtonGroup->setExclusive(false); ui->resultSDSSPushButton->setChecked(false); ui->resultSKYMAPPERPushButton->setChecked(false); ui->resultPANSTARRSPushButton->setChecked(false); ui->resultATLASPushButton->setChecked(false); ui->resultAVGWHITEPushButton->setChecked(false); resultButtonGroup->setExclusive(true); if (!resetLabels.isEmpty()) { ui->numPANSTARRSLabel->setText("? stars"); ui->numSDSSLabel->setText("? stars"); ui->numSKYMAPPERLabel->setText("? stars"); ui->numATLASLabel->setText("? stars"); ui->numAVGWHITELabel->setText("? stars"); } } void ColorPicture::on_actionClose_triggered() { this->close(); } void ColorPicture::on_redComboBox_currentIndexChanged(int index) { if (iViewOpen) { iView->close(); on_previewCalibPushButton_clicked(); } } void ColorPicture::on_greenComboBox_currentIndexChanged(int index) { if (iViewOpen) { iView->close(); on_previewCalibPushButton_clicked(); } } void ColorPicture::on_blueComboBox_currentIndexChanged(int index) { if (iViewOpen) { iView->close(); on_previewCalibPushButton_clicked(); } } void ColorPicture::on_narrowbandComboBox_currentTextChanged(const QString &arg1) { ui->filterRatioLineEdit->setText("0"); } void ColorPicture::on_broadbandComboBox_currentTextChanged(const QString &arg1) { ui->filterRatioLineEdit->setText("0"); } void ColorPicture::on_abortPushButton_clicked() { workerThread->quit(); workerThread->wait(); } THELI-3.1.3/src/colorpicture/colorpicture.h000066400000000000000000000134111417631501300205500ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef COLORPICTURE_H #define COLORPICTURE_H #include "../threading/colorpictureworker.h" #include "../iview/iview.h" #include "../query/query.h" #include "refcatdata.h" #include #include #include #include #include #include class ColorPictureWorker; namespace Ui { class ColorPicture; } class ColorPicture : public QMainWindow { Q_OBJECT public: explicit ColorPicture(QString main = "", QWidget *parent = nullptr); ~ColorPicture(); bool iViewOpen = false; int verbosity = 0; int maxCPU = 1; void taskInternalColorCalib(); void taskInternalCropCoadds(); void taskInternalFits2Tiff(); void taskInternalBBNBratio(); void taskInternalBBNBcombine(); signals: void colorFactorChanged(float redFactor, float blueFactor); void messageAvailable(QString message, QString type); void progressUpdate(float progress); void resetProgressBar(); void finished(); void showMessageBox(QString trigger, QString part1, QString part2); void updateNrefStars(QString name, long number); void addCombinedImage(MyImage *myImage); public slots: void taskFinished(QString taskname); void updateVerbosity(int verbosityLevel); private slots: void addCombinedImageReceived(MyImage *combinedImage); void criticalReceived(); void displayMessage(QString message, QString type); void measureStatistics(long x, long y); void on_abortPushButton_clicked(); void on_actionClose_triggered(); void on_createTiffPushButton_clicked(); void on_redComboBox_currentIndexChanged(int index); void on_greenComboBox_currentIndexChanged(int index); void on_blueComboBox_currentIndexChanged(int index); void on_narrowbandComboBox_currentTextChanged(const QString &arg1); void on_broadbandComboBox_currentTextChanged(const QString &arg1); void on_getRatioPushButton_clicked(); void on_previewCalibPushButton_clicked(); void on_calibratePushButton_clicked(); void on_selectDirPushButton_clicked(); void on_getCoaddsPushButton_clicked(); void on_clearCoaddsPushButton_clicked(); void on_BBNBcombinePushButton_clicked(); void sendColorFactors(); void setWCSLockReceived(bool locked); void updateCalibFactors(); void updateColorFactorsExternal(QString redFactor, QString blueFactor); void updateImageListView(); void updateFilterRatio(); void updateIviewStatus(); void updateTiff(); void updateNrefStarsReceived(QString name, long number); void validate(); private: QString mainDir; Ui::ColorPicture *ui; QString thelidir; QString userdir; QStringListModel *coaddImageModel; QStringListModel *coaddDirModel; IView *iView; QButtonGroup *resultButtonGroup = new QButtonGroup(this); QPalette buttonPalette; bool statisticsRetrieved = false; QThread *workerThread; ColorPictureWorker *colorpictureWorker; omp_lock_t wcsLock; float bbnbFluxRatio = 1.0; float bbnbFluxRatioError = 0.0; QList coaddList; // all coadds, including weights QList croppedList; // only the cropped coadded images, without the weights QStringList refCatList = {"SDSS", "ATLAS-REFCAT2", "SKYMAPPER", "PANSTARRS"}; Query *SDSSquery = new Query(&verbosity); Query *ATLASquery = new Query(&verbosity); Query *PANSTARRSquery = new Query(&verbosity); Query *SKYMAPPERquery = new Query(&verbosity); RefCatData *SDSS = new RefCatData("SDSS", this); RefCatData *ATLAS = new RefCatData("ATLAS-REFCAT2", this); RefCatData *SKYMAPPER = new RefCatData("SKYMAPPER", this); RefCatData *PANSTARRS = new RefCatData("PANSTARRS", this); typedef struct { QString catname; QString nstars; QString bfac; QString gfac; QString rfac; QString bfacerr; QString gfacerr; QString rfacerr; } _photcatresult_; _photcatresult_ photcatresult[5]; void addDirectories(); void checkCalibrationFactor(QLineEdit *le); void findRecursion(const QString &path, QStringList *result); void readFilterRatioResults(QString filename); void resetResultButtonGroup(QString resetLabels = ""); void refreshComboBoxes(); void showDone(QPushButton *pushButton, QString text); void toggleCalibResult(); void loadPreferences(); void filterSolarTypeStars(QList queryList); void colorCalibSegmentImages(); void colorCalibRetrieveCatalogs(QList queryList); void colorCalibMatchReferenceCatalog(const QVector > &matchedRGB, RefCatData *REFCAT, float tolerance); void colorCalibMatchCatalogs(); MyImage *identifyCroppedMyImage(QString name); QVector > getObjectData(MyImage *myImage); void updateBBNBcombine(); void writeG2refcat(const QString refcatName, const QVector > matchedREFCAT); void writeRGBTIFF(QVector &R, QVector &G, QVector &B, long n, long m, float min, float max, QString path); void filterReferenceCatalog(RefCatData *REFCAT, MyImage *channelImage); }; #endif // COLORPICTURE_H THELI-3.1.3/src/colorpicture/colorpicture.ui000066400000000000000000006534301417631501300207510ustar00rootroot00000000000000 ColorPicture 0 0 977 838 0 0 Photometric color calibration of RGB images 0 0 252 252 252 199 199 200 252 252 252 199 199 200 199 199 200 199 199 200 Qt::ClickFocus Performs the photometric color calibration method true 1 Preparation Qt::ClickFocus Coadditions will be searched for in all sub-directories (looking for coadd_* directories) Select parent directory ... 0 0 Qt::StrongFocus Coadditions will be searched for in all sub-directories (looking for coadd_* directories) true Qt::Vertical QSizePolicy::Fixed 20 15 75 true (1) Select coadds for cropping 75 true (2) Optional: Combine broad- and narrowband images 0 0 0 0 0 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 0 0 0 255 255 255 0 0 0 255 255 255 219 219 220 0 0 0 237 237 237 255 255 220 0 0 0 0 0 0 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 0 0 0 255 255 255 0 0 0 255 255 255 219 219 220 0 0 0 237 237 237 255 255 220 0 0 0 109 109 110 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 109 109 110 255 255 255 109 109 110 219 219 220 219 219 220 0 0 0 219 219 220 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Plain Selected and cropped coadded images 0 0 400 0 255 255 235 255 255 235 238 255 255 Qt::NoFocus The cropped coadded images available for calibration (stored in the color_theli/ subdirectory) QFrame::Panel 2 QAbstractItemView::NoEditTriggers QAbstractItemView::NoSelection 0 0 400 0 Qt::ClickFocus Click, or ctrl-click to select all coadditions needed for the color picture. QFrame::Panel 2 QAbstractItemView::NoEditTriggers false false QAbstractItemView::ExtendedSelection QAbstractItemView::SelectRows Qt::ClickFocus Clears the list of directories. Clear 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Crops coadded images to the same size, and stores them in a color_theli/ sub-directory. Crop coadded images Qt::Horizontal QSizePolicy::Fixed 20 20 0 0 0 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 0 0 0 255 255 255 0 0 0 255 255 255 219 219 220 0 0 0 237 237 237 255 255 220 0 0 0 0 0 0 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 0 0 0 255 255 255 0 0 0 255 255 255 219 219 220 0 0 0 237 237 237 255 255 220 0 0 0 109 109 110 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 109 109 110 255 255 255 109 109 110 219 219 220 219 219 220 0 0 0 219 219 220 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Plain 0 Narrowband 0 0 300 0 Qt::ClickFocus Select the narrowband image Broadband 0 0 300 0 Qt::ClickFocus Select the broadband image 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Measures the median flux ratio of the narrow and broadband filters (NB / BB). Requires PHOTINSTRU_KEY = FILTER for scamp! (1) Estimate effective ratio 0 0 255 255 235 255 255 235 219 219 220 Qt::ClickFocus The estimated ratio of the effective filter widths (narrow / broad) 0 true Relative weight of narrowband image 0 0 60 16777215 Default: 1.0. Larger values (1.5, 2, ...) increase the narrowband contribution while maintaining stellar fluxes. 1.0 Qt::Horizontal 329 27 Qt::Vertical QSizePolicy::Fixed 20 10 0 0 255 255 235 255 255 235 219 219 220 10 Qt::ClickFocus <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">Combines narrow- and broadband images to enhance nebular features, e.g. an H-alpha image combined with a red image. The combined images are added to the list shown at the left. </span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">The ratio of the effective bandpass widths is essential to preserve the stars' colors. The coadditions must be based on a 'Scamp' run with PHOTINSTRU_KEY = FILTER, otherwise the relative flux levels are not preserved.</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">The calculation is as follows (w = weight, r = ratio)</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">Image</span><span style=" font-size:12pt; vertical-align:sub;">combined</span><span style=" font-size:12pt;"> = (1 - w * r) * Image</span><span style=" font-size:12pt; vertical-align:sub;">broad</span><span style=" font-size:12pt;"> + w * Image</span><span style=" font-size:12pt; vertical-align:sub;">narrow</span></p></body></html> 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Combines broad- and narrowband images and adds them to the list of coadded images. (2) Combine images Photometric color calibration 75 true (3) Calibrate images against photometric reference catalogs 252 252 252 247 247 247 252 252 252 247 247 247 247 247 247 247 247 247 true QFrame::Panel QFrame::Sunken 1 Qt::Horizontal QSizePolicy::Preferred 525 20 Factor Uncertainty 75 true Choose calibration result 0 0 204 0 0 204 0 0 119 120 120 Red image 0 0 250 0 Qt::ClickFocus Select the image that will form the red channel of the RGB image 90 0 90 16777215 Adjust the red factor (relative to green) false 90 0 90 16777215 255 255 229 255 255 221 255 255 229 255 255 221 239 240 241 255 255 221 Qt::NoFocus The statistical uncertainty of the red factor false true 0 0 120 0 120 16777215 Qt::ClickFocus Shows the PANSTARRS result PANSTARRS true false 0 0 ? stars 0 0 0 153 0 0 153 0 119 120 120 Green image 0 0 250 0 Qt::ClickFocus Select the image that will form the green channel of the RGB image 90 0 90 16777215 255 255 229 255 255 229 239 240 241 Qt::NoFocus The green factor is fixed 1.000 true 90 0 90 16777215 255 255 229 255 255 221 255 255 229 255 255 221 239 240 241 255 255 221 Qt::NoFocus The uncertainty of the green factor (fixed) false 0.000 true Qt::Horizontal QSizePolicy::Fixed 20 20 0 0 120 0 120 16777215 Qt::ClickFocus Shows the SDSS result SDSS true false 0 0 ? stars 0 0 0 0 255 0 0 255 119 120 120 Blue image 0 0 250 0 Qt::ClickFocus Select the image that will form the blue channel of the RGB image 90 0 90 16777215 Adjust the blue factor (relative to green) false false 90 0 90 16777215 255 255 229 255 255 229 239 240 241 Qt::NoFocus The statistical uncertainty of the blue factor false true 0 0 120 0 120 16777215 Qt::ClickFocus Shows average white correction factors SKYMAPPER true false 0 0 ? stars Qt::Horizontal 18 20 DT 60 0 80 16777215 Detection threshold per pixel 10 DMIN 60 0 80 16777215 Minimum number of connected pixels above the detection threshold 5 0 0 150 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus This may take several minutes Determine the correction factors so that solar-type stars are displayed white. (1) Calibrate 0 0 120 0 120 16777215 Qt::ClickFocus Shows the ATLAS-REFCAT2 result ATLAS-REFCAT2 true false 0 0 ? stars Qt::Horizontal QSizePolicy::Preferred 85 20 Qt::Horizontal 431 20 150 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus (2) Preview RGB image 0 0 120 0 120 16777215 Qt::ClickFocus Shows average white correction factors AVGWHITE true false 0 0 ? stars 75 true The min and max levels will form the black and white points, respectively (4) Adjust dynamic range for the TIFF images 0 0 252 252 252 236 236 236 252 252 252 236 236 236 236 236 236 236 236 236 true QFrame::Panel QFrame::Sunken 2 75 true The min and max levels will form the black and white points, respectively Edit min and max as required Qt::Horizontal 218 20 Qt::Vertical 20 137 0 0 Qt::ClickFocus Adjust the thresholds according to your needs QAbstractItemView::SingleSelection false 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Select a region with empty sky (middle-click drag) in an image (3) Estimate background level 0 0 150 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Stores 16bit TIFF images for each channel under color_theli/ (4) Create TIFF images Qt::Vertical QSizePolicy::Fixed 20 6 75 true System output 0 0 500 0 16777215 200 Shows processing messages QFrame::Panel true Qt::Horizontal QSizePolicy::Fixed 40 20 120 16777215 0 0 0 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 0 0 0 255 255 255 0 0 0 255 255 255 223 77 123 0 0 0 239 166 189 255 255 220 0 0 0 0 0 0 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 0 0 0 255 255 255 0 0 0 255 255 255 223 77 123 0 0 0 239 166 189 255 255 220 0 0 0 111 38 61 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 111 38 61 255 255 255 111 38 61 223 77 123 223 77 123 0 0 0 223 77 123 255 255 220 0 0 0 Lets the current task finish gracefully, then stops before executing further tasks in the queue. Abort Qt::Horizontal QSizePolicy::Preferred 40 20 0 0 977 23 File Close dirLineEdit narrowbandWeightLineEdit redFactorLineEdit blueFactorLineEdit THELI-3.1.3/src/colorpicture/refcatdata.cc000066400000000000000000000017001417631501300202700ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "refcatdata.h" RefCatData::RefCatData(QString refcatname, QObject *parent) : QObject(parent) { name = refcatname; } void RefCatData::clear() { ra.clear(); de.clear(); mag1.clear(); mag2.clear(); mag3.clear(); mag4.clear(); mag5.clear(); } THELI-3.1.3/src/colorpicture/refcatdata.h000066400000000000000000000023341417631501300201360ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef REFCATDATA_H #define REFCATDATA_H #include #include class RefCatData : public QObject { Q_OBJECT public: explicit RefCatData(QString refcatname, QObject *parent = nullptr); QVector ra; QVector de; QVector mag1; QVector mag2; QVector mag3; QVector mag4; QVector mag5; long numRefSources = 0; long numG2Sources = 0; QString name = ""; QString resultString = ""; void clear(); signals: public slots: }; #endif // REFCATDATA_H THELI-3.1.3/src/colorpicture/subtaskColorcalib.cc000066400000000000000000000471631417631501300216550ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include #include #include #include #include #include #include #include void ColorPicture::on_calibratePushButton_clicked() { photcatresult[0].catname = "PANSTARRS"; photcatresult[1].catname = "SDSS"; photcatresult[2].catname = "SKYMAPPER"; photcatresult[3].catname = "ATLAS-REFCAT2"; photcatresult[4].catname = "AVGWHITE"; ui->redFactorLineEdit->setText(""); ui->greenFactorLineEdit->setText("1.000"); ui->blueFactorLineEdit->setText(""); ui->redErrorLineEdit->setText(""); ui->greenErrorLineEdit->setText("0.000"); ui->blueErrorLineEdit->setText(""); if (ui->DTLineEdit->text().isEmpty()) ui->DTLineEdit->setText("3.0"); if (ui->DMINLineEdit->text().isEmpty()) ui->DMINLineEdit->setText("5.0"); QDir colorCalibDir(mainDir+"/color_theli/PHOTCAT_calibration/"); if (! colorCalibDir.exists()) { if (!colorCalibDir.mkdir(mainDir+"/color_theli/PHOTCAT_calibration/")) { emit messageAvailable("Could not create
"+mainDir+"/color_theli/PHOTCAT_calibration/", "error"); return; } } ui->calibratePushButton->setText("Running ..."); ui->calibratePushButton->setDisabled(true); ui->redComboBox->setDisabled(true); ui->greenComboBox->setDisabled(true); ui->blueComboBox->setDisabled(true); resetResultButtonGroup("alsoResetLabels"); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "ColorCalib"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalColorCalib() { // get platescale if (croppedList.isEmpty()) return; croppedList.at(0)->loadHeader(); // get access to platescale and radius QList queryList; if (croppedList.at(0)->plateScale > 3. || croppedList.at(0)->radius > 1.5) { queryList = {ATLASquery}; ui->resultPANSTARRSPushButton->setDisabled(true); ui->resultSDSSPushButton->setDisabled(true); ui->resultSKYMAPPERPushButton->setDisabled(true); ui->numPANSTARRSLabel->setText("0 stars"); ui->numSDSSLabel->setText("0 stars"); ui->numSKYMAPPERLabel->setText("0 stars"); emit messageAvailable("PANSTARRS, SDSS and SKYMAPPER queries deactivated, field of view is too large.", "warning"); } else { queryList = {PANSTARRSquery, SDSSquery, SKYMAPPERquery, ATLASquery}; } // Retrieve the photometric reference catalogs and identify solar type analogs // nested parallelism within colorCalibSegmentImages(); #pragma omp parallel sections { #pragma omp section { // Detect sources in all images colorCalibSegmentImages(); } #pragma omp section { // retrieve catalogs colorCalibRetrieveCatalogs(queryList); // Extract solar analogs filterSolarTypeStars(queryList); } } // } //#pragma omp section // { // } // } // Match the object catalogs with the reference catalogs, and calculate the various correction factors colorCalibMatchCatalogs(); } void ColorPicture::colorCalibMatchCatalogs() { emit messageAvailable("Matching object and reference catalogs ...", "ignore"); MyImage *imageR = identifyCroppedMyImage(ui->redComboBox->currentText()); MyImage *imageG = identifyCroppedMyImage(ui->greenComboBox->currentText()); MyImage *imageB = identifyCroppedMyImage(ui->blueComboBox->currentText()); if (imageR == nullptr || imageG == nullptr || imageB == nullptr) { emit messageAvailable("Could not identify the three RGB channel images!", "error"); return; } QVector> objDatR = getObjectData(imageR); QVector> objDatG = getObjectData(imageG); QVector> objDatB = getObjectData(imageB); // Match R with G int multipleR = 0; int multipleG = 0; int multipleB = 0; double toleranceRG = (imageR->matchingTolerance + imageG->matchingTolerance) / 2.; // upper cap of 1.5 pixels if (toleranceRG*3600/imageR->plateScale > 2.0) toleranceRG = 1.5*imageR->plateScale/3600.; QVector> matchedRG; // if filter order is changed, must update rCorr and bCorr below! match2D(objDatR, objDatG, matchedRG, toleranceRG, multipleR, multipleG, 0); // Match R+G with B double toleranceRB = (imageR->matchingTolerance + imageB->matchingTolerance) / 2.; // upper cap of 1.5 pixels if (toleranceRB*3600/imageR->plateScale > 2.0) toleranceRB = 1.5*imageR->plateScale/3600.; // print matching radius in pixels // qDebug() << imageR->matchingTolerance*3600/imageR->plateScale << imageG->matchingTolerance*3600/imageG->plateScale << imageB->matchingTolerance*3600/imageB->plateScale; QVector> matchedRGB; match2D(matchedRG, objDatB, matchedRGB, toleranceRB, multipleR, multipleB, maxCPU); QString meanTol = QString::number(0.5*(toleranceRB+toleranceRG)*3600,'f',1) + "\" (" + QString::number(0.5*(toleranceRB+toleranceRG)*3600/imageB->plateScale,'f',1) + " pix)"; if (verbosity >= 2) emit messageAvailable("RGB mean matching tolerances: " + meanTol, "ignore"); if (verbosity >= 2) emit messageAvailable("RGB # of matched sources: " + QString::number(matchedRGB.length()), "ignore"); // Extract AVGWHITE color correction factors QVector rCorr; // red correction factors wrt. green channel QVector bCorr; // blue correction factors wrt. green channel rCorr.clear(); bCorr.clear(); rCorr.reserve(matchedRGB.length()); bCorr.reserve(matchedRGB.length()); for (auto &obj : matchedRGB) { // 'obj' contains RA, DEC, flux_b, flux_g, flux_r // CAREFUL: mag order depends on which filter is loaded into match2D as source and which one as reference rCorr.append(obj[3] / obj[4]); bCorr.append(obj[3] / obj[2]); } double num = rCorr.length(); // copy result for AVGWHITE into photcatresult int nrefcat = 4; photcatresult[nrefcat].rfac = QString::number(medianMask_T(rCorr),'f',3); photcatresult[nrefcat].rfacerr = QString::number(medianerrMask(rCorr) / sqrt(num),'f',3); photcatresult[nrefcat].gfac = "1.000"; photcatresult[nrefcat].gfacerr = "0.000"; photcatresult[nrefcat].bfac = QString::number(medianMask_T(bCorr),'f',3); photcatresult[nrefcat].bfacerr = QString::number(medianerrMask(bCorr) / sqrt(num),'f',3); photcatresult[nrefcat].nstars = QString::number(num); emit updateNrefStars("AVGWHITE", rCorr.length()); // Match with reference catalogs // TODO: take into account proper motions double toleranceRGB = (imageR->matchingTolerance + imageG->matchingTolerance + imageB->matchingTolerance) / 3.; filterReferenceCatalog(PANSTARRS, imageG); colorCalibMatchReferenceCatalog(matchedRGB, PANSTARRS, toleranceRGB); filterReferenceCatalog(SDSS, imageG); colorCalibMatchReferenceCatalog(matchedRGB, SDSS, toleranceRGB); filterReferenceCatalog(SKYMAPPER, imageG); colorCalibMatchReferenceCatalog(matchedRGB, SKYMAPPER, toleranceRGB); filterReferenceCatalog(ATLAS, imageG); colorCalibMatchReferenceCatalog(matchedRGB, ATLAS, toleranceRGB); } // Remove objects outside the actual field of view (simply for clarity) // We need to test a single exposure, only. Does not matter whether it is the red, green or blue channel void ColorPicture::filterReferenceCatalog(RefCatData *REFCAT, MyImage *channelImage) { long countG2inside = 0; for (int i=0; ira.length(); ++i) { // is the reference source within the FITS image? if (channelImage->containsRaDec(REFCAT->ra[i], REFCAT->de[i])) { // if yes, is it covered by valid pixels (rejecting empty image borders) double x = 0.; double y = 0.; channelImage->sky2xy(REFCAT->ra[i], REFCAT->de[i], x, y); long n = channelImage->naxis1; if (channelImage->dataCurrent[x + n * y] != 0.) ++countG2inside; } } if (REFCAT->ra.length() > 0) { REFCAT->resultString = REFCAT->name + " : " + QString::number(countG2inside) + " G2 references inside image"; } } void ColorPicture::colorCalibMatchReferenceCatalog(const QVector> &matchedRGB, RefCatData *REFCAT, float tolerance) { int index = 0; if (REFCAT->name == "PANSTARRS") index = 0; else if (REFCAT->name == "SDSS") index = 1; else if (REFCAT->name == "SKYMAPPER") index = 2; else if (REFCAT->name == "ATLAS-REFCAT2") index = 3; if (matchedRGB.isEmpty() || REFCAT->ra.isEmpty()) { photcatresult[index].rfac = "1.000"; photcatresult[index].rfacerr = "0.000"; photcatresult[index].gfac = "1.000"; photcatresult[index].gfacerr = "0.000"; photcatresult[index].bfac = "1.000"; photcatresult[index].bfacerr = "0.000"; photcatresult[index].nstars = "0"; QString nstars = "0 stars"; if (REFCAT->ra.isEmpty()) { if (REFCAT->name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (REFCAT->name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (REFCAT->name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (REFCAT->name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); } return; } QVector> refDat; QVector> matchedREFCAT; int dummy1; int dummy2; for (int i=0; ira.length(); ++i) { QVector refdata; // Add the two coords, and a dummy magnitude of 0.0 (required by match2D algorithm) refdata << REFCAT->de[i] << REFCAT->ra[i] << 0.0; refDat.append(refdata); } match2D(matchedRGB, refDat, matchedREFCAT, tolerance, dummy1, dummy2, maxCPU); if (matchedREFCAT.isEmpty()) { emit messageAvailable("None of the G2-like sources in " + REFCAT->name + " were detected.", "warning"); photcatresult[index].rfac = "1.000"; photcatresult[index].rfacerr = "0.000"; photcatresult[index].gfac = "1.000"; photcatresult[index].gfacerr = "0.000"; photcatresult[index].bfac = "1.000"; photcatresult[index].bfacerr = "0.000"; photcatresult[index].nstars = "0"; writeG2refcat(REFCAT->name, matchedREFCAT); QString nstars = "0 stars"; if (REFCAT->name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (REFCAT->name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (REFCAT->name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (REFCAT->name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); return; } // Calculate the color correction factors // matchRGB contains magnitudes in the order BGR, i.e. matchREFCAT contains: magref-B-G-R QVector rCorr; // red correction factors wrt. green channel QVector bCorr; // cblue orrection factors wrt. green channel rCorr.reserve(matchedREFCAT.length()); bCorr.reserve(matchedREFCAT.length()); for (auto &obj : matchedREFCAT) { // 'obj' contains RA, DEC, 0.0, flux_b, flux_g, flux_r // 0.0 is the dummy magnitude rCorr.append(obj[4] / obj[5]); bCorr.append(obj[4] / obj[3]); } photcatresult[index].rfac = QString::number(meanMask_T(rCorr),'f',3); photcatresult[index].rfacerr = QString::number(rmsMask_T(rCorr),'f',3); photcatresult[index].gfac = "1.000"; photcatresult[index].gfacerr = "0.000"; photcatresult[index].bfac = QString::number(meanMask_T(bCorr),'f',3); photcatresult[index].bfacerr = QString::number(rmsMask_T(bCorr),'f',3); photcatresult[index].nstars = QString::number(rCorr.length()); writeG2refcat(REFCAT->name, matchedREFCAT); QString nstars = QString::number(matchedREFCAT.length()) + " stars"; if (REFCAT->name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (REFCAT->name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (REFCAT->name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (REFCAT->name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); else if (REFCAT->name == "AVGWHITE") ui->numAVGWHITELabel->setText(nstars); QString type = "note"; if (matchedREFCAT.length() == 0) { REFCAT->resultString = REFCAT->name + " : None of the G2 references were detected in the image."; type = "warning"; } else { REFCAT->resultString.append(", " +QString::number(matchedREFCAT.length()) + " of which detected."); } emit messageAvailable(REFCAT->resultString, type); } void ColorPicture::writeG2refcat(const QString refcatName, const QVector> matchedREFCAT) { // The iView catalog (ASCII) QString outpath = mainDir+"/color_theli/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); QFile outcat_iview(outpath+"/PHOTCAT_calibration/PHOTCAT_sources_matched_"+refcatName+".iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable(QString(__func__) + ": ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit criticalReceived(); return; } // Write iView catalog for (auto &source : matchedREFCAT) { // RA first, then DEC! (matching is done with DEC in first column) stream_iview << QString::number(source[1], 'f', 9) << " " << QString::number(source[0], 'f', 9) << "\n"; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); } void ColorPicture::colorCalibRetrieveCatalogs(QList queryList) { emit messageAvailable("Querying reference sources, this may take a while ...", "ignore"); // Collector for meta data from the queries QStringList queryResult; for (int i=0; iphotomDir = ui->dirLineEdit->text() + "/color_theli/"; query->photomImage = croppedList[0]; query->doColorCalibQueryFromWeb(); query->identifySolarTypeStars(); QString info = "G2 sources " + query->refcatName + " : " + QString::number(query->numG2sources) + " (out of : " + QString::number(query->numSources) + ")"; queryResult[i] = info; emit messageAvailable(info, "append"); // emit updateNrefStars(query->refcatName, query->numG2sources); } } void ColorPicture::filterSolarTypeStars(QList queryList) { PANSTARRS->clear(); SDSS->clear(); SKYMAPPER->clear(); ATLAS->clear(); for (auto &query : queryList) { if (query->numSources == 0) continue; for (long k=0; kmag1_out.length(); ++k) { if (!query->G2type[k]) continue; if (query->refcatName == "PANSTARRS") { PANSTARRS->ra.append(query->ra_out[k]); PANSTARRS->de.append(query->de_out[k]); } if (query->refcatName == "SDSS") { SDSS->ra.append(query->ra_out[k]); SDSS->de.append(query->de_out[k]); } if (query->refcatName == "SKYMAPPER") { SKYMAPPER->ra.append(query->ra_out[k]); SKYMAPPER->de.append(query->de_out[k]); } if (query->refcatName == "ATLAS-REFCAT2") { ATLAS->ra.append(query->ra_out[k]); ATLAS->de.append(query->de_out[k]); } } } } void ColorPicture::colorCalibSegmentImages() { emit messageAvailable("Detecting sources ...", "ignore"); // Create object catalogs, get matching tolerance QString DT = ui->DTLineEdit->text(); QString DMIN = ui->DMINLineEdit->text(); #pragma omp parallel for num_threads(maxCPU) // ignored since we run it in a parallel section for (int i=0; iname != ui->redComboBox->currentText() && it->name != ui->greenComboBox->currentText() && it->name != ui->blueComboBox->currentText()) { continue; } // Do nothing if we have the catalog already if (it->segmentationDone) continue; // Obtain catalog // emit messageAvailable("Detecting sources in " + it->baseName +" ...", "ignore"); it->maxCPU = maxCPU / croppedList.length(); // TODO: introduce a 90% dynrange cutoff to avoid saturated sources it->resetObjectMasking(); it->readImage(it->path + "/" +it->name); it->readWeight(); it->backgroundModel(100, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->estimateMatchingTolerance(); it->matchingTolerance *= 3.; it->releaseBackgroundMemory(); it->releaseDetectionPixelMemory(); QString channelName = ""; if (it->name == ui->redComboBox->currentText()) channelName = "R"; if (it->name == ui->greenComboBox->currentText()) channelName = "G"; if (it->name == ui->blueComboBox->currentText()) channelName = "B"; if (verbosity >= 2) emit messageAvailable(channelName + " : " + QString::number(it->objectList.length()) + " sources", "ignore"); } } void ColorPicture::updateNrefStarsReceived(QString name, long number) { QString nstars = QString::number(number) + " stars"; if (name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); else if (name == "AVGWHITE") ui->numAVGWHITELabel->setText(nstars); } THELI-3.1.3/src/colorpicture/subtaskCropcoadd.cc000066400000000000000000000236361417631501300215010ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include #include #include #include #include #include #include #include void ColorPicture::on_getCoaddsPushButton_clicked() { // FIRST, fetch the selected images. This is fast because we link only, and hence we don't need an external thread. QItemSelectionModel *selectionModel = ui->coaddDirListView->selectionModel(); QStringList list = coaddDirModel->stringList(); QStringList imageList; QString dirName = ui->dirLineEdit->text(); for (int i=0; icoaddDirListView->model()->rowCount(); ++i) { QModelIndex index = ui->coaddDirListView->model()->index(i,0); if (selectionModel->isSelected(index)) imageList.append(list.at(i)); } // Stop if no images were selected if (imageList.length() < 2) { emit messageAvailable("At least two images must be chosen from the list of coadded images.", "warning"); return; } emit messageAvailable("Linking selected coadded images to "+dirName+"/color_theli/", "info"); QPalette palette; palette.setColor(QPalette::Base,QColor("#a9ffe6")); ui->getCoaddsPushButton->setText("Running ..."); ui->getCoaddsPushButton->setPalette(palette); ui->getCoaddsPushButton->setDisabled(true); QTest::qWait(50); // Create the directory containing the images QDir colorTheli(dirName+"/color_theli"); if (colorTheli.exists()) { colorTheli.rename(dirName+"/color_theli", dirName+"/color_theli_"+QDateTime::currentDateTime().toString(Qt::ISODate)); } colorTheli.mkdir(dirName+"/color_theli"); // Link the images QString coaddImageName; QString coaddWeightName; QFile coaddImage; QFile coaddWeight; QString identifier; QStringList coaddImageList; for (auto &it : imageList) { if (it.contains("coadd_")) { identifier = it.split("coadd_").at(1); } else continue; coaddImageName = dirName+"/"+it+"/coadd.fits"; coaddWeightName = dirName+"/"+it+"/coadd.weight.fits"; coaddImage.setFileName(coaddImageName); coaddWeight.setFileName(coaddWeightName); if (coaddImage.exists()) { coaddImage.link(dirName+"/color_theli/"+identifier+".fits"); coaddImageList.append(identifier+".fits"); // populate the coaddImage listView coaddImageModel->setStringList(coaddImageList); } if (coaddWeight.exists()) coaddWeight.link(dirName+"/color_theli/"+identifier+".weight.fits"); } coaddImageModel->sort(0); // Next, crop the images to their maximum overlap // Reset the button now, so we don't have to do it from within another thread buttonPalette = ui->getCoaddsPushButton->palette(); ui->getCoaddsPushButton->setText("Cropping images, please wait ..."); ui->getCoaddsPushButton->setDisabled(true); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "CropCoadds"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalCropCoadds() { if (verbosity <= 1) emit messageAvailable("Cropping images ...", "ignore"); QString dirName = ui->dirLineEdit->text() + "/color_theli/"; QDir colorTheli(dirName); QStringList filter("*.fits"); QStringList imageList = colorTheli.entryList(filter); coaddList.clear(); for (auto &it : imageList) { QVector dummyMask; dummyMask.clear(); MyImage *myImage = new MyImage(dirName+it, dummyMask, &verbosity); connect(myImage, &MyImage::messageAvailable, this, &ColorPicture::displayMessage); connect(myImage, &MyImage::critical, this, &ColorPicture::criticalReceived); // WCSlock not necessary, as the corresponding initWCS() call is inside a critical section // Besides, the following line stalls the execution of the cropping, because the unlocking signal apparently never gets received ... // connect(myImage, &MyImage::setWCSLock, this, &ColorPicture::setWCSLockReceived, Qt::DirectConnection); myImage->globalMaskAvailable = false; myImage->maxCPU = maxCPU / imageList.length(); myImage->loadHeader(); coaddList.append(myImage); } // for consistency checks QVector crval1; QVector crval2; QVector cd11; QVector cd12; QVector cd21; QVector cd22; int length = coaddList.length(); for (int i=0; iwcs->crval[0]; crval2 << it->wcs->crval[1]; cd11 << it->wcs->cd[0]; cd12 << it->wcs->cd[1]; cd21 << it->wcs->cd[2]; cd22 << it->wcs->cd[3]; } if (numberOfDuplicates_T(crval1) != length - 1 || numberOfDuplicates_T(crval2) != length - 1 || numberOfDuplicates_T(cd11) != length - 1 || numberOfDuplicates_T(cd12) != length - 1 || numberOfDuplicates_T(cd21) != length - 1 || numberOfDuplicates_T(cd22) != length - 1) { emit messageAvailable("The coadditions do not share the same astrometric projection. You must use identical reference coordinates when creating the coadditions.", "error"); emit messageAvailable("Done.", "info"); return; } QVector crpix1; QVector crpix2; QVector naxis1; QVector naxis2; QVector d1; QVector d2; for (int i=0; iwcs->crpix[0]; crpix2 << it->wcs->crpix[1]; naxis1 << it->naxis1; naxis2 << it->naxis2; d1 << it->naxis1 - it->wcs->crpix[0]; d2 << it->naxis2 - it->wcs->crpix[1]; } float xlow = -1.*minVec_T(crpix1); float ylow = -1.*minVec_T(crpix2); float xhigh = minVec_T(d1); float yhigh = minVec_T(d2); CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(); #pragma omp parallel for num_threads(maxCPU) for (int i=0; i= 2) emit messageAvailable("Cropping "+it->name, "ignore"); // crop image float xlowNew = xlow + crpix1[i]; float ylowNew = ylow + crpix2[i]; float xhighNew = xhigh + crpix1[i] - 1; float yhighNew = yhigh + crpix2[i] - 1; QString tmpName = it->name; QString name; if (it->name.contains(".weight.fits")) { tmpName.remove(".weight.fits"); name = tmpName + "_cropped.weight.fits"; it->baseName = tmpName + "_cropped.weight.fits"; } else { name = it->baseName + "_cropped.fits"; } it->readImage(it->path+"/"+it->name); it->makeCutout(xlowNew, xhighNew, ylowNew, yhighNew); it->writeImage(dirName + name); it->name = name; // update fits header int status = 0; float crpix1New = crpix1[i] - xlowNew + 1; float crpix2New = crpix2[i] - ylowNew + 1; fitsfile *fptr = nullptr; fits_open_file(&fptr, (dirName+name).toUtf8().data(), READWRITE, &status); fits_update_key_flt(fptr, "CRPIX1", crpix1New, 6, nullptr, &status); fits_update_key_flt(fptr, "CRPIX2", crpix2New, 6, nullptr, &status); fits_close_file(fptr, &status); QString code = errorCodes->errorKeyMap.value(status); if (status) { emit messageAvailable("CFITSIO: Could not update CRPIX keywords in "+name+":
"+code, "error"); } } delete errorCodes; errorCodes = nullptr; // Prepare for segmentation // Move the cropped weights over into the cropped coadd croppedList.clear(); for (auto &coadd : coaddList) { if (coadd->name.contains("weight.fits")) continue; QString baseCoadd = coadd->name; baseCoadd.remove("_cropped.fits"); for (auto &weight : coaddList) { if (!weight->name.contains("weight.fits")) continue; QString baseWeight = weight->name; baseWeight.remove("_cropped.weight.fits"); if (baseCoadd == baseWeight) { coadd->dataWeight.swap(weight->dataCurrent); coadd->weightInMemory = true; coadd->globalMaskAvailable = false; croppedList.append(coadd); } } } emit messageAvailable("Done.", "info"); } THELI-3.1.3/src/colorpicture/subtaskbbnb.cc000066400000000000000000000221531417631501300204770ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../instrumentdata.h" #include "../preferences.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include #include #include #include #include #include void ColorPicture::on_getRatioPushButton_clicked() { ui->filterRatioLineEdit->setText(""); QDir colorCalibDir(mainDir+"/color_theli/PHOTCAT_calibration/"); if (! colorCalibDir.exists()) { if (!colorCalibDir.mkdir(mainDir+"/color_theli/PHOTCAT_calibration/")) { emit messageAvailable("Could not create "+mainDir+"/color_theli/PHOTCAT_calibration/", "error"); return; } } ui->getRatioPushButton->setText("Running ..."); ui->getRatioPushButton->setDisabled(true); ui->narrowbandComboBox->setDisabled(true); ui->broadbandComboBox->setDisabled(true); ui->BBNBcombinePushButton->setDisabled(true); QTest::qWait(50); QString n_image = ui->narrowbandComboBox->currentText(); QString b_image = ui->broadbandComboBox->currentText(); // leave conditions if (n_image == b_image) { emit messageAvailable("You must choose different images to combine.", "warning"); ui->getRatioPushButton->setText("Estimate flux ratio"); ui->getRatioPushButton->setEnabled(true); ui->narrowbandComboBox->setEnabled(true); ui->broadbandComboBox->setEnabled(true); ui->BBNBcombinePushButton->setEnabled(true); return; } workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "BBNBratio"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalBBNBratio() { MyImage *bbImage = identifyCroppedMyImage(ui->broadbandComboBox->currentText()); MyImage *nbImage = identifyCroppedMyImage(ui->narrowbandComboBox->currentText()); if (bbImage == nullptr || nbImage == nullptr) return; // This should never happen QList bbnbList; bbnbList << bbImage << nbImage; // Create object catalogs #pragma omp parallel for num_threads(maxCPU) for (int i=0; isegmentationDone) continue; // Obtain catalog emit messageAvailable("Detecting sources in " + it->baseName +" ...", "ignore"); it->maxCPU = maxCPU / bbnbList.length(); it->resetObjectMasking(); it->readImage(it->path+"/"+it->name); it->readWeight(); it->backgroundModel(100, "interpolate"); it->segmentImage("5", "5", true, true); it->estimateMatchingTolerance(); it->releaseBackgroundMemory(); it->releaseDetectionPixelMemory(); } emit messageAvailable("Matching broadband and narrowband catalogs ...", "ignore"); QVector> objDataBB = getObjectData(bbImage); QVector> objDataNB = getObjectData(nbImage); QVector> matched; float tolerance = (bbImage->matchingTolerance + nbImage->matchingTolerance) / 2.; int dummy1; int dummy2; match2D(objDataNB, objDataBB, matched, tolerance, dummy1, dummy2, maxCPU); // Calculate mean flux ratio QVector fluxRatios; // compute flux_narrowband / flux_broadband fluxRatios.reserve(matched.length()); for (auto &obj : matched) { // Skip objects with negative fluxes (could be OK though if background is oversubtracted) // CAREFUL: ORDER in 'obj': RA DE FLUX_BB FLUX_NB // match2D inserts the properties of the reference catalog 'in between' if (obj[2] <= 0. || obj[3] <= 0.) continue; fluxRatios.append(obj[3] / obj[2]); } if (fluxRatios.length() <= 1) { bbnbFluxRatio = 1.0; bbnbFluxRatioError = 0.0; } bbnbFluxRatio = straightMedian_T(fluxRatios); bbnbFluxRatioError = rmsMask_T(fluxRatios) / sqrt(fluxRatios.length()); emit messageAvailable("Done.", "info"); } void ColorPicture::on_BBNBcombinePushButton_clicked() { QString BBimage = ui->broadbandComboBox->currentText(); QString NBimage = ui->narrowbandComboBox->currentText(); // leave conditions if (BBimage == NBimage) { emit messageAvailable("You must choose two different images for this task.", "warning"); ui->getRatioPushButton->setText("Estimate flux ratio"); ui->getRatioPushButton->setEnabled(true); ui->narrowbandComboBox->setEnabled(true); ui->broadbandComboBox->setEnabled(true); ui->BBNBcombinePushButton->setEnabled(true); return; } ui->BBNBcombinePushButton->setText("Running..."); ui->BBNBcombinePushButton->setDisabled(true); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "BBNBcombine"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalBBNBcombine() { MyImage *bbImage = identifyCroppedMyImage(ui->broadbandComboBox->currentText()); MyImage *nbImage = identifyCroppedMyImage(ui->narrowbandComboBox->currentText()); if (bbImage == nullptr || nbImage == nullptr) return; // This should never happen emit messageAvailable("Combining narrowband and broadband images into: " +bbImage->baseName + nbImage->baseName + "_cropped.fits", "ignore"); long n = bbImage->naxis1; long m = bbImage->naxis2; QString path = bbImage->path + "/"; QVector dummyMask; dummyMask.clear(); QString newName = bbImage->baseName + nbImage->baseName + "_cropped.fits"; QString newNameWeight = bbImage->baseName + nbImage->baseName + "_cropped.weight.fits"; MyImage *combinedImage = new MyImage(path, bbImage->name, "", 1, dummyMask, &verbosity); MyImage *combinedWeight = new MyImage(path, bbImage->name, "", 1, dummyMask, &verbosity); combinedImage->loadHeader(); combinedWeight->loadHeader(); // Compute and write the combined image as follows: // newImage = (1 - weight * width(NB) / width(BB)) * BB + weight * NB; float weight = ui->narrowbandWeightLineEdit->text().toFloat(); if (ui->narrowbandWeightLineEdit->text().isEmpty()) weight = 1.0; float scale = 1. - weight * bbnbFluxRatio; combinedImage->baseName = bbImage->baseName + nbImage->baseName; combinedImage->name = bbImage->baseName + nbImage->baseName + "_cropped.fits"; combinedImage->weightPath = combinedImage->path; combinedImage->weightName = bbImage->baseName + nbImage->baseName + "_cropped.weight"; combinedImage->dataCurrent.resize(n*m); combinedWeight->dataCurrent.resize(n*m); for (long i=0; idataCurrent[i] = scale * bbImage->dataCurrent[i] + weight * nbImage->dataCurrent[i]; combinedWeight->dataCurrent[i] = bbImage->dataWeight[i] + nbImage->dataWeight[i]; } combinedImage->writeImage(path+newName); combinedWeight->writeImage(path+newNameWeight); emit addCombinedImage(combinedImage); emit messageAvailable("Done.", "info"); delete combinedWeight; combinedWeight = nullptr; } THELI-3.1.3/src/colorpicture/subtaskfits2tiff.cc000066400000000000000000000154601417631501300214770ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include "tiffio.h" #include #include #include #include #include #include void ColorPicture::on_createTiffPushButton_clicked() { ui->createTiffPushButton->setText("Running ..."); ui->createTiffPushButton->setDisabled(true); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "Fits2Tiff"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalFits2Tiff() { int nrows = ui->statisticsTableWidget->rowCount(); int ncols = ui->statisticsTableWidget->columnCount(); // Leave if the table hasn't been initialized if (ncols != 5 || !statisticsRetrieved) { emit messageAvailable("You must first determine the background level.", "warning"); return; } QString bfac = ui->blueFactorLineEdit->text(); QString rfac = ui->redFactorLineEdit->text(); if (bfac.isEmpty()) bfac = "1.0"; if (rfac.isEmpty()) rfac = "1.0"; // retrieve the black and white points for the RGB channels (must have the same range) float maxMax = 0.; float minMin = 0.; float rescale = 1.0; for (int i=0; istatisticsTableWidget->item(i,0)->data(Qt::DisplayRole).toString(); float min = ui->statisticsTableWidget->item(i,3)->data(Qt::DisplayRole).toFloat(); float max = ui->statisticsTableWidget->item(i,4)->data(Qt::DisplayRole).toFloat(); if (name == ui->redComboBox->currentText()) rescale = rfac.toFloat(); if (name == ui->blueComboBox->currentText()) rescale = bfac.toFloat(); // Clip only the RGB images to the same min/max values if (name == ui->redComboBox->currentText() || name == ui->greenComboBox->currentText() || name == ui->blueComboBox->currentText()) { if (rescale*max > maxMax) maxMax = rescale*max; if (rescale*min < minMin) minMin = rescale*min; } } // Convert FITS to TIFF #pragma omp parallel for num_threads(maxCPU) for (int i=0; iindex(i,0).data().toString(); MyImage *myImage = identifyCroppedMyImage(name); if (myImage == nullptr) continue; float factor = 1.0; if (name == ui->redComboBox->currentText()) factor = ui->redFactorLineEdit->text().toFloat(); else if (name == ui->blueComboBox->currentText()) factor = ui->blueFactorLineEdit->text().toFloat(); else factor = 1.0; float medVal = ui->statisticsTableWidget->item(i,1)->data(Qt::DisplayRole).toFloat(); // Do the rescaling on a separate data vector myImage->dataTIFF = myImage->dataCurrent; myImage->subtract(medVal, "TIFF"); myImage->multiply(factor, "TIFF"); myImage->toTIFF(16, minMin, maxMax); myImage->writeImageTIFF(myImage->path + "/"+myImage->baseName + "_2tiff.fits"); emit messageAvailable("Wrote " + myImage->path + "/"+myImage->baseName + ".tiff", "ignore"); myImage->dataTIFF.clear(); myImage->dataTIFF.squeeze(); } } // Implementation not finished. void ColorPicture::writeRGBTIFF(QVector &R, QVector &G, QVector &B, long n, long m, float min, float max, QString path) { emit messageAvailable("Creating RGB.tiff ...", "ignore"); // Clipping min and max values QVector> RGBlist; RGBlist << R << G << B; #pragma omp parallel for for (int i=0; i<3; ++i) { for (auto &pixel : RGBlist[i]) { if (pixel <= min) pixel = min; if (pixel >= max) pixel = max; } } float grey = 0.; // inactive grey = grey / 100. * 65000.; float blowup = (65000. - grey) / (max - min); std::vector< std::vector > imtiff(n); for (long i=0; i #include #include bool MainWindow::areAllPathsValid() { bool test = checkPathsLineEdit(ui->setupBiasLineEdit); test = test && checkPathsLineEdit(ui->setupDarkLineEdit); test = test && checkPathsLineEdit(ui->setupFlatoffLineEdit); test = test && checkPathsLineEdit(ui->setupFlatLineEdit); test = test && checkPathsLineEdit(ui->setupScienceLineEdit); test = test && checkPathsLineEdit(ui->setupSkyLineEdit); test = test && checkPathsLineEdit(ui->setupStandardLineEdit); return test; } bool MainWindow::checkMultipledirConsistency(QString mode) { int nbias = datadir2StringList(ui->setupBiasLineEdit).length(); int ndark = datadir2StringList(ui->setupDarkLineEdit).length(); int nflatoff = datadir2StringList(ui->setupFlatoffLineEdit).length(); int nflat = datadir2StringList(ui->setupFlatLineEdit).length(); int nscience = datadir2StringList(ui->setupScienceLineEdit).length(); int nsky = datadir2StringList(ui->setupSkyLineEdit).length(); int nstandard = datadir2StringList(ui->setupStandardLineEdit).length(); int ncorr; // can represent various calibrators if (mode == "HDUreformat") return true; if (mode == "ProcessBias") return true; if (mode == "ProcessDark") return true; // Flat processing (and a few other checks so we don't have to repeat them) bool flatcheck = false; if (mode == "ProcessFlat" || mode == "ProcessScience" || mode == "ProcessSky" || mode == "ProcessStandard") { // Check if we have a consistent setup to process the flats // flatoff takes precedence over bias if both are defined: if (nflatoff > 0 && nbias > 0) ncorr = nflatoff; else if (nflatoff > 0 && nbias == 0) ncorr = nflatoff; else { // (nflatoff == 0 && nbias > 0 or both == 0) ncorr = nbias; } // Now check if the setup is consistent: if (nflat == ncorr) flatcheck = true; else if (nflat > 1 && ncorr <= 1) flatcheck = true; else flatcheck = false; if (mode == "ProcessFlat") { if (flatcheck) return true; else { message(ui->plainTextEdit, "STOP: Inconsistent number of directories for FLAT processing."); return false; } } } if ((mode == "ProcessScience" || mode == "ProcessBackground") && nsky > 0) { if (nscience != nsky && nsky != 1) { message(ui->plainTextEdit, "STOP: Inconsistent number of SKY directories for SCIENCE."); message(ui->plainTextEdit, "Must be equal to that of SCIENCE, or one."); return false; } } if (mode == "ProcessScience" || mode == "ProcessSky" || mode == "ProcessStandard") { if (mode == "ProcessSky") nscience = nsky; if (mode == "ProcessStandard") nscience = nstandard; // We have checked the consistency for flat processing. if (!flatcheck) { message(ui->plainTextEdit, "STOP: Inconsistent number of directories for FLAT processing."); return false; } // If darks were specified, then they take precedence over biases! if ( ndark > 0 && nbias > 0) ncorr = ndark; else if (ndark > 0 && nbias == 0) ncorr = ndark; else { // ndark == 0 && nbias > 0 or both == 0 ncorr = nbias; } // What remains is to check the consistency science -> flat and science ->bias/dark // where 'science' can also be 'sky' or 'standard' if (nscience == nflat && nscience == ncorr) return true; else if (nscience > 1 && nflat <= 1 && ncorr <= 1) return true; else if (nscience > 1 && nflat <= 1 && ncorr == nscience) return true; else if (nscience > 1 && nflat == nscience && ncorr <= 1) return true; else { if (mode == "ProcessScience") message(ui->plainTextEdit, "STOP: Inconsistent number of directories for SCIENCE processing."); if (mode == "ProcessSky") message(ui->plainTextEdit, "STOP: Inconsistent number of directories for SKY processing."); if (mode == "ProcessStandard") message(ui->plainTextEdit, "STOP: Inconsistent number of directories for STANDARD processing."); // should we set the 'stop' flag here? return false; } } // In all other cases (later on during processing) we don't care anymore, hence: return true; } void MainWindow::hasDirCurrentData(DataDir *datadir, bool &stop) { QString currentStatus = status.getStatusFromHistory(); // The task does not change the status string. We expect the status to be current if (!datadir->hasType(currentStatus)) { message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain expected images (*"+currentStatus+".fits)."); stop = true; } } QString MainWindow::estimateStatusFromFilename(DataDir *datadir) { // Get the name of a single fits file QStringList filterList("*.fits"); QDir dir(datadir->name); QStringList imageList = dir.entryList(filterList); QString image; if (!imageList.isEmpty()) image = imageList.at(0); // The image extension (e.g. A, or AB) image = getLastWord(image,'_').remove(".fits").remove(QRegExp("[0-9]{1,3}")); return image; } void MainWindow::check_taskHDUreformat(DataDir *datadir, bool &stop, bool &skip, const QString mode) { // if (datadir->isEmpty()) { // if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note"); // skip = true; // } if (datadir->hasType("P")) { if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' already contains HDU reformatted images. Skipping...", "note"); skip = true; } if (datadir->numEXT("PA*") > 0) { if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains preprocessed images. Skipping...", "note"); skip = true; } } void MainWindow::check_taskProcessbias(DataDir *datadir, bool &stop, bool &skip, const QString mode) { if (datadir->isEmpty()) { if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note"); skip = true; } if (!datadir->hasType("P") && !ui->applyHDUreformatCheckBox->isChecked()) { message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images."); stop = true; } if (!stop && datadir->numCHIP < 3 && !ui->applyHDUreformatCheckBox->isChecked()) { // message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'."); // stop = true; } } void MainWindow::check_taskProcessdark(DataDir *datadir, bool &stop, bool &skip, const QString mode) { if (datadir->isEmpty()) { if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note"); skip = true; } if (!datadir->hasType("P") && !ui->applyHDUreformatCheckBox->isChecked()) { message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images."); stop = true; } if (!stop && datadir->numCHIP < 3 && !ui->applyHDUreformatCheckBox->isChecked()) { // message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'."); // stop = true; } } void MainWindow::check_taskProcessflatoff(DataDir *datadir, bool &stop, bool &skip, const QString mode) { if (datadir->isEmpty()) { if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note"); skip = true; } if (!datadir->hasType("P") && !ui->applyHDUreformatCheckBox->isChecked()) { message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images."); stop = true; } if (!stop && datadir->numCHIP < 3 && !ui->applyHDUreformatCheckBox->isChecked()) { // message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'."); // stop = true; } } void MainWindow::check_taskProcessflat(DataDir *datadir, bool &stop, bool &skip, const QString mode) { if (datadir->isEmpty()) { if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note"); skip = true; } if (!datadir->hasType("P") && !ui->applyHDUreformatCheckBox->isChecked()) { message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images."); stop = true; } if (!stop && datadir->numCHIP < 2 && !ui->applyHDUreformatCheckBox->isChecked()) { // message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'."); // stop = true; } } void MainWindow::check_taskProcessscience(DataDir *datadir, bool &stop, bool &skip, const QString mode) { if (datadir->isEmpty()) { if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note"); skip = true; } if (!datadir->hasType("P") && !datadir->hasType("PA") && !ui->applyHDUreformatCheckBox->isChecked()) { message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images."); stop = true; } } void MainWindow::check_taskChopnod(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskBackground(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskCollapse(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskBinnedpreview(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskGlobalweight(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskIndividualweight(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskAbsphotindirect(DataDir *datadir, bool &stop, bool &skip, const QString mode) { QString standardDir = ui->setupStandardLineEdit->text(); if (standardDir.isEmpty()) { if (mode != "execute") message(ui->plainTextEdit, "No standard star directory was defined.", "stop"); stop = true; } } void MainWindow::check_taskSeparate(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskCreatesourcecat(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskAstromphotom(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskGetCatalogFromWEB(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskGetCatalogFromIMAGE(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskRestoreHeader(DataDir *datadir, bool &stop, bool &skip, const QString mode) { hasDirCurrentData(datadir, stop); // Check that original headers exist } void MainWindow::check_taskResolveTargetSidereal(DataDir *datadir, bool &stop, bool &skip, const QString mode) { QString target = cdw->ui->ARCtargetresolverLineEdit->text(); if (target.isEmpty()) { message(ui->plainTextEdit, "A target name must be provided for coordinate resolution.", "stop"); stop = true; cdw->ui->ARCraLineEdit->clear(); cdw->ui->ARCdecLineEdit->clear(); } } void MainWindow::check_taskSkysub(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } void MainWindow::check_taskCoaddition(DataDir *datadir, bool &stop, bool &skip, const QString mode) { } THELI-3.1.3/src/datadir.cc000066400000000000000000000105171417631501300150760ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "datadir.h" #include "functions.h" #include // Constructor DataDir::DataDir(QString data, QString main) { setPaths(data, main); } DataDir::DataDir() { name = ""; subdirname = ""; numFITS = 0; numCHIP = 0; } void DataDir::setPaths(QString data, QString main) { if (data.isEmpty()) { qDebug() << __func__ << ": sub-directory cannot be an empty string!"; return; } if (!main.isEmpty()) { QDir maindir(main); if (!maindir.exists()) { qDebug() << __func__ << ": main directory does not exist!"; return; } if (!maindir.isAbsolute()) { qDebug() << __func__ << ": main directory must be absolute!"; return; } } // If main was not provided but data contains a blank (e.g. MAINDIR SCIENCE) if (data.contains(" ")) { QStringList list = data.split(" "); main = list.at(0); data = list.at(1); } // Concatenate maindir and datadir, collapse multiple slashes etc name = QDir::cleanPath(main+"/"+data+"/"); subdirname = data; dir.setPath(name); if (dir.exists()) { QStringList fileList; // How many FITS files do we have in total QStringList filter; filter << "*.fits" << "*.fit" << "*.FIT" << "*.FITS" << "*.fits.fz" << "*.fit.fz" << "*.FIT.fz" << "*.FITS.fz"; dir.setNameFilters(filter); fileList = dir.entryList(); numFITS = fileList.length(); if (numFITS == 0) { // Check for RAW files instead filter.clear(); filter << "*.cr2" << "*.CR2" << "*.arw" << "*.ARW" << "*.dng" << "*.DNG" << "*.nef" << "*.NEF" << "*.pef" << "*.PEF"; dir.setNameFilters(filter); fileList = dir.entryList(); numFITS = fileList.length(); } // How many FITS files do we have a chip 1 (i.e., number of exposures) // (needed to create master calibrators) int chip = 1; QVector numExposures; while (chip <= numChips) { QStringList filterCHIP; filterCHIP << "*_"+QString::number(chip)+"P.fits"; dir.setNameFilters(filterCHIP); fileList = dir.entryList(); numExposures << fileList.length(); ++chip; } numCHIP = maxVec_T(numExposures); } else { numFITS = 0; numCHIP = 0; } } bool DataDir::hasMaster() { // This is to check if a BIAS, DARK etc directory already contains a master BIAS, DARK, etc QString cleanname = subdirname.remove("/"); QStringList filter; int chip = 1; while (chip <= numChips) { filter << cleanname+"_"+QString::number(chip)+".fits"; ++chip; } dir.setNameFilters(filter); QStringList fileList = dir.entryList(); if (fileList.length() > 1) { return true; } else { return false; } } bool DataDir::isEmpty() { if (numFITS == 0) { return true; } else { return false; } } bool DataDir::exists() { return dir.exists(); } long DataDir::numEXT(QString type) { // How many FITS files of a certain type do we have (e.g. "_*AB.fits") QStringList filter; filter << "*_*"+type+".fits"; dir.setNameFilters(filter); QStringList fileList = dir.entryList(); return fileList.length(); } bool DataDir::hasType(QString type) { // Do we have FITS files of a certain type (e.g. "_*AB.fits") QStringList filter; filter << "*_*"+type+".fits"; dir.setNameFilters(filter); QStringList fileList = dir.entryList(); if (fileList.length() > 0) { return true; } else { return false; } } THELI-3.1.3/src/datadir.h000066400000000000000000000022661417631501300147420ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef DATADIR_H #define DATADIR_H #include #include class DataDir { public: DataDir(QString data, QString main = ""); DataDir(); QString name; // the full path name QString subdirname; // the data subdir name alone QDir dir; bool exists(); long numFITS; long numCHIP; long numChips = 1; bool hasMaster(); bool isEmpty(); bool hasType(QString type); long numEXT(QString type); void setPaths(QString data, QString main = ""); }; #endif // DATADIR_H THELI-3.1.3/src/datamodel/000077500000000000000000000000001417631501300151055ustar00rootroot00000000000000THELI-3.1.3/src/datamodel/datamodel.cc000066400000000000000000000477621417631501300173660ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "datamodel.h" #include #include #include "../myimage/myimage.h" DataModel::DataModel(Data *someData, QObject *parent) : QAbstractTableModel(parent) { myData = someData; if (myData->dataType == "BIAS" || myData->dataType == "DARK" || myData->dataType == "FLATOFF" || myData->dataType == "FLAT") { modelType = "calib"; } else { if (myData->dataType == "GLOBALWEIGHT") modelType = "globalweight"; else modelType = "science"; } // Create the image list updateImageList(); connect(myData, &Data::modelUpdateNeeded, this, &DataModel::modelUpdateReceiver); connect(myData, &Data::globalModelUpdateNeeded, this, &DataModel::updateImageList); connect(myData, &Data::updateModelHeaderLine, this, &DataModel::updateHeaderLineGlobal); } DataModel::DataModel(Data *someData, QString weight, QObject *parent) : QAbstractTableModel(parent) { myData = someData; modelType = weight; // must be "weight" // Create the image list updateImageList(); connect(myData, &Data::modelUpdateNeeded, this, &DataModel::modelUpdateReceiver); } // Empty data model (displayed when switching projects) DataModel::DataModel(QObject *parent) : QAbstractTableModel(parent) { myData = nullptr; imageList.clear(); } void DataModel::updateImageList() { if (myData == nullptr) return; imageList.clear(); // Master calibrators if (modelType == "calib" && !myData->combinedImage.isEmpty()) { for (auto &image: myData->combinedImage) { if (image == nullptr) break; if (!image->baseName.isEmpty()) { imageList.append(image); } } } // Individual images if (!myData->myImageList.isEmpty()) { for (int chip=0; chipinstData->numChips; ++chip) { // Exposure list if (chip == 0) { for (auto &image: myData->myImageList[chip]) { exposureList.append(image); } } // All images list for (auto &image: myData->myImageList[chip]) { imageList.append(image); } } } } QVariant DataModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return QString("Image"); case 1: return QString("Active"); case 2: return QString("On\nDrive"); case 3: { QString add = ""; if (myData != nullptr) add = myData->processingStatus->statusString; return QString("L0 in\nRAM\n("+add+")"); } case 4: { QString add = ""; if (myData != nullptr) add = myData->statusBackupL1; return QString("L1 in\nRAM\n("+add+")"); } case 5: { QString add = ""; if (myData != nullptr) add = myData->statusBackupL2; return QString("L2 in\nRAM\n("+add+")"); } case 6: { QString add = ""; if (myData != nullptr) add = myData->statusBackupL3; return QString("L3 in\nRAM\n("+add+")"); } case 7: return QString("Comment"); } } return QVariant(); } int DataModel::rowCount(const QModelIndex &parent) const { if (parent.isValid() || myData == nullptr) return 0; // Total length is given by the images and master calibration files // Master cals only exist for calibration data, hence the check against nullptr long numMasterCals = myData->numMasterCalibs; // Single exposures long numExposures = 0; if (myData->myImageList.isEmpty()) return numMasterCals; for (int chip=0; chipinstData->numChips; ++chip) { numExposures += myData->myImageList[chip].length(); } return numMasterCals + numExposures; } int DataModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 8; } QVariant DataModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || imageList.isEmpty()) return QVariant(); int row = index.row(); int col = index.column(); if (row >= imageList.length()) { // qDebug() << "DataModel::data(): invalid row index" << row <<", max num images =" << imageList.length(); return QVariant(); } switch (role) { case Qt::DisplayRole: // First column contains the image name. Blanks are added for a little extra space if (modelType == "weight") { if (col == 0) return imageList[row]->rootName + "_" + QString::number(imageList[row]->chipNumber) + ".weight "; // Y/N indicators if (col==2) { if (!imageList[row]->weightOnDrive) return "N"; else return "Y"; } else if (col==3) { if (!imageList[row]->weightInMemory) return "N"; else return "Y"; } else if (col==4 || col == 5 || col == 6) return "N"; else if (col == 7) return ""; } if (modelType == "globalweight") { if (col == 0) return imageList[row]->rootName + "_" + QString::number(imageList[row]->chipNumber) + " "; // Y/N indicators if (col==2) { if (!imageList[row]->imageOnDrive) return "N"; else return "Y"; } else if (col==3) { if (!imageList[row]->imageInMemory) return "N"; else return "Y"; } else if (col==4 || col == 5 || col == 6) return "N"; else if (col == 7) return ""; } else { if (col == 0) return imageList[row]->rootName + "_" + QString::number(imageList[row]->chipNumber) + " "; // Y/N indicators if (col==2) { if (!imageList[row]->imageOnDrive) return "N"; else return "Y"; } else if (col==3) { if (!imageList[row]->imageInMemory) return "N"; else return "Y"; } else if (col==4) { if (!imageList[row]->backupL1InMemory) return "N"; else return "Y"; } else if (col==5) { if (!imageList[row]->backupL2InMemory) return "N"; else return "Y"; } else if (col==6) { if (!imageList[row]->backupL3InMemory) return "N"; else return "Y"; } else if (col==7) { if (imageList[row]->activeState == MyImage::ACTIVE) return ""; else if (imageList[row]->activeState == MyImage::INACTIVE) return "Deactivated"; else if (imageList[row]->activeState == MyImage::BADBACK) return "Poor background model"; else if (imageList[row]->activeState == MyImage::BADSTATS) return "Poor data quality"; else if (imageList[row]->activeState == MyImage::NOASTROM) return "No astrometric solution for at least one detector"; else if (imageList[row]->activeState == MyImage::LOWDETECTION) return "Insufficient sources for astrometry"; else if (imageList[row]->activeState == MyImage::DELETED) return "Image not found or deleted"; else return ""; } } break; case Qt::BackgroundRole: // Color coding if (modelType == "weight") { if (col==0) return QBrush(white); if (col==1) return QBrush(turquois); if (col==2) { if (!imageList[row]->weightOnDrive) return QBrush(red); else return QBrush(green); } else if (col==3) { if (!imageList[row]->weightInMemory) return QBrush(orange); else return QBrush(blue); } if (col == 4 || col == 5 || col == 6) return QBrush(orange); } else if (modelType == "globalweight") { if (col==0) return QBrush(white); if (col==1) return QBrush(turquois); if (col==2) { if (!imageList[row]->imageOnDrive) return QBrush(red); else return QBrush(green); } else if (col==3) { if (!imageList[row]->imageInMemory) return QBrush(orange); else return QBrush(blue); } if (col == 4 || col == 5 || col == 6) return QBrush(orange); } else { if (col==0) { if (imageList[row]->activeState != MyImage::ACTIVE) return QBrush(grey); else return QBrush(white); } if (col==1) { if (imageList[row]->activeState != MyImage::ACTIVE) return QBrush(grey); else return QBrush(turquois); } if (col==2) { if (!imageList[row]->imageOnDrive) return QBrush(red); else return QBrush(green); } else if (col==3) { if (!imageList[row]->imageInMemory) return QBrush(orange); else return QBrush(blue); } else if (col==4) { if (!imageList[row]->backupL1InMemory) return QBrush(orange); else return QBrush(blue); } else if (col==5) { if (!imageList[row]->backupL2InMemory) return QBrush(orange); else return QBrush(blue); } else if (col==6) { if (!imageList[row]->backupL3InMemory) return QBrush(orange); else return QBrush(blue); } } break; case Qt::TextAlignmentRole: if (col == 0 || col == 7) return Qt::AlignLeft; else return Qt::AlignCenter; break; case Qt::CheckStateRole: if (modelType == "weight") { if (col == 1) return Qt::Checked; if (col == 2) { if (!imageList[row]->weightOnDrive) return Qt::Unchecked; else return Qt::Checked; } } else if (modelType == "globalweight") { if (col == 1) return Qt::Checked; if (col == 2) { if (!imageList[row]->imageOnDrive) return Qt::Unchecked; else return Qt::Checked; } } else { if (col == 1) { if (imageList[row]->activeState != MyImage::ACTIVE) return Qt::Unchecked; else return Qt::Checked; } if (col == 2) { if (!imageList[row]->imageOnDrive) return Qt::Unchecked; else return Qt::Checked; } } break; } return QVariant(); } Qt::ItemFlags DataModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; // Inherit and append mode Qt::ItemFlags result = QAbstractTableModel::flags(index); if (modelType == "weight" || modelType == "globalweight") { // Toggle active / inactive state (triggers physical move of file on disk) if (index.column() == 1) { result = Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; } // Clicking on an unchecked box will check it (dumps data to disk) if (index.column() == 2) { result = Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; } if (index.column() == 3) result = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren; if (index.column() > 3) result = Qt::ItemIsEnabled |Qt::ItemNeverHasChildren; } else { // Toggle active / inactive state (triggers physical move of file on disk) if (index.column() == 1) { result = Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemNeverHasChildren; } // Clicking on an unchecked box will check it (dumps data to disk) if (index.column() == 2) { result = Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemNeverHasChildren; } if (index.column() > 2) result = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren; } return result; } bool DataModel::setData(const QModelIndex & index, const QVariant & value, int role) { if (!index.isValid()) return false; if (modelType == "weight" || modelType == "globalweight") return false; // Activate / deactivate images if (role == Qt::CheckStateRole && index.column() == 1) { // CONFUSING! Example: // The user clicks on a checked 'active' box to deactivate the image. // The 'active' checkbox state e.g. changes from checked to unchecked, // but only THEN this slot is invoked, at which point the checkbox is already unchecked. if ((Qt::CheckState)value.toInt() == Qt::Checked) { // the user clicked an unchecked box, which is now checked, hence we must activate the image // ONLY do this if the deactivated image has the same processing state as the active images! QString imagestatus = imageList[index.row()]->processingStatus->statusString; QString drivestatus = myData->processingStatus->whatIsStatusOnDrive(); if (imagestatus == drivestatus) { imageList[index.row()]->oldState = imageList[index.row()]->activeState; imageList[index.row()]->setActiveState(MyImage::ACTIVE); // Setting this value automatically moves the image on drive accordingly! } else { emit activationWarning(imagestatus, drivestatus); } } else { // the user clicked an checked box, which is now unchecked, hence we must deactivate the image imageList[index.row()]->oldState = imageList[index.row()]->activeState; imageList[index.row()]->setActiveState(MyImage::INACTIVE); // Setting this value automatically moves the image on drive accordingly! } emit dataChanged(index,index); emit activationChanged(); // meant to update image statistics module; has no effect emit refreshMemoryViewer(); return true; } // Force write to drive if (role == Qt::CheckStateRole && index.column() == 2) { if ((Qt::CheckState)value.toInt() == Qt::Checked) { MyImage *it = imageList[index.row()]; if (!it->imageOnDrive) { it->writeImage(); it->imageOnDrive = true; } } emit dataChanged(index,index); return true; } return false; } void DataModel::modelUpdateReceiver(QString chipName) { // Find the index of the MyImage that has emitted the original signal QModelIndexList list = match(index(0,0), Qt::DisplayRole, chipName); if (list.isEmpty()) { // An image was removed // Consistency check (required for debayering, which adds images that were not there previously) updateImageList(); return; } // retrieve the indices of the various cells for the current exposure long row = list[0].row(); QModelIndex indexImage = index(row, 0); QModelIndex indexState = index(row, 1); QModelIndex indexDrive = index(row, 2); QModelIndex indexL0 = index(row, 3); QModelIndex indexL1 = index(row, 4); QModelIndex indexL2 = index(row, 5); QModelIndex indexL3 = index(row, 6); // QModelIndex indexComment = index(row, 7); // unused // Update the background colors setData(indexImage, getColorImage(imageList[row]->activeState), Qt::BackgroundRole); setData(indexState, getColorState(imageList[row]->activeState), Qt::BackgroundRole); setData(indexDrive, getColorDrive(imageList[row]->imageOnDrive), Qt::BackgroundRole); setData(indexL0, getColorRAM(imageList[row]->imageInMemory), Qt::BackgroundRole); setData(indexL1, getColorRAM(imageList[row]->backupL1InMemory), Qt::BackgroundRole); setData(indexL2, getColorRAM(imageList[row]->backupL2InMemory), Qt::BackgroundRole); setData(indexL3, getColorRAM(imageList[row]->backupL3InMemory), Qt::BackgroundRole); // Update the Y/N chars setData(indexDrive, getIndicator(imageList[row]->imageOnDrive), Qt::DisplayRole); setData(indexL0, getIndicator(imageList[row]->imageInMemory), Qt::DisplayRole); setData(indexL1, getIndicator(imageList[row]->backupL1InMemory), Qt::DisplayRole); setData(indexL2, getIndicator(imageList[row]->backupL2InMemory), Qt::DisplayRole); setData(indexL3, getIndicator(imageList[row]->backupL3InMemory), Qt::DisplayRole); updateHeaderLine(row); // Inform the view that the model has changed emit dataChanged(indexDrive,indexL3); } void DataModel::updateheaderLineExternal() { updateHeaderLine(0); emit dataChanged(index(0, 0), index(0,5)); } void DataModel::updateHeaderLine(long row) { setHeaderData(3, Qt::Horizontal, "L0 in\nRAM\n("+imageList[row]->processingStatus->statusString+")"); setHeaderData(4, Qt::Horizontal, "L1 in\nRAM\n("+imageList[row]->statusBackupL1+")"); setHeaderData(5, Qt::Horizontal, "L2 in\nRAM\n("+imageList[row]->statusBackupL2+")"); setHeaderData(6, Qt::Horizontal, "L3 in\nRAM\n("+imageList[row]->statusBackupL3+")"); } void DataModel::updateHeaderLineGlobal() { setHeaderData(3, Qt::Horizontal, "L0 in\nRAM\n("+myData->processingStatus->statusString+")"); setHeaderData(4, Qt::Horizontal, "L1 in\nRAM\n("+myData->statusBackupL1+")"); setHeaderData(5, Qt::Horizontal, "L2 in\nRAM\n("+myData->statusBackupL2+")"); setHeaderData(6, Qt::Horizontal, "L3 in\nRAM\n("+myData->statusBackupL3+")"); } void DataModel::beginResetModelReceived() { beginResetModel(); } void DataModel::endResetModelReceived() { endResetModel(); } QColor DataModel::getColorImage(MyImage::active_type state) { if (state == MyImage::ACTIVE) return white; else return grey; } QColor DataModel::getColorState(MyImage::active_type state) { if (state == MyImage::ACTIVE) return turquois; else return grey; } QColor DataModel::getColorDrive(bool flag) { if (flag) return green; else return red; } QColor DataModel::getColorRAM(bool flag) { if (flag) return blue; else return orange; } QString DataModel::getIndicator(bool flag) { if (flag) return "Y"; else return "N"; } // E.g. master calibrations are created bool DataModel::insertRows(int row, int count, const QModelIndex &parent) { beginInsertRows(parent, row, row + count - 1); QVector dummyMask; dummyMask.clear(); MyImage *newImage = new MyImage("path", "file", "", 1, dummyMask, myData->verbosity); connect(newImage, &MyImage::modelUpdateNeeded, this, &DataModel::modelUpdateReceiver); imageList.insert(row, newImage); endInsertRows(); return true; } bool DataModel::insertColumns(int column, int count, const QModelIndex &parent) { beginInsertColumns(parent, column, column + count - 1); // Nothing to be done endInsertColumns(); return true; } // E.g. input images after they were debayered bool DataModel::removeRows(int row, int count, const QModelIndex &parent) { beginRemoveRows(parent, row, row + count - 1); imageList.removeAt(row); endRemoveRows(); return true; } bool DataModel::removeColumns(int column, int count, const QModelIndex &parent) { beginRemoveColumns(parent, column, column + count - 1); // Nothing to be done endRemoveColumns(); return true; } THELI-3.1.3/src/datamodel/datamodel.h000066400000000000000000000063421417631501300172150ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef DATAMODEL_H #define DATAMODEL_H #include "../processingInternal/data.h" #include "../myimage/myimage.h" #include #include #include class Data; class DataModel : public QAbstractTableModel { Q_OBJECT public: explicit DataModel(Data *someData, QObject *parent = nullptr); explicit DataModel(Data *someData, QString weight, QObject *parent = nullptr); explicit DataModel(QObject *parent = nullptr); // Header: Q_INVOKABLE QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; Data *myData; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QList imageList; QList exposureList; QString modelType = "science"; // can be "calib", "weight", and "globalweight"; // Add and remove data: bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex()) override; bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex()) override; void updateImageList(); void updateheaderLineExternal(); private slots: void modelUpdateReceiver(QString chipName); void updateHeaderLine(long row); void updateHeaderLineGlobal(); public slots: void beginResetModelReceived(); void endResetModelReceived(); private: int numImages = 0; QColor orange = QColor("#f39c12"); QColor blue = QColor("#3498d8"); QColor green = QColor("#16a085"); QColor red = QColor("#e74c3c"); QColor turquois = QColor("#49ebc5"); QColor grey = QColor("#dddddd"); QColor white = QColor("#ffffff"); QColor getColorDrive(bool flag); QColor getColorRAM(bool flag); QColor getColorState(MyImage::active_type state); QColor getColorImage(MyImage::active_type state); QString getIndicator(bool flag); bool setData(const QModelIndex &index, const QVariant &value, int role); Qt::ItemFlags flags(const QModelIndex &index) const; signals: void activationWarning(QString imagestatus, QString drivestatus); void refreshMemoryViewer(); void activationChanged(); // void writeImageToDisk(MyImage *myImage) const; }; #endif // DATAMODEL_H THELI-3.1.3/src/deepmessages.cc000066400000000000000000000375761417631501300161510ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainwindow.h" #include #include // This source file handles signals emitted from within the processing threads // Show error messages void MainWindow::showMessageBoxReceived(QString trigger, QString part1, QString part2) { if (trigger == "Controller::GAP_DYNAMIC_FOUND" && !GAP_DYNAMIC_FOUND_shown) { GAP_DYNAMIC_FOUND_shown = true; QMessageBox::warning(this, tr("Significant gap found in background image series"), tr("A gap of ")+part1+tr(" hours was found ")+ tr("in the dynamic series of background images, exceeding the maximum ")+ tr("allowed gap size of ")+part2+ tr(" hours.\nUsually, a gap size does not need to be defined with dynamic background modeling."), QMessageBox::Ok); } else if (trigger == "Controller::INSUFFICIENT_BACKGROUND_NUMBER" && !INSUFFICIENT_BACKGROUND_NUMBER_shown) { INSUFFICIENT_BACKGROUND_NUMBER_shown = true; QMessageBox::warning(this, tr("Insufficient number of suitable background images."), part1+tr(" images were found to construct a background model. ")+ tr("This is less than the required minimum of ")+part2+tr(" images."), QMessageBox::Ok); } else if (trigger == "Controller::WINDOWSIZE_TOO_LARGE" && !WINDOWSIZE_TOO_LARGE_shown) { WINDOWSIZE_TOO_LARGE_shown = true; QMessageBox::warning(this, tr("Window size too large"), tr("The currently selected window size of ")+part1+tr(" images is larger than the number")+ tr("of images (")+part2+tr(") available for background correction. Aborting."), QMessageBox::Ok); } else if (trigger == "Controller::SKY_FILE_NOT_FOUND" && !SKY_FILE_NOT_FOUND_shown) { SKY_FILE_NOT_FOUND_shown = true; QMessageBox::warning(this, tr("File not found / no sky positions selected"), tr("The file with blank sky positions could not be found or is empty:")+"\n"+ part1+"/skysamples.dat\n"+ tr("Click on \"Select sky area(s)\" to open iView and select at least one empty sky area with the middle mouse button."), QMessageBox::Ok); } else if (trigger == "Controller::NO_OVERLAP_WITH_SKYAREA" && !NO_OVERLAP_WITH_SKYAREA_shown) { NO_OVERLAP_WITH_SKYAREA_shown = true; QMessageBox::warning(this, tr("Insufficient sky data"), tr("The following exposure did not overlap with any of the manually defined sky positions:")+"\n"+ part1+"\nAborting.", QMessageBox::Ok); } else if (trigger == "Controller::POOR_COORD") { QMessageBox::warning(this, tr("Inconsistent coaddition coordinates"), tr("The manually provided coordinates for the sky projection do not fall within any of the exposures:")+"\n"+ "R.A. = "+part1+"\n"+ "DEC = "+part2+"\nEither provide correct coordinates, or leave the fields empty. Aborting.", QMessageBox::Ok); } else if (trigger == "Controller::MASTER_BIAS_NOT_FOUND" && !MASTER_BIAS_NOT_FOUND_shown) { MASTER_BIAS_NOT_FOUND_shown = true; QMessageBox::warning(this, tr("Master BIAS not found"), tr("The following master BIAS or DARK was not found for calibrating science images:")+"\n"+ part1+"\n"+ tr("\nYou must create it first."), QMessageBox::Ok); } else if (trigger == "Controller::MASTER_FLAT_NOT_FOUND" && !MASTER_FLAT_NOT_FOUND_shown) { MASTER_FLAT_NOT_FOUND_shown = true; QMessageBox::warning(this, tr("Master FLAT not found"), tr("The following master FLAT was not found for calibrating science images:")+"\n"+ part1+"\n"+ tr("\nYou must create it first."), QMessageBox::Ok); } else if (trigger == "Controller::MASTER_FLATOFF_NOT_FOUND" && !MASTER_FLATOFF_NOT_FOUND_shown) { MASTER_FLATOFF_NOT_FOUND_shown = true; QMessageBox::warning(this, tr("Master Calibrator not found"), tr("Master BIAS or FLAT_OFF not found for creation of master FLAT!")+"\n"+ part1+"\n"+ tr("You must create it first."), QMessageBox::Ok); } else if (trigger == "Controller::MASTER_BIAS_NOT_FOUND_GLOBW" && !MASTER_BIAS_NOT_FOUND_GLOBW_shown) { MASTER_BIAS_NOT_FOUND_GLOBW_shown = true; QMessageBox::warning(this, tr("Master BIAS or FLATOFF not found"), tr("Master BIAS or FLATOFF not found, needed to create the global weight.")+"\n"+ part1+"\n"+ tr("You must create it first."), QMessageBox::Ok); } else if (trigger == "Controller::MASTER_FLAT_NOT_FOUND_GLOBW" && !MASTER_FLAT_NOT_FOUND_GLOBW_shown) { MASTER_FLAT_NOT_FOUND_GLOBW_shown = true; QMessageBox::warning(this, tr("Master FLAT not found"), tr("Master FLAT not found, needed to create the global weight.")+"\n"+ part1+"\n"+ tr("You must create it first."), QMessageBox::Ok); } else if (trigger == "Controller::NO_MJDOBS_FOR_PM" && !NO_MJDOBS_FOR_PM_shown) { NO_MJDOBS_FOR_PM_shown = true; QMessageBox::warning(this, tr("MJD-OBS not found"), tr("The MJD-OBS keyword was not found or zero in at least one of the exposures.")+"\n"+ tr("It is required for the requested non-sidereal motion correction. Aborting."), QMessageBox::Ok); } else if (trigger == "Controller::CANNOT_UPDATE_HEADER_WITH_PM_READ" && !CANNOT_UPDATE_HEADER_WITH_PM_READ_shown) { CANNOT_UPDATE_HEADER_WITH_PM_READ_shown = true; QMessageBox::warning(this, tr("Cannot read header file"), tr("The header file") + part1 + tr("\ncould not be opened for reading. Needed to update with the non-sidereal proper motion.")+"\n"+ tr("Error is: ") + part2 + "\nAborting.", QMessageBox::Ok); } else if (trigger == "Controller::CANNOT_UPDATE_HEADER_WITH_PM_WRITE" && !CANNOT_UPDATE_HEADER_WITH_PM_WRITE_shown) { CANNOT_UPDATE_HEADER_WITH_PM_WRITE_shown = true; QMessageBox::warning(this, tr("Cannot write header file"), tr("The header file\n") + part1 + tr("\ncould not be opened for writing. Needs to be updated with the non-sidereal proper motion.")+"\n"+ tr("Error is: ") + part2 + "\nAborting.", QMessageBox::Ok); } else if (trigger == "Controller::CANNOT_UPDATE_HEADER_WITH_PA" && !CANNOT_UPDATE_HEADER_WITH_PA_shown) { CANNOT_UPDATE_HEADER_WITH_PA_shown = true; QMessageBox::warning(this, tr("Cannot read header file"), part1 + tr("\ncould not be opened to read the CD matrix. This is needed for the update it with the new position angle.")+"\n"+ tr("Error is: ") + part2 + "\nAborting.", QMessageBox::Ok); } else if (trigger == "Controller::CANNOT_WRITE_RESAMPLE_LIST" && !CANNOT_WRITE_RESAMPLE_LIST_shown) { CANNOT_WRITE_RESAMPLE_LIST_shown = true; QMessageBox::warning(this, tr("Cannot write file"), tr("Coaddition: Could not append image names to ")+part1+"
"+ tr("Error is: ") + part2 + "
Aborting.", QMessageBox::Ok); } else if (trigger == "Controller::CANNOT_OPEN_FILE" && !CANNOT_OPEN_FILE_shown) { CANNOT_OPEN_FILE_shown = true; QMessageBox::warning(this, tr("Cannot open file for read/write"), tr("The following file could not be opened: ")+part1+"

"+ tr("The Error is: \"") + part2 + "\"
Aborting.", QMessageBox::Ok); } else if (trigger == "Data::CANNOT_READ_HEADER_KEYS" && !CANNOT_READ_HEADER_KEYS_shown) { CANNOT_READ_HEADER_KEYS_shown = true; QMessageBox::warning(this, tr("Could not read one or more of the following keywords:\nNAXIS1, NAXIS2, FILTER, MJD-OBS"), tr("Add the keywords manually, or the remove the corrupted images.\n")+part1, QMessageBox::Ok); } else if (trigger == "Data::INCONSISTENT_DATA_STATUS" && INCONSISTENT_DATA_STATUS_shown) { INCONSISTENT_DATA_STATUS_shown = true; QMessageBox::warning(this, tr("Inconsistent data status detected in ")+part1, part1 + " : " + tr("The FITS files found do not match the recorded status (*") + part2 +".fits).\n"+ tr("Either restore the files manually, or use the 'Processing status' menu to reflect the current status. A restart is recommended."), QMessageBox::Ok); } else if (trigger == "Data::Duplicate_MJDOBS" && !DUPLICATE_MJDOBS_shown) { DUPLICATE_MJDOBS_shown = true; QMessageBox::warning(this, tr("One or more images have identical MJD-OBS header keywords."), tr("THELI cannot build a list of contemporal images for the background model in")+part1+ tr("
nor construct correct source catalogs for the astrometric solution.")+ tr("
You must first fix the MJD-OBS keywords to their correct values, or the DATE-OBS keyword in the raw data."), QMessageBox::Ok); } else if (trigger == "Data::IMAGES_NOT_FOUND" && !IMAGES_NOT_FOUND_shown) { IMAGES_NOT_FOUND_shown = true; QMessageBox::warning(this, tr("ERROR: Images not found"), tr("Could not find any images of type :
")+"*"+part1+".fits" + "
in "+part2 + tr("
Check that the recorded processing status matches the currently present images."), QMessageBox::Ok); } else if (trigger == "Controller::TARGET_UNRESOLVED") { QMessageBox::warning(this, tr("Target not found"), tr("The coordinates of ") + part1 + tr(" could not be resolved.")+ tr("
Check for typos, or try a different name of the same target."), QMessageBox::Ok); } else if (trigger == "Controller::RESET_REQUESTED") { const QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Clearing error status?"), tr("The data in ") + part1 + tr(" is in an error state due to an earlier processing failure.")+ tr("
Do you want to clear the error state to allow reprocessing (you must re-execute the task)?"), QMessageBox::Ok | QMessageBox::Cancel); switch (ret) { case QMessageBox::Ok: emit resetErrorStatus(part1); break; default: break; } } else if (trigger == "Colorpicture::EmptySelection") { QMessageBox::warning(this, tr("Empty selection"), tr("At least two images must be chosen from the list of coadded images."), QMessageBox::Ok); } else if (trigger == "Splitter::IncompatibleSizeRAW" && !IncompatibleSizeRAW_shown) { IncompatibleSizeRAW_shown = true; QMessageBox::warning(this, tr("Incompatible detector geometry in setup"), tr("You must adjust the SIZEX and SIZEY parameters in ")+part1+ tr(" to match the geometry defined in the RAW file: ")+part2, QMessageBox::Ok); } else if (trigger == "Data::WEIGHT_DATA_NOT_FOUND") { QMessageBox::warning(this, tr("Missing weight images"), tr("The following ")+part1+tr(" images do not have a matching weight image (WEIGHTS/*weight.fits):\n")+part2, QMessageBox::Ok); } else if (trigger == "Data::HEADER_DATA_NOT_FOUND") { QMessageBox::warning(this, tr("Missing astrometric headers"), tr("The following ")+part1+tr(" images do not have matching astrometric headers (headers/*.head):\n")+part2, QMessageBox::Ok); } else if (trigger == "Data::SCAMP_CATS_NOT_FOUND") { QMessageBox::warning(this, tr("Missing scamp catalogs"), tr("The following ")+part1+tr(" images do not have matching scamp catalogs (cat/*.scamp). The corresponding exposures will be deactivated:\n")+part2, QMessageBox::Ok); } else if (trigger == "Controller::BACKGROUND_PARALLELIZATION") { QMessageBox::warning(this, tr("Parallelization unstable"), tr("You are running the background modelling with more than 1 CPU. ") + tr("Currently, this is the only task that is still unstable when run in parallel, and random crashes may occur. ") + tr("Use a single CPU if you have problems. Once background modeling is done, you can revert to full parallelization."), QMessageBox::Ok); } else if (trigger == "DATA::RAW_AND_PROCESSED_FOUND") { QMessageBox::warning(this, tr("Invalid data mix"), tr("Both processed and RAW files were found. This status is not allowed. ") + tr("You must manually clean up the data in ") + part1, QMessageBox::Ok); } else if (trigger == "Data::BACKUP_DATA_NOT_FOUND") { QString warningText = ""; warningText = tr("You were about to repeat a processing task.") + " " +tr("However, THELI could not find the data with the previous processing state, neither in memory nor in the backup folders on your drive.") + " " +tr("You have the following options:") + "\n(1) "+tr("Do not repeat this task and continue processing") + "\n(2) "+tr("Restore a previous state from within the memory viewer") + "\n(3) "+tr("Manually restore FITS files from a backup directory and restart THELI"); QMessageBox::warning(this, tr("ERROR: Failed to locate backup data"), warningText, QMessageBox::Ok); } } void MainWindow::resetProcessingErrorFlags() { GAP_DYNAMIC_FOUND_shown = false; WINDOWSIZE_TOO_LARGE_shown = false; INSUFFICIENT_BACKGROUND_NUMBER_shown = false; SKY_FILE_NOT_FOUND_shown = false; NO_OVERLAP_WITH_SKYAREA_shown = false; } THELI-3.1.3/src/dockwidgets/000077500000000000000000000000001417631501300154625ustar00rootroot00000000000000THELI-3.1.3/src/dockwidgets/confdockwidget.cc000066400000000000000000001556261417631501300210020ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "confdockwidget.h" #include "ui_confdockwidget.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "functions.h" #include "../iview/iview.h" #include #include #include #include ConfDockWidget::ConfDockWidget(MainWindow *parent) : QDockWidget(parent), ui(new Ui::ConfDockWidget) { mainGUI = parent; ui->setupUi(this); doingInitialLaunch = true; initConfDockWidget(); setupAstrometry(); populateDefaultMap(); establish_connections(); populateAPIlists(); updateConfPageLabel(); ui->skyAreaComboBox->setStyleSheet("combobox-popup: 0;"); // enforcing max number of 18 entries (set in designer) doingInitialLaunch = false; } ConfDockWidget::~ConfDockWidget() { delete ui; } void ConfDockWidget::initConfDockWidget() { QIcon magnifyer(":/icons/magnifyer.png"); ui->ARCtargetresolverToolButton->setIcon(magnifyer); ui->xtalk_col_1x2ToolButton->setIcon(QIcon(":/icons/xtalk_col_1x2.png")); ui->xtalk_col_2x1ToolButton->setIcon(QIcon(":/icons/xtalk_col_2x1.png")); ui->xtalk_col_2x2ToolButton->setIcon(QIcon(":/icons/xtalk_col_2x2.png")); ui->xtalk_nor_1x2ToolButton->setIcon(QIcon(":/icons/xtalk_nor_1x2.png")); ui->xtalk_nor_2x1ToolButton->setIcon(QIcon(":/icons/xtalk_nor_2x1.png")); ui->xtalk_nor_2x2ToolButton->setIcon(QIcon(":/icons/xtalk_nor_2x2.png")); ui->xtalk_row_1x2ToolButton->setIcon(QIcon(":/icons/xtalk_row_1x2.png")); ui->xtalk_row_2x1ToolButton->setIcon(QIcon(":/icons/xtalk_row_2x1.png")); ui->xtalk_row_2x2ToolButton->setIcon(QIcon(":/icons/xtalk_row_2x2.png")); ui->skyReadmePushButton->hide(); // update the collapse direction icon QString colldir = ui->COCdirectionComboBox->currentText(); ui->COCdirectionLabel->setPixmap(QPixmap(":/icons/collapse_"+colldir)); // These comboboxes do not get initialized or filled properly unless one clicks on it: on_APDrefcatComboBox_currentTextChanged(ui->APDrefcatComboBox->currentText()); on_ASTmethodComboBox_currentIndexChanged(ui->ASTmethodComboBox->currentIndex()); // why commented / uncommented above? // on_APIrefcatComboBox_currentTextChanged(ui->APIrefcatComboBox->currentText()); updateARCdisplay(); toggle_skyparams(); toggle_skyparamThresholds(""); applyStyleSheets(); setupXtalkButtonGroups(); updateAPIsolutions(); } void ConfDockWidget::establish_connections() { // Connect crosstalk ToolButtons with icon updater connect(ui->xtalk_col_1x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_col_2x1ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_col_2x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_row_1x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_row_2x1ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_row_2x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_nor_1x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_nor_2x1ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_nor_2x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); // Connect skysub Radio Buttons with a function that dis/enables frames connect(ui->skyModelRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::toggle_skyparams); connect(ui->skyPolynomialRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::toggle_skyparams); connect(ui->skyConstsubRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::toggle_skyparams); connect(ui->skyAreaComboBox, &QComboBox::currentTextChanged, this, &ConfDockWidget::toggle_skyparamThresholds); connect(ui->BACwindowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::switch_static_dynamic); connect(ui->confStackedWidget, &QStackedWidget::currentChanged, this, &ConfDockWidget::updateConfPageLabel); connect(ui->parametersDefaultPushButton, &QPushButton::clicked, this, &ConfDockWidget::loadDefaults); // TODO: check if needed // connect(ui->skyModelRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->skyPolynomialRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->skyConstsubRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // Update command list in real time when the following parameters are changed // (may or may not add further scripts) // TODO: check if needed // connect(ui->BACdistLineEdit, &QLineEdit::textChanged, this, &MainWindow::on_startPushButton_clicked); // connect(ui->BACmagLineEdit, &QLineEdit::textChanged, this, &MainWindow::on_startPushButton_clicked); // connect(ui->ARCwebRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->ARCimageRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->ASTmethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::startPushButton_clicked_dummy); // connect(ui->APIWCSCheckBox, &QCheckBox::clicked, this, &MainWindow::on_startPushButton_clicked); // TODO: must activate connect(ui->ARCgetcatalogPushButton, &QPushButton::clicked, mainGUI, &MainWindow::on_startPushButton_clicked); connect(ui->restoreHeaderPushButton, &QPushButton::clicked, mainGUI, &MainWindow::on_startPushButton_clicked); connect(ui->ARCtargetresolverToolButton, &QToolButton::clicked, mainGUI, &MainWindow::on_startPushButton_clicked); connect(ui->ARCwebRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::updateARCdisplay); connect(ui->ARCimageRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::updateARCdisplay); // TODO: must activate // Connect StandardStar solution PushButtons with iView for (auto &it : APIstdPushButtonList) { connect(it, &QPushButton::clicked, this, &ConfDockWidget::showAPIsolution); } connect(ui->excludeDetectorsLineEdit, &QLineEdit::textChanged, mainGUI, &MainWindow::updateExcludedDetectors); connect(mainGUI->ui->setupInstrumentComboBox, &QComboBox::currentTextChanged, this, &ConfDockWidget::setupInstrumentComboBox_clicked); connect_validators(); } void ConfDockWidget::applyStyleSheets() { QList conftitleLabelList; conftitleLabelList.append(ui->conftitleHDUreformatLabel); conftitleLabelList.append(ui->conftitleExcludeDetectorsLabel); conftitleLabelList.append(ui->conftitleProcessbiasLabel); conftitleLabelList.append(ui->conftitleChopnodLabel); conftitleLabelList.append(ui->conftitleBackground1Label); conftitleLabelList.append(ui->conftitleBackground2Label); conftitleLabelList.append(ui->conftitleCollapseLabel); conftitleLabelList.append(ui->conftitleBinnedpreviewLabel); conftitleLabelList.append(ui->conftitleGlobalweightLabel); conftitleLabelList.append(ui->conftitleIndividualweightLabel); conftitleLabelList.append(ui->conftitleSeparateLabel); conftitleLabelList.append(ui->conftitleAbsphotindirect1Label); conftitleLabelList.append(ui->conftitleAbsphotindirect2Label); conftitleLabelList.append(ui->conftitleCreatesourcecatLabel); conftitleLabelList.append(ui->conftitleGetCatalogLabel); conftitleLabelList.append(ui->conftitleAstromphotom1Label); conftitleLabelList.append(ui->conftitleAstromphotom2Label); conftitleLabelList.append(ui->conftitleStarflatLabel); conftitleLabelList.append(ui->conftitleSkysubLabel); conftitleLabelList.append(ui->conftitleCoadd1Label); conftitleLabelList.append(ui->conftitleCoadd2Label); for (auto &it : conftitleLabelList) { it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);"); it->setMargin(8); } QList confsubtitleLabelList; confsubtitleLabelList.append(ui->confsubtitleHDUreformat1Label); confsubtitleLabelList.append(ui->confsubtitleHDUreformat2Label); confsubtitleLabelList.append(ui->confsubtitleCalibrators1Label); confsubtitleLabelList.append(ui->confsubtitleCalibrators2Label); confsubtitleLabelList.append(ui->confsubtitleBackground1Label); confsubtitleLabelList.append(ui->confsubtitleBackground2Label); confsubtitleLabelList.append(ui->confsubtitleBackground3Label); confsubtitleLabelList.append(ui->confsubtitleBackground4Label); confsubtitleLabelList.append(ui->confsubtitleBackground5Label); confsubtitleLabelList.append(ui->confsubtitleBackground6Label); confsubtitleLabelList.append(ui->confsubtitleCollapse1Label); confsubtitleLabelList.append(ui->confsubtitleCollapse2Label); confsubtitleLabelList.append(ui->confsubtitleCollapse3Label); confsubtitleLabelList.append(ui->confsubtitleGlobalweight1Label); confsubtitleLabelList.append(ui->confsubtitleGlobalweight2Label); confsubtitleLabelList.append(ui->confsubtitleGlobalweight3Label); confsubtitleLabelList.append(ui->confsubtitleIndividualweight1Label); confsubtitleLabelList.append(ui->confsubtitleIndividualweight2Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect1Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect2Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect3Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect4Label); confsubtitleLabelList.append(ui->confsubtitleCreatesourcecat1Label); confsubtitleLabelList.append(ui->confsubtitleCreatesourcecat2Label); confsubtitleLabelList.append(ui->confsubtitleCreatesourcecat3Label); confsubtitleLabelList.append(ui->confsubtitleGetCatalog1Label); confsubtitleLabelList.append(ui->confsubtitleGetCatalog2Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom1Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom2Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom3Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom4Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom5Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom6Label); confsubtitleLabelList.append(ui->confsubtitleSkysub1Label); confsubtitleLabelList.append(ui->confsubtitleSkysub2Label); confsubtitleLabelList.append(ui->confsubtitleSkysub3Label); confsubtitleLabelList.append(ui->confsubtitleCoadd1Label); confsubtitleLabelList.append(ui->confsubtitleCoadd2Label); confsubtitleLabelList.append(ui->confsubtitleCoadd3Label); confsubtitleLabelList.append(ui->confsubtitleCoadd4Label); confsubtitleLabelList.append(ui->confsubtitleCoadd5Label); confsubtitleLabelList.append(ui->confsubtitleCoadd6Label); for (auto &it : confsubtitleLabelList) { it->setStyleSheet("background-color: rgb(190,190,210);"); it->setMargin(4); } QList confFrameList; confFrameList.append(ui->confHDUreformat1Frame); confFrameList.append(ui->confHDUreformat2Frame); confFrameList.append(ui->confExcludeDetectorsFrame); confFrameList.append(ui->confCalibrators1Frame); confFrameList.append(ui->confCalibrators2Frame); confFrameList.append(ui->confChopnodFrame); confFrameList.append(ui->confBackground1Frame); confFrameList.append(ui->confBackground2Frame); confFrameList.append(ui->confBackground3Frame); confFrameList.append(ui->confBackground4Frame); confFrameList.append(ui->confBackground5Frame); confFrameList.append(ui->confBackground6Frame); confFrameList.append(ui->confCollapse1Frame); confFrameList.append(ui->confCollapse2Frame); confFrameList.append(ui->confCollapse3Frame); confFrameList.append(ui->confBinnedpreviewFrame); confFrameList.append(ui->confGlobalweight1Frame); confFrameList.append(ui->confGlobalweight2Frame); confFrameList.append(ui->confGlobalweight3Frame); confFrameList.append(ui->confIndividualweight1Frame); confFrameList.append(ui->confIndividualweight2Frame); confFrameList.append(ui->confSeparateFrame); confFrameList.append(ui->confAbsphotindirect1Frame); confFrameList.append(ui->confAbsphotindirect2Frame); confFrameList.append(ui->confAbsphotindirect3Frame); confFrameList.append(ui->confAbsphotindirect4Frame); confFrameList.append(ui->confAstromphotom1Frame); confFrameList.append(ui->confAstromphotom2Frame); confFrameList.append(ui->confAstromphotom3Frame); confFrameList.append(ui->confAstromphotom4Frame); confFrameList.append(ui->confAstromphotom5Frame); confFrameList.append(ui->confAstromphotom6Frame); confFrameList.append(ui->confCreatesourcecat1Frame); confFrameList.append(ui->confCreatesourcecat2Frame); confFrameList.append(ui->confCreatesourcecat3Frame); confFrameList.append(ui->confGetCatalog1Frame); confFrameList.append(ui->confGetCatalog2Frame); confFrameList.append(ui->confStarflatFrame); confFrameList.append(ui->confSkysub1Frame); confFrameList.append(ui->confSkysub2Frame); confFrameList.append(ui->confSkysub3Frame); confFrameList.append(ui->confCoadd1Frame); confFrameList.append(ui->confCoadd2Frame); confFrameList.append(ui->confCoadd3Frame); confFrameList.append(ui->confCoadd4Frame); confFrameList.append(ui->confCoadd5Frame); /* for (auto &it : confFrameList) { // specify large style sheet? } */ /* // Checkboxes with differently colored background QList confCheckboxList; confCheckboxList.append(ui->CIWmaskbloomingCheckBox); for (auto &it : confCheckboxList) { // it->setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(160,160,160);"); it->setStyleSheet("background-color: rgb(190,190,210);"); } */ } void ConfDockWidget::targetResolvedReceived(const QString &alpha, const QString &delta) { ui->ARCraLineEdit->setText(alpha); ui->ARCdecLineEdit->setText(delta); } void ConfDockWidget::toggle_icons_xtalkToolButtons() { QToolButton *toolbutton = qobject_cast(sender()); QString sender_name = toolbutton->objectName().remove("ToolButton"); // Override checked/unchecked ToolButton background color // The "checked" color will actually be a bit darker than requested here (shade overriden) QPalette palette_checked, palette_unchecked; palette_checked.setColor(QPalette::Button,QColor("#00ffff")); palette_unchecked.setColor(QPalette::Button,QColor("#ffffff")); if (toolbutton->isChecked()) { if (sender()) { QToolButton *toolbutton = qobject_cast(sender()); if (toolbutton->isChecked()) toolbutton->setPalette(palette_checked); else toolbutton->setPalette(palette_unchecked); } toolbutton->setPalette(palette_checked); // also activate the checkbox if a xtalk mode is selected if (sender_name.contains("nor")) ui->normalxtalkCheckBox->setChecked(true); else ui->rowxtalkCheckBox->setChecked(true); } else { toolbutton->setPalette(palette_unchecked); } } // This is a slot that receives a signal with a QString argument, but does not use it void ConfDockWidget::toggle_skyparamThresholds(QString text) { if (ui->skyAreaComboBox->currentIndex() == 0 && ui->confSkysub3Frame->isEnabled()) ui->confSkysub2Frame->setDisabled(true); else ui->confSkysub2Frame->setEnabled(true); } void ConfDockWidget::load_default_stdcat() { if (instrument_type == "OPT") { ui->APIrefcatComboBox->setCurrentIndex(4); ui->APDfilterComboBox->setCurrentIndex(0); } else if (instrument_type == "NIR") { ui->APIrefcatComboBox->setCurrentIndex(6); ui->APDfilterComboBox->setCurrentIndex(1); } else if (instrument_type == "NIRMIR") { ui->APIrefcatComboBox->setCurrentIndex(10); ui->APDfilterComboBox->setCurrentIndex(1); } else { // There isn't really a solution for MIR... ui->APIrefcatComboBox->setCurrentIndex(10); ui->APDfilterComboBox->setCurrentIndex(1); } } void ConfDockWidget::populateAPIlists() { APIstdPushButtonList.append(ui->APInight1PushButton); APIstdPushButtonList.append(ui->APInight2PushButton); APIstdPushButtonList.append(ui->APInight3PushButton); APIstdPushButtonList.append(ui->APInight4PushButton); APIstdPushButtonList.append(ui->APInight5PushButton); APIstdPushButtonList.append(ui->APInight6PushButton); APIstdPushButtonList.append(ui->APInight7PushButton); APIstdPushButtonList.append(ui->APInight8PushButton); APIstdPushButtonList.append(ui->APInight9PushButton); APIstdComboBoxList.append(ui->APInight1ComboBox); APIstdComboBoxList.append(ui->APInight2ComboBox); APIstdComboBoxList.append(ui->APInight3ComboBox); APIstdComboBoxList.append(ui->APInight4ComboBox); APIstdComboBoxList.append(ui->APInight5ComboBox); APIstdComboBoxList.append(ui->APInight6ComboBox); APIstdComboBoxList.append(ui->APInight7ComboBox); APIstdComboBoxList.append(ui->APInight8ComboBox); APIstdComboBoxList.append(ui->APInight9ComboBox); } void ConfDockWidget::toggle_skyparams() { const QStandardItemModel* skyAreaModel = dynamic_cast< QStandardItemModel * >( ui->skyAreaComboBox->model() ); if (ui->skyModelRadioButton->isChecked()) { ui->confSkysub2Frame->setEnabled(true); ui->confSkysub3Frame->setDisabled(true); ui->skyAreaPushButton->setDisabled(true); } else if (ui->skyPolynomialRadioButton->isChecked()) { ui->confSkysub2Frame->setDisabled(true); ui->confSkysub3Frame->setEnabled(true); for (int i=1; iskyAreaComboBox->count(); ++i) { skyAreaModel->item(i,0)->setEnabled(false); } // Must use specific areas ui->skyAreaComboBox->setCurrentIndex(0); ui->skyAreaPushButton->setEnabled(true); } else { if (ui->skyAreaComboBox->currentIndex() == 0) ui->confSkysub2Frame->setDisabled(true); else ui->confSkysub2Frame->setEnabled(true); ui->confSkysub3Frame->setEnabled(true); for (int i=1; iskyAreaComboBox->count(); ++i) { skyAreaModel->item(i,0)->setEnabled(true); } ui->skyAreaPushButton->setEnabled(true); } } void ConfDockWidget::on_COAcelestialtypeComboBox_activated(const QString &arg1) { if (arg1 == "EQUATORIAL") { ui->COAtype1Label->setText("R.A."); ui->COAtype2Label->setText("DEC"); } else if (arg1 == "GALACTIC") { ui->COAtype1Label->setText("GLON"); ui->COAtype2Label->setText("GLAT"); } else if (arg1 == "ECLIPTIC") { ui->COAtype1Label->setText("ELON"); ui->COAtype2Label->setText("ELAT"); } else if (arg1 == "SUPERGALACTIC") { ui->COAtype1Label->setText("SLON"); ui->COAtype2Label->setText("SLAT"); } else { ui->COAtype1Label->setText("R.A."); ui->COAtype2Label->setText("DEC"); } } void ConfDockWidget::switch_static_dynamic() { if (ui->BACwindowLineEdit->text().toInt() == 0) ui->BACcurrentmodeLabel->setText("The mode is: STATIC"); else ui->BACcurrentmodeLabel->setText("The mode is: DYNAMIC"); } void ConfDockWidget::on_COCdirectionComboBox_currentTextChanged(const QString &arg1) { ui->COCdirectionLabel->setPixmap(QPixmap(":/icons/collapse_"+arg1)); } void ConfDockWidget::on_APDrefcatComboBox_currentTextChanged(const QString &arg1) { if (arg1 == "SDSS") fill_combobox(ui->APDfilterComboBox, "u g r i z"); else if (arg1 == "2MASS") fill_combobox(ui->APDfilterComboBox, "J H Ks"); } void ConfDockWidget::on_APIrefcatComboBox_currentTextChanged(const QString &arg1) { if (arg1 == "LANDOLT_UBVRI") { fill_combobox(ui->APIfilterComboBox, "U B V R I"); fill_combobox(ui->APIcolorComboBox, "U-B B-V V-R R-I"); } else if (arg1 == "STETSON_UBVRI") { fill_combobox(ui->APIfilterComboBox, "U B V R I"); fill_combobox(ui->APIcolorComboBox, "U-B B-V V-R R-I"); } else if (arg1 == "STRIPE82_ugriz") { fill_combobox(ui->APIfilterComboBox, "u g r i z"); fill_combobox(ui->APIcolorComboBox, "u-g g-r r-i i-z g-i"); } else if (arg1 == "STRIPE82_u'g'r'i'z'") { fill_combobox(ui->APIfilterComboBox, "u' g' r' i' z'"); fill_combobox(ui->APIcolorComboBox, "u'-g' g'-r' r'-i' i'-z' g'-i'"); } else if (arg1 == "SMITH_u'g'r'i'z'") { fill_combobox(ui->APIfilterComboBox, "u' g' r' i' z'"); fill_combobox(ui->APIcolorComboBox, "u'-g' g'-r' r'-i' i'-z' g'-i'"); } else if (arg1 == "WASHINGTON") { fill_combobox(ui->APIfilterComboBox, "C M T1 T2"); fill_combobox(ui->APIcolorComboBox, "C-M M-T1 T1-T2"); } else if (arg1 == "MKO_JHK") { fill_combobox(ui->APIfilterComboBox, "J H K"); fill_combobox(ui->APIcolorComboBox, "J-H H-K J-K"); } else if (arg1 == "HUNT_JHK") { fill_combobox(ui->APIfilterComboBox, "J H K"); fill_combobox(ui->APIcolorComboBox, "J-H H-K J-K"); } else if (arg1 == "2MASSfaint_JHK") { fill_combobox(ui->APIfilterComboBox, "J H K"); fill_combobox(ui->APIcolorComboBox, "J-H H-K J-K"); } else if (arg1 == "PERSSON_JHKKs") { fill_combobox(ui->APIfilterComboBox, "J H K Ks"); fill_combobox(ui->APIcolorComboBox, "J-H H-K H-Ks J-K J-Ks"); } else if (arg1 == "JAC_YJHKLM") { fill_combobox(ui->APIfilterComboBox, "Y J H K L M"); fill_combobox(ui->APIcolorComboBox, "Y-J J-H H-K J-K K-L L-M"); } else if (arg1 == "MKO_LM") { fill_combobox(ui->APIfilterComboBox, "L M"); fill_combobox(ui->APIcolorComboBox, "L-M"); } } void ConfDockWidget::on_confStackedWidget_currentChanged(int arg1) { if (this->isFloating()) { ui->confStackedWidget->setGeometry(100,100,300,300); } } void ConfDockWidget::updateARCdisplay() { if (ui->ARCwebRadioButton->isChecked()) ui->ARCstackedWidget->setCurrentIndex(0); else ui->ARCstackedWidget->setCurrentIndex(1); } void ConfDockWidget::on_ASTmatchMethodComboBox_currentIndexChanged(int index) { // TODO: check if needed (probably not, because we don't invoke scripts anymore) // on_startPushButton_clicked(); if (index >= 1) { ui->ASTposangleLineEdit->setDisabled(true); ui->ASTpositionLineEdit->setDisabled(true); ui->ASTmatchflippedCheckBox->setDisabled(true); ui->ASTposangleLabel->setDisabled(true); ui->ASTpositionLabel->setDisabled(true); } else { ui->ASTposangleLineEdit->setEnabled(true); ui->ASTpositionLineEdit->setEnabled(true); ui->ASTmatchflippedCheckBox->setEnabled(true); ui->ASTposangleLabel->setEnabled(true); ui->ASTpositionLabel->setEnabled(true); } } void ConfDockWidget::on_ASTmethodComboBox_currentIndexChanged(int index) { if (index == 0) { // ui->confAstromphotom1Frame->setDisabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->confAstromphotom6Frame->setEnabled(true); ui->ASTxcorrDTLineEdit->hide(); ui->ASTxcorrDMINLineEdit->hide(); ui->ASTxcorrDTLabel->hide(); ui->ASTxcorrDMINLabel->hide(); } else if (index == 1) { // ui->confAstromphotom1Frame->setDisabled(true); ui->confAstromphotom2Frame->setDisabled(true); ui->confAstromphotom3Frame->setDisabled(true); ui->confAstromphotom4Frame->setDisabled(true); ui->confAstromphotom5Frame->setDisabled(true); ui->confAstromphotom6Frame->setDisabled(true); ui->ASTxcorrDTLineEdit->show(); ui->ASTxcorrDMINLineEdit->show(); ui->ASTxcorrDTLabel->show(); ui->ASTxcorrDMINLabel->show(); } else { // ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setDisabled(true); ui->confAstromphotom3Frame->setDisabled(true); ui->confAstromphotom4Frame->setDisabled(true); ui->confAstromphotom5Frame->setDisabled(true); ui->confAstromphotom6Frame->setDisabled(true); ui->ASTxcorrDTLineEdit->hide(); ui->ASTxcorrDMINLineEdit->hide(); ui->ASTxcorrDTLabel->hide(); ui->ASTxcorrDMINLabel->hide(); } } void ConfDockWidget::on_COAskypaPushButton_clicked() { QString maindir = mainGUI->ui->setupMainLineEdit->text(); // Grab the first entry of the science dir QString science; if (!mainGUI->ui->setupScienceLineEdit->text().isEmpty()) { science = datadir2StringList(mainGUI->ui->setupScienceLineEdit).at(0); } else { return; } QString sciencedir = maindir+"/"+science; QDir dir(sciencedir); if (!dir.exists()) return; int testChip = -1; for (int chip=0; chipinstData.numChips; ++chip) { if (!mainGUI->instData.badChips.contains(chip)) { testChip = chip; break; } } if (testChip == -1) { qDebug() << __func__ << "error: no data left after filtering"; } QString currentStatus = mainGUI->status.getStatusFromHistory(); QStringList filter1("*_"+QString::number(testChip+1)+currentStatus+".fits"); QStringList filter2("*_"+QString::number(testChip+1)+currentStatus+".sub.fits"); dir.setNameFilters(filter1); dir.setSorting(QDir::Name); QStringList list = dir.entryList(); QString sub = ""; if (list.isEmpty()) { // Probably normal images were parked or removed, try skysub images dir.setNameFilters(filter2); dir.setSorting(QDir::Name); list = dir.entryList(); if (list.isEmpty()) return; sub = ".sub"; } if (list.length() == 0) { QMessageBox::warning( this, "Data not found!", "No "+currentStatus+"-images were found in "+science+"\n"); return; } // Images must have astrometric headers QString headerdir = sciencedir+"/headers/"; bool check = hasMatchingPartnerFiles(sciencedir, currentStatus+sub+".fits", headerdir, ".head", "This task requires that all science images have astrometric headers."); if (!check) return; // Grab the first header file QString baseName = list.at(0); baseName.replace(currentStatus+sub+".fits",""); QString headerName = headerdir+baseName+".head"; QFile header(headerName); QString cd11 = ""; QString cd12 = ""; QString cd21 = ""; QString cd22 = ""; QString line; QString key; QString value; if ( header.open(QIODevice::ReadOnly)) { QTextStream stream( &header ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); if (!line.isEmpty()) { key = line.section(' ',0,0); value = line.section(' ',2,2); if (key == "CD1_1") cd11 = value; if (key == "CD1_2") cd12 = value; if (key == "CD2_1") cd21 = value; if (key == "CD2_2") cd22 = value; } } header.close(); } if (!cd11.isEmpty() && !cd12.isEmpty() && !cd21.isEmpty() && !cd22.isEmpty()) { double skyPA = getPosAnglefromCD(cd11.toDouble(), cd12.toDouble(), cd21.toDouble(), cd22.toDouble()); // in [deg] skyPA *= -1.; // it appears I need that, at least for: /* * these data require a -1 prefactor GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD1_1 = 2.069880636041E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD1_2 = -5.020554295263E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD2_1 = 4.995016509429E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD2_2 = 2.197139027629E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD1_1 = 2.133359158630E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD1_2 = -5.029786624776E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD2_1 = 5.142047608929E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD2_2 = 2.185105945141E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD1_1 = 2.113575793537E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD1_2 = -5.089493103124E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD2_1 = 5.144032585776E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD2_2 = 2.028047913328E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD1_1 = 2.060624347989E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD1_2 = -5.091430845254E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD2_1 = 4.999641460896E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD2_2 = 2.040364194243E-06 / Linear projection matrix */ // Truncate the result to one digit QString skyPAstring = QString::number(skyPA, 'f', 1); ui->COAskypaLineEdit->setText(skyPAstring); } else QMessageBox::warning( this, "Corrupted astrometric header", "The CD matrix in "+headerName+" is incomplete, meaning the astrometry was not successful."); } /* void ConfDockWidget::on_viewerToolButton_clicked() { QString main = ui->setupMainLineEdit->text(); QString science = ui->setupScienceLineEdit->text().split(" ").at(0); QString dirname = main+"/"+science; if (!QDir(dirname).exists()) dirname = QDir::homePath(); IView *iView = new IView(dirname, "*.fits", this); iView->show(); } */ void ConfDockWidget::on_skyAreaComboBox_currentTextChanged(const QString &arg1) { if (arg1 != "Specific sky area(s)") ui->skyAreaPushButton->setDisabled(true); else ui->skyAreaPushButton->setEnabled(true); } void ConfDockWidget::on_skyAreaPushButton_clicked() { QMessageBox msgBox; msgBox.setText("Use the middle mouse button (click and drag) to select one or more empty sky areas. " "You can use the forward / backward buttons to select other images. Close the viewer when finished.\n\n" "Alternatively, you can click on any image in the memory viewer, or open any astrometrically calibrated image in iView, e.g. a previous coaddition of the same data. " "Select the dropper tool at the upper left and then use the middle mouse button as explained above."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); QString maindir = mainGUI->ui->setupMainLineEdit->text(); // Grab the first entry of the science dir QString science; if (!mainGUI->ui->setupScienceLineEdit->text().isEmpty()) { science = datadir2StringList(mainGUI->ui->setupScienceLineEdit).at(0); } else { QMessageBox msgBox; msgBox.setText("The science directory is empty."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); return; } QString sciencedir = maindir+"/"+science; if (!QDir(sciencedir).exists()) { QMessageBox msgBox; msgBox.setText("The science directory"+sciencedir+"does not exist."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); return; } launchViewer("SkyMode"); } // void ConfDockWidget::launchViewer(const QString &dirname, const QString &filter, const QString &mode) void ConfDockWidget::launchViewer(const QString &mode) { // Load the plot viewer // IView *iView = new IView(dirname, filter, false); // IView *iView = new IView("FITSmonochrome", dirname, filter, this); // IView *iView = new IView(dirname, filter); // iView->show(); // iView->setMiddleMouseMode(mode); QString mainDirName = mainGUI->controller->mainDirName; QString scienceDirName = mainGUI->controller->DT_SCIENCE[0]->subDirName; QString dirName = mainDirName + "/"+scienceDirName; IView *iView = new IView("MEMview", mainGUI->controller->DT_SCIENCE[0]->myImageList[mainGUI->instData.validChip], dirName, this); iView->scene->clear(); MyImage *it = mainGUI->controller->DT_SCIENCE[0]->myImageList[mainGUI->instData.validChip][0]; iView->loadFromRAM(it, 3); iView->currentId = 0; // IView needs to know the directory name so that it can overlay catalogs iView->show(); iView->setMiddleMouseMode(mode); // iView->raise(); } void ConfDockWidget::on_ARCcatalogComboBox_currentTextChanged(const QString &arg1) { if (arg1.contains("GAIA") || arg1.contains("UCAC5")) ui->gaiaFrame->show(); else ui->gaiaFrame->hide(); } void ConfDockWidget::on_ARCselectimagePushButton_clicked() { QString currentFileName = QFileDialog::getOpenFileName(this, tr("Select astrometrically calibrated image"), QDir::homePath(), tr("Images (*.fits *.fit *.fts *.FIT *.FITS *.FTS);; All (*.*)")); if ( currentFileName.isEmpty() ) return; ui->ARCselectimageLineEdit->setText(currentFileName); } void ConfDockWidget::updateGaiaBulkMotion(const QString &pmRA, const QString &pmDE) { ui->ARCpmRALineEdit->setText(pmRA); ui->ARCpmDECLineEdit->setText(pmDE); } void ConfDockWidget::on_confForwardPushButton_clicked() { int count = ui->confStackedWidget->count(); int current = ui->confStackedWidget->currentIndex(); ui->confBackwardPushButton->setDisabled(false); if (current >= count-2) { ui->confForwardPushButton->setDisabled(true); ui->confBackwardPushButton->setFocus(); } if (current < count-1) ui->confStackedWidget->setCurrentIndex(current+1); updateConfPageLabel(); } void ConfDockWidget::on_confBackwardPushButton_clicked() { int current = ui->confStackedWidget->currentIndex(); ui->confForwardPushButton->setDisabled(false); if (current <= 1) { ui->confBackwardPushButton->setDisabled(true); ui->confForwardPushButton->setFocus(); } if (current > 0) ui->confStackedWidget->setCurrentIndex(current-1); updateConfPageLabel(); } void ConfDockWidget::updateConfPageLabel() { int current = ui->confStackedWidget->currentIndex(); ui->confPageLabel->setText("Page "+QString::number(current+1)+"/9"); ui->parametersDefaultPushButton->setText("Defaults for page "+QString::number(current+1)); } void ConfDockWidget::setupAstrometry() { const QStandardItemModel* astrometryMatchModel = dynamic_cast< QStandardItemModel * >( ui->ASTmatchMethodComboBox->model() ); // Enable / disable matching methods QString anetSolver = findExecutableName("solve-field"); QString anetIndex = findExecutableName("build-astrometry-index"); bool anet = true; if (anetSolver.isEmpty() || anetIndex.isEmpty()) anet = false; astrometryMatchModel->item( 0,0 )->setEnabled( true ); astrometryMatchModel->item( 1,0 )->setEnabled( anet ); astrometryMatchModel->item( 2,0 )->setEnabled( true ); if (!doingInitialLaunch) { ui->ASTmatchMethodComboBox->setCurrentIndex(0); } } void ConfDockWidget::setupXtalkButtonGroups() { norxtalkButtonGroup->addButton(ui->xtalk_nor_2x2ToolButton); norxtalkButtonGroup->addButton(ui->xtalk_nor_1x2ToolButton); norxtalkButtonGroup->addButton(ui->xtalk_nor_2x1ToolButton); norxtalkButtonGroup->setId(ui->xtalk_nor_2x2ToolButton, 0); norxtalkButtonGroup->setId(ui->xtalk_nor_1x2ToolButton, 1); norxtalkButtonGroup->setId(ui->xtalk_nor_2x1ToolButton, 2); ui->xtalk_nor_2x2ToolButton->setChecked(true); rowxtalkButtonGroup->addButton(ui->xtalk_row_2x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_row_1x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_row_2x1ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_col_2x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_col_1x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_col_2x1ToolButton); rowxtalkButtonGroup->setId(ui->xtalk_row_2x2ToolButton, 0); rowxtalkButtonGroup->setId(ui->xtalk_row_1x2ToolButton, 1); rowxtalkButtonGroup->setId(ui->xtalk_row_2x1ToolButton, 2); rowxtalkButtonGroup->setId(ui->xtalk_col_2x2ToolButton, 3); rowxtalkButtonGroup->setId(ui->xtalk_col_1x2ToolButton, 4); rowxtalkButtonGroup->setId(ui->xtalk_col_2x1ToolButton, 5); ui->xtalk_row_2x2ToolButton->setChecked(true); } void ConfDockWidget::setupInstrumentComboBox_clicked() { // The structure holding the content of the instrument file // TODO: check if actually needed // initInstrumentData(instrument_dir+instrument_name+".ini"); //if (!readingSettings) { // ui->COApixscaleLineEdit->setText(get_fileparameter(&instrument_file, "PIXSCALE")); //} // Update some comboboxes ui->skyAreaComboBox->clear(); ui->skyAreaComboBox->addItem("Specific sky area(s)"); if (instrument_nchips == 1) { ui->skyAreaComboBox->addItem("From entire chip"); } else { ui->skyAreaComboBox->addItem("From each chip"); for (int i=1; i<=instrument_nchips; ++i) { QString entry = "From chip "+QString::number(i); ui->skyAreaComboBox->addItem(entry); } } int currentASTmethod = ui->ASTmethodComboBox->currentIndex(); // (de)activate some GUI elements depending on wavelength regime; // the following two lines are needed to (de)activate some elements in a ComboBox const QStandardItemModel* astrom_model = dynamic_cast< QStandardItemModel * >( ui->ASTmethodComboBox->model() ); const QStandardItemModel* mosaictype_model = dynamic_cast< QStandardItemModel * >( ui->ASTmosaictypeComboBox->model() ); const QStandardItemModel* focalplane_model = dynamic_cast< QStandardItemModel * >( ui->ASTfocalplaneComboBox->model() ); const QStandardItemModel* std_model = dynamic_cast< QStandardItemModel * >( ui->APIrefcatComboBox->model() ); if (instrument_nchips == 1) { mosaictype_model->item( 1,0 )->setEnabled( false ); mosaictype_model->item( 2,0 )->setEnabled( false ); mosaictype_model->item( 3,0 )->setEnabled( false ); mosaictype_model->item( 4,0 )->setEnabled( false ); focalplane_model->item( 1,0 )->setEnabled( false ); focalplane_model->item( 2,0 )->setEnabled( false ); if (!doingInitialLaunch) { ui->ASTmosaictypeComboBox->setCurrentIndex(0); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } // Show the option of masking a rectangular region for collapse correction ui->confsubtitleCollapse3Label->show(); ui->confCollapse3Frame->show(); } else { mosaictype_model->item( 1,0 )->setEnabled( true ); mosaictype_model->item( 2,0 )->setEnabled( true ); mosaictype_model->item( 3,0 )->setEnabled( true ); mosaictype_model->item( 4,0 )->setEnabled( true ); focalplane_model->item( 1,0 )->setEnabled( true ); focalplane_model->item( 2,0 )->setEnabled( true ); if (ui->ASTstabilityComboBox->currentText() == "INSTRUMENT") { ui->ASTmosaictypeComboBox->setCurrentIndex(3); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } else if (ui->ASTstabilityComboBox->currentText() == "EXPOSURE") { ui->ASTmosaictypeComboBox->setCurrentIndex(4); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } // Hide the option of masking a rectangular region for collapse correction ui->confsubtitleCollapse3Label->hide(); ui->confCollapse3Frame->hide(); } if (instrument_type == "MIR") { ui->splitMIRcubeCheckBox->show(); ui->confChopnodSpacer->changeSize(1,30); ui->confChopnodFrame->show(); ui->conftitleChopnodLabel->show(); ui->confsubtitleBackground1Label->setDisabled(true); ui->confsubtitleBackground2Label->setDisabled(true); ui->confsubtitleBackground3Label->setDisabled(true); ui->confsubtitleBackground4Label->setDisabled(true); ui->confsubtitleBackground5Label->setDisabled(true); ui->confsubtitleBackground6Label->setDisabled(true); ui->confBackground1Frame->setDisabled(true); ui->confBackground2Frame->setDisabled(true); ui->confBackground3Frame->setDisabled(true); ui->confBackground4Frame->setDisabled(true); ui->confBackground5Frame->setDisabled(true); ui->confBackground6Frame->setDisabled(true); ui->ASTmethodComboBox->setCurrentIndex(2); ui->confAstromphotom1Frame->setDisabled(true); ui->confAstromphotom2Frame->setDisabled(true); ui->confAstromphotom3Frame->setDisabled(true); ui->confAstromphotom4Frame->setDisabled(true); ui->confAstromphotom5Frame->setDisabled(true); ui->CIWmaskbloomingCheckBox->setDisabled(true); ui->confIndividualweight2Frame->setDisabled(true); astrom_model->item( 0,0 )->setEnabled( false ); } else if (instrument_type == "NIR") { ui->splitMIRcubeCheckBox->hide(); ui->confChopnodFrame->hide(); ui->conftitleChopnodLabel->hide(); ui->confChopnodSpacer->changeSize(1,0); ui->confsubtitleBackground1Label->setEnabled(true); ui->confsubtitleBackground1Label->show(); ui->confsubtitleBackground2Label->setEnabled(true); ui->confsubtitleBackground3Label->setEnabled(true); ui->confsubtitleBackground4Label->setEnabled(true); ui->confsubtitleBackground5Label->setEnabled(true); ui->confsubtitleBackground6Label->setEnabled(true); ui->confBackground1Frame->setEnabled(true); ui->confBackground1Frame->show(); ui->confBackground2Frame->setEnabled(true); ui->confBackground3Frame->setEnabled(true); ui->confBackground4Frame->setEnabled(true); ui->confBackground5Frame->setEnabled(true); ui->confBackground6Frame->setEnabled(true); if (currentASTmethod < 2) ui->ASTmethodComboBox->setCurrentIndex(currentASTmethod); else ui->ASTmethodComboBox->setCurrentIndex(0); ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->CIWmaskbloomingCheckBox->setDisabled(true); // ui->confIndividualweight2Frame->setDisabled(true); astrom_model->item( 0,0 )->setEnabled( true ); std_model->item( 0,0 )->setEnabled( false ); std_model->item( 1,0 )->setEnabled( false ); std_model->item( 2,0 )->setEnabled( false ); std_model->item( 3,0 )->setEnabled( false ); std_model->item( 4,0 )->setEnabled( false ); std_model->item( 5,0 )->setEnabled( false ); std_model->item( 6,0 )->setEnabled( true ); std_model->item( 7,0 )->setEnabled( true ); std_model->item( 8,0 )->setEnabled( true ); std_model->item( 9,0 )->setEnabled( true ); std_model->item( 10,0 )->setEnabled( true ); std_model->item( 11,0 )->setEnabled( true ); } else if (instrument_type == "NIRMIR") { ui->splitMIRcubeCheckBox->show(); ui->confChopnodFrame->show(); ui->conftitleChopnodLabel->show(); ui->confChopnodSpacer->changeSize(1,30); ui->confsubtitleBackground1Label->setEnabled(true); ui->confsubtitleBackground2Label->setEnabled(true); ui->confsubtitleBackground3Label->setEnabled(true); ui->confsubtitleBackground4Label->setEnabled(true); ui->confsubtitleBackground5Label->setEnabled(true); ui->confsubtitleBackground6Label->setEnabled(true); ui->confBackground1Frame->setEnabled(true); ui->confBackground2Frame->setEnabled(true); ui->confBackground3Frame->setEnabled(true); ui->confBackground4Frame->setEnabled(true); ui->confBackground5Frame->setEnabled(true); ui->confBackground6Frame->setEnabled(true); if (currentASTmethod < 2) ui->ASTmethodComboBox->setCurrentIndex(currentASTmethod); else ui->ASTmethodComboBox->setCurrentIndex(0); ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->CIWmaskbloomingCheckBox->setDisabled(true); // ui->confIndividualweight2Frame->setDisabled(true); astrom_model->item( 0,0 )->setEnabled( true ); std_model->item( 0,0 )->setEnabled( false ); std_model->item( 1,0 )->setEnabled( false ); std_model->item( 2,0 )->setEnabled( false ); std_model->item( 3,0 )->setEnabled( false ); std_model->item( 4,0 )->setEnabled( false ); std_model->item( 5,0 )->setEnabled( false ); std_model->item( 6,0 )->setEnabled( true ); std_model->item( 7,0 )->setEnabled( true ); std_model->item( 8,0 )->setEnabled( true ); std_model->item( 9,0 )->setEnabled( true ); std_model->item( 10,0 )->setEnabled( true ); std_model->item( 11,0 )->setEnabled( true ); } else if (instrument_type == "OPT" || instrument_type == "") { ui->splitMIRcubeCheckBox->hide(); ui->confChopnodSpacer->changeSize(1,0); ui->confChopnodFrame->hide(); ui->conftitleChopnodLabel->hide(); ui->confsubtitleBackground1Label->hide(); ui->confsubtitleBackground2Label->setEnabled(true); ui->confsubtitleBackground3Label->setEnabled(true); ui->confsubtitleBackground4Label->setEnabled(true); ui->confsubtitleBackground5Label->setEnabled(true); ui->confsubtitleBackground6Label->setEnabled(true); ui->confBackground1Frame->hide(); ui->confBackground2Frame->setEnabled(true); ui->confBackground3Frame->setEnabled(true); ui->confBackground4Frame->setEnabled(true); ui->confBackground5Frame->setEnabled(true); ui->confBackground6Frame->setEnabled(true); if (currentASTmethod < 2) ui->ASTmethodComboBox->setCurrentIndex(currentASTmethod); else ui->ASTmethodComboBox->setCurrentIndex(0); ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->CIWmaskbloomingCheckBox->setEnabled(true); ui->confIndividualweight2Frame->setEnabled(true); // The following line triggers repaintDataDirs. Why? astrom_model->item( 0,0 )->setEnabled( true ); std_model->item( 0,0 )->setEnabled( true ); std_model->item( 1,0 )->setEnabled( true ); std_model->item( 2,0 )->setEnabled( true ); std_model->item( 3,0 )->setEnabled( true ); std_model->item( 4,0 )->setEnabled( true ); std_model->item( 5,0 )->setEnabled( true ); std_model->item( 6,0 )->setEnabled( false ); std_model->item( 7,0 )->setEnabled( false ); std_model->item( 8,0 )->setEnabled( false ); std_model->item( 9,0 )->setEnabled( false ); std_model->item( 10,0 )->setEnabled( false ); std_model->item( 11,0 )->setEnabled( false ); } load_default_stdcat(); // Update settings // TODO: make sure this does not happen in parallel to the same task in MainWindow // MUST UNCOMMENT // writeGUISettings(); } void ConfDockWidget::updateAPIsolutions() { QString standard = getNthWord(mainGUI->ui->setupStandardLineEdit->text(),1); QDir standardDir = QDir(mainGUI->ui->setupMainLineEdit->text()+"/"+standard+"/calib/"); QStringList filter("night*.dat"); QStringList solutionList = standardDir.entryList(filter); if (solutionList.isEmpty()) ui->APInodataLabel->show(); else ui->APInodataLabel->hide(); int numNights = solutionList.length(); int i=0; for (auto &it : APIstdPushButtonList) { if (isetText("Show "+buttonText); it->show(); } else { it->hide(); } ++i; } i=0; for (auto &it : APIstdComboBoxList) { if (ishow(); else it->hide(); ++i; } } // Not yet implemented void ConfDockWidget::showAPIsolution() { // QString standard = getNthWord(mainGUI->ui->setupStandardLineEdit->text(),1); // QPushButton* pushbutton = qobject_cast(sender()); // QString solutionPlotPath = mainGUI->ui->setupMainLineEdit->text()+"/"+standard+"/calib/"; // launchViewer(solutionPlotPath, pushbutton->text()+"_result.png", ""); // probably have to define a new IView mode for this } void ConfDockWidget::on_ASTreadmepushButton_clicked() { scampreadme = new ScampReadme(this); scampreadme->show(); } bool ConfDockWidget::checkRightScampMode(const QString &coordsMode) { if (coordsMode != "execute") return true; if (instrument_nchips == 1) return true; if (ui->ASTmosaictypeComboBox->currentText() == "UNCHANGED" || (ui->ASTmosaictypeComboBox->currentText() == "FIX_FOCALPLANE" && ui->ASTfocalplaneComboBox->currentText() != "IGNORE_PRIOR")) { QMessageBox msgBox; msgBox.setText("Likely inconsistent Scamp setup:\n'MOSAIC_TYPE = UNCHANGED' or\n" "'MOSAIC_TYPE = FIX_FOCALPLANE' and 'FPA mode = IGNORE_PRIOR'"); msgBox.setInformativeText("Relative chip orientations as encoded by the reference pixels and CD matrix " "may vary over short or long time scales. The best way is to re-measure the " "relative orientations from the data themselves. Five well-dithered exposures " "are usually sufficient, in particular if calibrated against GAIA. To do this, use\n\n" "'MOSAIC_TYPE = FIX_FOCALPLANE' and 'FPA mode = IGNORE_PRIOR'. \n\n" "If that doesn't work, try \n\n" "'MOSAIC_TYPE = LOOSE' and 'FPA mode = IGNORE_PRIOR'.\n\n" "If that does not work, try using the pre-determined focal plane array (FPA):\n\n " "'MOSAIC_TYPE = SAME_CRVAL' and 'FPA mode = USE_PRIOR'.\n\n"); QAbstractButton* pButtonContinue = msgBox.addButton(tr("Continue as is"), QMessageBox::YesRole); QAbstractButton* pButtonDetails = msgBox.addButton(tr("Details [...]"), QMessageBox::YesRole); QAbstractButton* pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton()==pButtonContinue) return true; else if (msgBox.clickedButton()==pButtonDetails) { scampreadme = new ScampReadme(this); scampreadme->show(); return false; } else if (msgBox.clickedButton()==pButtonCancel) { return false; } } else return true; return true; } void ConfDockWidget::on_nonlinearityCheckBox_clicked() { if (!ui->nonlinearityCheckBox->isChecked()) return; QString coeffsFileName = instrument_dir+"/"+instrument_name+".nldat"; QFile coeffsFile(coeffsFileName); if (!coeffsFile.exists() || !coeffsFile.open(QIODevice::ReadOnly)) { QMessageBox msgBox; msgBox.setText("Nonlinearity correction for "+instrument_name+" is not implemented.\n" +"Contact the author if you have the polynomial correction coefficients available."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); ui->nonlinearityCheckBox->setChecked(false); } } void ConfDockWidget::on_ASTviewCheckPlotsPushButton_clicked() { Data *scienceData = nullptr; if (mainGUI->controller->DT_SCIENCE.length() == 1) { scienceData = mainGUI->controller->DT_SCIENCE.at(0); } else if (mainGUI->controller->DT_SCIENCE.length() == 0) { QMessageBox::information(this, tr("Missing data"), tr("No SCIENCE data were specified in the data tree.\n"), QMessageBox::Ok); return; } // See if any checkplots exist bool checkPlotsExist = false; for (auto &data : mainGUI->controller->DT_SCIENCE) { QDir plotsDir = data->dirName+"/plots/"; if (plotsDir.exists()) checkPlotsExist = true; } if (checkPlotsExist) { if (mainGUI->controller->DT_SCIENCE.length() > 1) { QMessageBox msgBox; msgBox.setInformativeText(tr("The current SCIENCE data tree contains several entries for which astrometry check plots exist.\n") + tr("Display the plots for:\n\n")); for (auto &data : mainGUI->controller->DT_SCIENCE) { QDir plotsDir = data->dirName+"/plots/"; if (plotsDir.exists()) msgBox.addButton(data->subDirName, QMessageBox::YesRole); } QAbstractButton *pCancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole); msgBox.exec(); QString choice = msgBox.clickedButton()->text().remove('&'); // remove & is a KDE fix if (msgBox.clickedButton()== pCancel) return; for (auto &data : mainGUI->controller->DT_SCIENCE) { if (data->subDirName == choice) { scienceData = data; break; } } } IView *checkplotViewer = new IView("SCAMP_VIEWONLY", scienceData->dirName+"/plots/", this); checkplotViewer->show(); } else { QMessageBox msgBox; msgBox.setInformativeText(tr("Could not find astrometric check plots in any of the science directories.\n") + tr("You must run the astrometry first.\n")); msgBox.addButton(tr("OK"), QMessageBox::YesRole); msgBox.exec(); } } THELI-3.1.3/src/dockwidgets/confdockwidget.h000066400000000000000000000073101417631501300206260ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef CONFDOCKWIDGET_H #define CONFDOCKWIDGET_H #include "readmes/scampreadme.h" #include #include #include #include #include #include #include #include #include class MainWindow; // forward declaration to access GUI members namespace Ui { class ConfDockWidget; } class ConfDockWidget : public QDockWidget { Q_OBJECT public: explicit ConfDockWidget(MainWindow *parent = 0); ~ConfDockWidget(); Ui::ConfDockWidget *ui; QMap defaultMap; MainWindow *mainGUI; // The following are set externally by MainWindow::on_setupInstrumentComboBox_clicked() QFile instrument_file; QString instrument_dir; QString instrument_name; QString instrument_type; QString instrument_bayer; int instrument_nchips = 1; QButtonGroup *norxtalkButtonGroup = new QButtonGroup(this); QButtonGroup *rowxtalkButtonGroup = new QButtonGroup(this); void load_default_stdcat(); bool checkRightScampMode(const QString &coordsMode); private: QList APIstdPushButtonList; QList APIstdComboBoxList; ScampReadme *scampreadme; bool doingInitialLaunch = false; void populateDefaultMap(); void populateAPIlists(); void establish_connections(); void launchViewer(const QString &mode); void initConfDockWidget(); void applyStyleSheets(); void setupXtalkButtonGroups(); void validate(); void connect_validators(); void setupAstrometry(); private slots: void on_APDrefcatComboBox_currentTextChanged(const QString &arg1); void on_APIrefcatComboBox_currentTextChanged(const QString &arg1); void on_ARCcatalogComboBox_currentTextChanged(const QString &arg1); void on_ARCselectimagePushButton_clicked(); void on_ASTmethodComboBox_currentIndexChanged(int index); void on_ASTmatchMethodComboBox_currentIndexChanged(int index); void on_ASTreadmepushButton_clicked(); void on_COAcelestialtypeComboBox_activated(const QString &arg1); void on_COAskypaPushButton_clicked(); void on_COCdirectionComboBox_currentTextChanged(const QString &arg1); void on_confStackedWidget_currentChanged(int arg1); void on_confForwardPushButton_clicked(); void on_confBackwardPushButton_clicked(); void on_skyAreaComboBox_currentTextChanged(const QString &arg1); void on_skyAreaPushButton_clicked(); void showAPIsolution(); void switch_static_dynamic(); void toggle_icons_xtalkToolButtons(); void updateConfPageLabel(); void on_nonlinearityCheckBox_clicked(); void on_ASTviewCheckPlotsPushButton_clicked(); public slots: void loadDefaults(); void updateGaiaBulkMotion(const QString &pmRA, const QString &pmDE); void updateAPIsolutions(); void updateARCdisplay(); void setupInstrumentComboBox_clicked(); void toggle_skyparams(); void toggle_skyparamThresholds(QString text); void targetResolvedReceived(const QString &alpha, const QString &delta); }; #endif // CONFDOCKWIDGET_H THELI-3.1.3/src/dockwidgets/confdockwidget.ui000066400000000000000000045774201417631501300210360ustar00rootroot00000000000000 ConfDockWidget 0 0 618 670 false QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Configuration 0 0 600 0 600 16777215 0 0 0 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 0 0 0 255 255 255 0 0 0 255 255 255 170 170 170 0 0 0 212 212 212 255 255 220 0 0 0 0 0 0 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 0 0 0 255 255 255 0 0 0 255 255 255 170 170 170 0 0 0 212 212 212 255 255 220 0 0 0 85 85 85 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 85 85 85 255 255 255 85 85 85 170 170 170 170 170 170 0 0 0 170 170 170 255 255 220 0 0 0 Qt::ClickFocus true QFrame::Panel QFrame::Sunken 1 5 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); <html><head/><body><p>HDU / Detector corrections</p></body></html> true 75 true QFrame::NoFrame (1) Renaming 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame 50 false Qt::ClickFocus Split MIR cubes. Otherwise, the cubes are stacked right away. Split MIR cubes 50 false Qt::ClickFocus Renames the files to INST.FILTER.DATEOBS_CHIP.fits Use THELI naming scheme true 75 true QFrame::NoFrame (2) Low-level corrections 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame 50 false Qt::ClickFocus Applies overscan correction. Note: some instruments will always be corrected. Overscan correction : true Qt::Horizontal 18 20 50 false Qt::ClickFocus Applies a nonlinearity correction for flats and science images (if the coefficients are known for the current instrument) Nonlinearity correction 50 false Qt::ClickFocus Check if you want to correct normal crosstalk (ghost images) Point crosstalk correction Qt::Horizontal 8 20 Amplitude rowxtalkAmplitudeLineEdit Amplitude normalxtalkAmplitudeLineEdit 80 0 100 16777215 The crosstalk amplitude factor (can be negative) 50 false Qt::ClickFocus Check if you want to correct row crosstalk (ghost lines) Row crosstalk correction Qt::Horizontal 8 20 Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_nor_2x2p.png icons/xtalk_nor_2x2a.pngicons/xtalk_nor_2x2p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_nor_1x2p.png icons/xtalk_nor_1x2a.pngicons/xtalk_nor_1x2p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_nor_2x1p.png icons/xtalk_nor_2x1a.pngicons/xtalk_nor_2x1p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_row_2x2p.png icons/xtalk_row_2x2a.pngicons/xtalk_row_2x2p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_row_2x1p.png icons/xtalk_row_2x1a.pngicons/xtalk_row_2x1p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_row_1x2p.png icons/xtalk_row_1x2a.pngicons/xtalk_row_1x2p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_col_2x2p.png icons/xtalk_col_2x2a.pngicons/xtalk_col_2x2p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_col_2x1p.png icons/xtalk_col_2x1a.pngicons/xtalk_col_2x1p.png 49 49 true true Qt::ClickFocus Select a crosstalk pattern ... icons/xtalk_col_1x2p.png icons/xtalk_col_1x2a.pngicons/xtalk_col_1x2p.png 49 49 true true 80 0 100 16777215 The crosstalk amplitude factor (can be negative) Qt::NoFocus Method used to combine images in the stack Line median Line mean Global median Saturation level in the raw data (in ADU) Saturation [ ADU ] Qt::Vertical 207 28 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Exclude unusable / unwanted detectors true 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame A comma- or blank-separated list of the bad detector numbers Chip numbers Qt::Vertical QSizePolicy::Fixed 20 20 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Process BIAS / DARK / FLATOFF / FLAT true 75 true QFrame::NoFrame (1) Reject pixels / combine method 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain nlow nhigh Method BIAS biasNlowLineEdit 0 0 60 0 60 16777215 The number of low pixels to be rejected from the stack 0 0 60 0 60 16777215 The number of high pixels to be rejected from the stack Qt::NoFocus Method used to combine images in the stack Median Mean DARK darkNlowLineEdit 0 0 60 0 60 16777215 The number of low pixels to be rejected from the stack 0 0 60 0 60 16777215 The number of high pixels to be rejected from the stack Qt::NoFocus Method used to combine images in the stack Median Mean FLAT OFF flatoffNlowLineEdit 0 0 60 0 60 16777215 The number of low pixels to be rejected from the stack 0 0 60 0 60 16777215 The number of high pixels to be rejected from the stack Qt::NoFocus Method used to combine images in the stack Median Mean FLAT flatNlowLineEdit 0 0 60 0 60 16777215 The number of low pixels to be rejected from the stack 0 0 60 0 60 16777215 The number of high pixels to be rejected from the stack Qt::NoFocus Method used to combine images in the stack Median Mean 75 true QFrame::NoFrame (2) Min / max counts [e-] allowed 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame min max BIAS biasMinLineEdit 0 0 16777215 16777215 The minimum mode to be accepted for an image to enter a stack. Per chip, not per exposure. 0 0 16777215 16777215 The maximum mode to be accepted for an image to enter a stack. Per chip, not per exposure. DARK darkMinLineEdit 0 0 16777215 16777215 The minimum mode to be accepted for an image to enter a stack. Per chip, not per exposure. 0 0 16777215 16777215 The maximum mode to be accepted for an image to enter a stack. Per chip, not per exposure. FLAT OFF flatoffMinLineEdit 0 0 16777215 16777215 The minimum mode to be accepted for an image to enter a stack. Per chip, not per exposure. 0 0 16777215 16777215 The maximum mode to be accepted for an image to enter a stack. Per chip, not per exposure. 0 0 16777215 16777215 The minimum mode to be accepted for an image to enter a stack. Per chip, not per exposure. 0 0 16777215 16777215 The maximum mode to be accepted for an image to enter a stack. Per chip, not per exposure. FLAT flatMinLineEdit Qt::Vertical 20 17 Qt::Horizontal 182 20 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Chop / nod skysub (MIR) true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Chopnod pattern chopnodComboBox Qt::ClickFocus The chopnod pattern 0110 1001 0101 1010 pairwise Qt::ClickFocus Invert the pattern every 2nd time, e.g. 0110-1001-0110-1001 ... Invert chopnod pattern Qt::Vertical QSizePolicy::Fixed 20 20 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Background correction true 75 true (0) Grouping / exclude images 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Number of groups SPSnumbergroupsLineEdit 60 0 60 16777215 The number of groups in a sequence with different background characteristics Se&quence length SPSlengthLineEdit 60 0 60 16777215 The number of exposures in a sequence. E&xclude 'n' first exposures SPSlengthLineEdit 60 0 60 16777215 This many exposures are rejected at the beginning of a sequence of images at a given dither position 75 true (1) Object masking (optional) 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain &Mask expansion factor BACmefLineEdit 80 0 80 16777215 Increases the default object mask by this factor Combine method BACmethodComboBox Qt::ClickFocus Median is robust against outliers, but has higher noise. Median Mean Qt::ClickFocus Remove rough background model before object masking (recommended for NIR data) 2-pass model Qt::ClickFocus Convolution DT BACDTLineEdit 80 0 80 16777215 SExtractor detection threshold per pixel DMIN BACDMINLineEdit 80 0 80 16777215 SExtractor minimum number of connected pixels above the detection threshold 75 true (2) Reject pixels during combination 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain nlow nhigh 0 0 &1st pass BAC1nlowLineEdit 80 0 80 16777215 The number of low pixels removed from the stack 80 0 80 16777215 The number of high pixels removed from the stack 0 0 &2nd pass BAC2nlowLineEdit 80 0 80 16777215 The number of low pixels removed from the stack 80 0 80 16777215 The number of high pixels removed from the stack Qt::Vertical 20 22 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); true 75 true (3) Reject chips with bright stars 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Brighter than [ mag ] BACmagLineEdit 80 0 80 16777215 Chips containing stars brighter than this magnitude are excluded from the model Edge distance [ ' ] BACdistLineEdit 80 0 80 16777215 Chips are rejected if stars are located outside the chip less than this distance. 75 true (4) How to apply the model 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 0 0 Qt::ClickFocus How to apply the background model QComboBox::AdjustToMinimumContentsLength Subtract model Divide model Kernel width [ pixel ] 80 0 80 16777215 The smoothing scale for the background model (unsmoothed if left empty) 0 0 Qt::ClickFocus Rescale the model to each exposure. DO NOT do this for bright / extended sources. Rescale model 75 true (5) Static or dynamic mode 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain The mode is: STATIC Max gap size [hours] BACgapsizeLineEdit 80 0 80 16777215 A pause in the sequence longer than this marks a break point. Models do not extend over breakpoints. Window si&ze BACwindowLineEdit 80 0 80 16777215 How many contemporal images should be used to calculate the model. If empty or 0, all exposures will be used. 80 0 80 16777215 The minimum required window size. Equal to 'window size' if left empty. Min useful window size Qt::Vertical 20 40 Qt::Vertical 17 17 Qt::Horizontal 399 20 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Collapse correction true 75 true (1) Object masking true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 0 0 DT COCDTLineEdit 0 0 80 0 80 16777215 Detection threshold per pixel 0 0 DMIN COCDMINLineEdit 0 0 80 0 80 16777215 Minimum number of connected pixels above the detection threshold Qt::LeftToRight &Mask expansion factor Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter COCmefLineEdit 0 0 80 0 80 16777215 Increases the default object mask by this factor 75 true (2) Collapse parameters 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 0 0 Re&jection threshold COCrejectLineEdit 80 0 80 16777215 Sigma cutoff for pixels in a line/column. Default: 1.5 0 0 Collapse direction COCdirectionComboBox 0 0 44 44 44 44 Qt::ClickFocus Choose the gradient pattern that needs to be corrected. x y xy xyyx yxxy xxxx yyyy 75 true (3) Exclude this region 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 0 0 min COCxminLineEdit 0 0 max COCxminLineEdit 0 0 &x COCxminLineEdit 80 0 80 16777215 A rectangular region that should be excluded from the correction. Makes sense only for single-chip cameras. 80 0 80 16777215 A rectangular region that should be excluded from the correction. Makes sense only for single-chip cameras. Qt::Horizontal 80 20 0 0 y COCyminLineEdit 80 0 80 16777215 A rectangular region that should be excluded from the correction. Makes sense only for single-chip cameras. 80 0 80 16777215 A rectangular region that should be excluded from the correction. Makes sense only for single-chip cameras. Qt::Vertical QSizePolicy::Expanding 20 18 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Binned preview true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Binning BIPSpinBox 100 0 100 16777215 Qt::ClickFocus The binning factor for the mosaiced image. 1 Qt::ClickFocus Rejects the lowest and highest 10% of pixels from the binned image. Reject outliers Qt::Vertical 20 40 Qt::Horizontal 37 20 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Global weight maps true 75 true (1) Do not use the flat (?) 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Qt::ClickFocus Uses a constant weight of 1 for all pixels if checked. Same weight for all pixels 75 true (2) Allowed range for calibrators 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain min max BIAS / DARK [e-] CGWdarkminLineEdit 60 0 60 16777215 Pixels will be zero in the global weight if below this value in this reference image 60 0 60 16777215 Pixels will be zero in the global weight if above this value in this reference image Norm. FLAT [e-] CGWflatminLineEdit 60 0 60 16777215 Pixels will be zero in the global weight if below this value in this reference image 0.5 60 0 60 16777215 Pixels will be zero in the global weight if above this value in this reference image 1.5 Background [e-] CGWbackminLineEdit 60 0 60 16777215 Pixels will be zero in the global weight if below this value in this reference image 60 0 60 16777215 Pixels will be zero in the global weight if above this value in this reference image 75 true (3) Defect detection 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 Will smooth a flat / background map with some kernel, and then detect bad rows / columns / clusters in the difference image true QFrame::NoFrame QFrame::Plain FLAT BACK Kernel size [pix] CGWflatsmoothLineEdit 60 0 60 16777215 Kernel size (suggest: 100) 60 0 60 16777215 Kernel size (suggest: 30) Row tolerance CGWflatrowtolLineEdit 60 0 60 16777215 Pixels above this relative contrast in the difference image will be masked. Suggested value: 0.02 60 0 60 16777215 Pixels above this relative contrast in the difference image will be masked. Suggested value: 0.02 Column tolerance CGWflatcoltolLineEdit 60 0 60 16777215 Pixels above this relative contrast in the difference image will be masked. Suggested value: 0.02 60 0 60 16777215 Pixels above this relative contrast in the difference image will be masked. Suggested value: 0.02 Cluster tolerance CGWflatclustolLineEdit 60 0 60 16777215 Pixels above this relative contrast in the difference image will be masked. Suggested value: 0.1 60 0 60 16777215 Pixels above this relative contrast in the difference image will be masked. Suggested value: 0.1 Qt::Vertical 20 17 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Individual weight maps true 75 true (1) Dynamic range thresholding 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Image min value [e-] CIWminaduLineEdit 80 0 80 16777215 Pixels below this value will be masked Image max value [e-] CIWmaxaduLineEdit 80 0 80 16777215 Pixels above this value will be masked 75 true (2) Cosmetics 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain false Trigger level [e-] CIWbloomRangeLineEdit 80 0 80 16777215 The saturation value of blooming spikes may vary by this much across the CCD Qt::Horizontal 35 20 Range [e-] CIWbloomRangeLineEdit Min value [e-] CIWbloomMinaduLineEdit Qt::Horizontal 35 20 80 0 80 16777215 Values larger / smaller than 1.0 will mask more / less cosmics (SLOW). If zero or empty, no cosmics will be detected. 1.0 Qt::Horizontal 35 20 80 0 80 16777215 The min value to cut-off the background (10 sigma above mean background if empty) false Time scale [ min] CIWbloomRangeLineEdit Qt::Horizontal 35 20 Aggressiveness CIWaggressivenessLineEdit 0 0 0 153 153 153 230 230 230 191 191 191 76 76 76 102 102 102 0 0 0 255 255 255 0 0 0 255 255 255 153 153 153 0 0 0 204 204 204 255 255 220 0 0 0 0 0 0 153 153 153 230 230 230 191 191 191 76 76 76 102 102 102 0 0 0 255 255 255 0 0 0 255 255 255 153 153 153 0 0 0 204 204 204 255 255 220 0 0 0 76 76 76 153 153 153 230 230 230 191 191 191 76 76 76 102 102 102 76 76 76 255 255 255 76 76 76 153 153 153 153 153 153 0 0 0 153 153 153 255 255 220 0 0 0 50 false Qt::ClickFocus Check this if blooming spikes should be masked. Mask blooming spikes false 40 0 80 16777215 Minimum pixel level that triggers persistence. Cosmics and spurious pixels: CIWbloomMinaduLineEdit false 40 0 80 16777215 Images taken this many minutes before the current image will be considered. false 0 0 0 153 153 153 230 230 230 191 191 191 76 76 76 102 102 102 0 0 0 255 255 255 0 0 0 255 255 255 153 153 153 0 0 0 204 204 204 255 255 220 0 0 0 0 0 0 153 153 153 230 230 230 191 191 191 76 76 76 102 102 102 0 0 0 255 255 255 0 0 0 255 255 255 153 153 153 0 0 0 204 204 204 255 255 220 0 0 0 76 76 76 153 153 153 230 230 230 191 191 191 76 76 76 102 102 102 76 76 76 255 255 255 76 76 76 153 153 153 153 153 153 0 0 0 153 153 153 255 255 220 0 0 0 50 false Qt::ClickFocus Check this to mask pixels which suffer from image persistence Mask persistent pixels Masks saturated pixels. Mask saturated pixels 80 0 80 16777215 Tolerance. A vakue of 0.9 would mask pixels with values 0.9 or more of the saturation estimate. Qt::Vertical QSizePolicy::Fixed 20 20 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Separate target groups true true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain true Images with a linear pixel overlap larger than this value belong to the same target. Separation [ ' ] separateTargetLineEdit true 80 0 80 16777215 Image associations separated by at least this many arcminutes will form separate groups. Qt::Vertical 17 18 Qt::Horizontal 59 20 0 false 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Absolute photometry (indirect) true 75 true (1) General settings true false 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain STD CATALOG APIrefcatComboBox Qt::ClickFocus The reference catalog. Must contain your standard stars. LANDOLT_UBVRI STETSON_UBVRI STRIPE82_ugriz STRIPE82_u'g'r'i'z' SMITH_u'g'r'i'z' WASHINGTON MKO_JHK HUNT_JHK 2MASSfaint_JHK PERSSON_JHKKs JAC_YJHKLM MKO_LM STD FILTER APIfilterComboBox 0 0 80 16777215 Qt::ClickFocus The reference filter you want to use to calibrate your images STD COLOR APIcolorComboBox 0 0 80 16777215 Qt::ClickFocus The reference color index you want. Calibration mode APIcalibrationmodeComboBox Qt::ClickFocus Calculate one solution per night (NIGHTCALIB) or for all data (RUNCALIB) NIGHTCALIB RUNCALIB Aperture diameter [ pixel ] APIapertureLineEdit 80 0 80 16777215 The aperture diameter for the photometric measurement in your data. Your FILTER keyword APIfilterkeywordLineEdit 80 0 80 16777215 The filter keyword of your observations (just for the plots) 75 true (2) Fit parameters true false 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain EXTINCTION (fixed) APIextinctionLineEdit 80 0 80 16777215 A fixed value for the color term of your instrument 80 0 80 16777215 A fixed value for the extinction (must be negative) COLOR TERM (fixed) APIcolortermLineEdit &ZP min [ mag ] APIzpmaxLineEdit 80 0 80 16777215 Stars brighter than this magnitude in the reference catalog will be excluded from the fit. 80 0 80 16777215 The sigma threshold used to reject sources during the fit. Non-phot. cut-off [ mag ] APIthresholdLineEdit Con&vergence criterion APIconvergenceLineEdit 80 0 80 16777215 Sources this many mag below the fit are rejected (suggest: 0.15) 80 0 80 16777215 Min value of the zeropoint (to reject clearly false data points) ZP max [ mag ] APIzpmaxLineEdit 80 0 80 16777215 Max value of the zeropoint (to reject clearly false data points) Threshold [ sigma ] APIkappaLineEdit 80 0 80 16777215 ZP, extinction and color term change by less than this amount in one iteration step (suggest: 0.01) Min mag for STD catalog APIminmagLineEdit Qt::Vertical 288 17 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); true 75 true (3) Standard star astrometry true false 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain WCS uncertainty ["] APIWCSLineEdit 80 0 80 16777215 Match observation and reference within this many arcsec if no astrometric solution is performed. Qt::ClickFocus Find astrometric solution of standard star data. DO ASTROMETRY 30 30 30 30 0 0 0 85 170 255 213 234 255 149 202 255 42 85 127 56 113 170 0 0 0 255 255 255 0 0 0 255 255 255 85 170 255 0 0 0 170 212 255 255 255 220 0 0 0 0 0 0 85 170 255 213 234 255 149 202 255 42 85 127 56 113 170 0 0 0 255 255 255 0 0 0 255 255 255 85 170 255 0 0 0 170 212 255 255 255 220 0 0 0 42 85 127 85 170 255 213 234 255 149 202 255 42 85 127 56 113 170 42 85 127 255 255 255 42 85 127 85 170 255 85 170 255 0 0 0 85 170 255 255 255 220 0 0 0 Qt::ClickFocus ? 75 true (4) Select photometric solution(s) true false 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 0 0 Qt::ClickFocus PushButton 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 0 0 Qt::ClickFocus PushButton 0 0 140 0 Qt::ClickFocus Reject night Use fit # 1 Use fit # 2 Use fit # 3 Use fit # 4 No photometric solutions available. Qt::Vertical 20 68 Qt::Horizontal 46 20 0 0 0 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Source catalogs true (1) Detection true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Detection with 0 0 Qt::NoFocus THELI internal detection method or Source Extractor THELI Source Extractor DT CSCDTLineEdit Qt::Horizontal 49 20 80 0 80 16777215 Detection threshold per pixel DMIN CSCDTLineEdit Qt::Horizontal 40 20 80 0 80 16777215 Minimum number of connected pixels above the detection threshold DEBLEND CSCmincontLineEdit Qt::Horizontal 49 20 80 0 80 16777215 Deblending contrast. Min FWHM [pix] CSCFWHMLineEdit Qt::Horizontal 49 20 80 0 80 16777215 Min FWHM (pixel) for a source to be kept Qt::ClickFocus Turn off if the field is highly crowded, or if the PSF is undersampled AND lots of hot pixels are present. Convolution true (2) Filtering true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain The image value above which saturation occurs Saturation value [e-] 80 0 80 16777215 Max FLAG of a source to be kept 80 0 80 16777215 Manually fixed background level (in case the automatic value is very wrong) Background level 80 0 80 16777215 Saturation (or non-linearity, as you wish) starts above this level Max FLAG Qt::ClickFocus Check if image is well-sampled but has lots of hot pixels. Also consider turning off SExtractor filtering. Many hot pixels (3) Exposure rejection true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Min # of sources in any detector for good exposure true 80 0 80 16777215 Deactivate exposure if any chip has less than this many sources (e.g. due to clouds) Qt::Vertical 267 13 0 0 0 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Astrometric reference catalog true (1) Source true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Raised Qt::ClickFocus Retrieve the reference catalog from the Web Catalog from WEB true Qt::ClickFocus Retrieve the reference catalog from an astrometrically calibrated image Catalog from IMAGE (2) Settings true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Qt::Horizontal QSizePolicy::MinimumExpanding 52 13 0 0 150 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Retrieve the astrometric reference catalog Get catalog 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true 0 Catalog ARCcatalogComboBox 0 0 0 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 0 0 0 255 255 255 0 0 0 255 255 255 219 219 220 0 0 0 237 237 237 255 255 220 0 0 0 0 0 0 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 0 0 0 255 255 255 0 0 0 255 255 255 219 219 220 0 0 0 237 237 237 255 255 220 0 0 0 109 109 110 219 219 220 255 255 255 237 237 237 109 109 110 146 146 147 109 109 110 255 255 255 109 109 110 219 219 220 219 219 220 0 0 0 219 219 220 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Raised GAIA proper motions [ mas/yr ] true Max allowed pm ARCraLineEdit Qt::Horizontal 28 20 GAIA proper motions are corrected to the median epoch of the observations. Hence this parameter can stay empty. However, to measure proper motions across epochs it might be necessary to restrict proper motions in the reference catalog, OR you correct for the bulk proper motions for your field listed below.<br> The maximum proper motion allowed for a reference star Bulk pm in R.A. ARCraLineEdit 255 255 238 255 255 238 235 235 238 The median proper motion in RA along this line of sight (before filtering for max allowed pm) true Bulk pm in Dec ARCdecLineEdit 255 255 238 255 255 238 235 235 238 The median proper motion in DEC along this line of sight (before filtering for max allowed pm) true R.A. ARCraLineEdit Right ascension of your field (only if absent in FITS header) Dec ARCdecLineEdit Declination of your field (only if absent in FITS header) Target ARCtargetresolverLineEdit 30 30 30 30 Qt::ClickFocus Lookup the sky coordinates for the given target name (e.g. NGC 1234; only if absent in FITS header) false ... icons/magnifyer.pngicons/magnifyer.png 49 49 false true true Use target lookup to retrieve sky coordinates (e.g. NGC 1234; only if absent in FITS header) Mag limit ARCminmagLineEdit Faint magnitude limit of the reference catalog. No limit is applied if left empty. Radius [ ' ] ARCradiusLineEdit Search radius for the reference catalog (determined automatically if left empty) Qt::Vertical 20 13 Qt::ClickFocus The astrometric reference catalog GAIA-EDR3 PANSTARRS-DR1 SDSS-DR12 SKYMAPPER-DR1 VHS-DR4 2MASS UCAC5 ASCC TYC DT CSCDTLineEdit 80 0 80 16777215 SExtractor minimum number of connected pixels above the detection threshold 200 0 The full absolute path to an astrometrically calibrated reference image DMIN CSCDTLineEdit Qt::ClickFocus Select image with WCS [...] 80 0 80 16777215 SExtractor detection threshold per pixel Qt::Vertical 20 247 Qt::Vertical 326 17 Qt::Horizontal 13 20 0 0 0 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Astrometry / relative photometry true 75 true (1) Method true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 80 0 80 16777215 Detection threshold per pixel DMIN 80 0 80 16777215 Minimum number of connected pixels above the detection threshold DT false 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 Qt::ClickFocus Choose the astrometric solver Scamp Cross-correlation Header 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus FITS headers are updated with the 0th order WCS solution. This button restores the original header if necessary. Restore header 75 true (2) Matching true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Method ASTmosaictypeComboBox Qt::ClickFocus How the matching with the reference catalog is done. Scamp Astrometry.net Do not match POSANGLE_MAXERR ASTposangleLineEdit 80 0 100 16777215 Upper limit of the position angle uncertainty POSITION_MAXERR [ ' ] ASTpositionLineEdit 80 0 100 16777215 Upper limit of the sky position uncertainty PIXSCALE_MAXERR ASTpixscaleLineEdit 80 0 100 16777215 Upper limit of the plate scale uncertainty CROSSID_RADIUS [ " ] ASTcrossidLineEdit 80 0 100 16777215 Sources are matched with the reference catalog within this radius after matching has finished. Qt::ClickFocus Allow for mirrored images when doing the matching. Match flipped images 75 true (3) Solution context true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Raised 80 0 100 16777215 Relative weight of reference-source pairs compared to source-source pairs in the solution. ASTR_INSTRUKEY ASTastrinstrukeyLineEdit ASTREF_WEIGHT ASTastrefweightLineEdit 80 0 Separate photometric solutions for images having the same FITS keyword(s) value. Leave empty for a single solution. 80 0 100 16777215 S/N thresholds for the statistics. Two numbers, comma-separated SN_THRESHOLDS ASTsnthreshLineEdit 80 0 Separate astrometric solutions for images having the same FITS keyword(s) value. Leave empty for a single solution. PHOT_INSTRUKEY ASTphotinstrukeyLineEdit Qt::Vertical 17 13 0 0 0 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); true 75 true (4) Distortion true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 80 0 100 16777215 SExtractor keywords and FITS keywords. The latter must be preceded by a colon, e.g. ":AIRMASS" 80 0 100 16777215 Polynomial distortion degree(s) (comma-separated) DISTORT_GROUPS ASTdistortgroupsLineEdit DISTORT_KEYS ASTdistortkeysLineEdit 80 0 100 16777215 The number of distortion groups DISTORT_DEGREES ASTdistortLineEdit 75 true (5) Focal plane array handling true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain STABILITY_TYPE ASTstabilityComboBox Qt::ClickFocus Stability of the optical distortion INSTRUMENT EXPOSURE MOSAIC_TYPE ASTmosaictypeComboBox Qt::ClickFocus Defines how multi-chip cameras are handled. UNCHANGED SAME_CRVAL SHARE_PROJAXIS FIX_FOCALPLANE LOOSE FPA mode ASTfocalplaneComboBox Qt::ClickFocus Whether to use or recreate prior information of the relative chip positioning IGNORE_PRIOR USE_PRIOR NEW 0 0 30 0 30 16777215 85 170 255 85 170 255 85 170 255 75 true Qt::ClickFocus ? 75 true (6) Check plots true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Resolution ASTdistortLineEdit 80 0 100 16777215 The resolution of the scamp check plots Displays the astrometry check plots (if existing) View Qt::Vertical QSizePolicy::Fixed 20 20 false 0 0 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Star flat true false 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain CATALOG APDrefcatComboBox 100 0 100 16777215 Qt::ClickFocus SDSS PANSTARRS 2MASS FILTER true APDfilterComboBox 100 0 100 16777215 Qt::ClickFocus Error [ mag ] APDmaxphoterrorLineEdit 100 0 100 16777215 Qt::Vertical 20 18 Qt::Horizontal 56 20 0 0 0 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Sky subtraction true 75 true true (1) Method true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Qt::ClickFocus The sky is modeled after object masking &Model the sky true 0 0 30 0 30 16777215 85 170 255 85 170 255 85 170 255 75 true Qt::ClickFocus ? Qt::ClickFocus Fit a polynomial to empty sky areas selected by the user. Polynomial fit with degree Qt::Horizontal Qt::ClickFocus Subtracts a constant sky. Under (3) you must select either specific sky areas or entire chips. S&ubstract a constant sky Qt::ClickFocus Saves the sky models in a SKY_IMAGES/ subdirectory. Save sky model in SKY_IMAGES/ 0 0 60 0 60 16777215 Qt::ClickFocus The degree of the polynomial fit 2 4 75 true true (2) Object masking true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 0 0 DMIN skyDMINLineEdit 0 0 DT skyDTLineEdit 0 0 80 0 80 16777215 Detection threshold per pixel 0 0 80 0 80 16777215 Increases the default object mask by this factor 0 0 80 0 80 16777215 The width of the Gaussian smoothing kernel when modeling the sky 0 0 Kernel width [ pixel ] false skyKernelLineEdit Qt::LeftToRight Mask e&xpansion factor Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter skyMefLineEdit 0 0 80 0 80 16777215 Minimum number of connected pixels above the detection threshold 75 true true (3) Empty sky area(s) true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Choose 0 0 Qt::ClickFocus The empty sky areas from which background estimates should be obtained 18 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Using middle-click drag, select area(s) of empty sky regions in an astrometrically calibrated image. Launches iView. Select empty sky areas using the middle mouse button. Select sky area(s) Qt::Vertical 20 90 Qt::Horizontal 333 20 0 0 0 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Coaddition true 75 true true (1) Reference coordinates 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain R.A. COAraLineEdit 200 0 200 16777215 Reference RA (should be identical if stacks are created for different filters) Dec COAdecLineEdit 200 0 200 16777215 Reference Declination (should be identical if stacks are created for different filters) 75 true true (2) Resampling, stacking, zeropoint 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain 80 16777215 The plate scale to which the images should be resampled 80 0 80 16777215 The sky position angle. North Up and East left for 0 degrees (or empty) Combine method COAcombinetypeComboBox Qt::ClickFocus The method by which the resampled images should be combined WEIGHTED MEDIAN AVERAGE MIN MAX CHI-MEAN CHI-MODE CHI-OLD SUM WEIGHTED_WEIGHT MEDIAN_WEIGHT Resampling kernel COAkernelComboBox Qt::ClickFocus Resampling kernel. Use Lanczos3 for properly sampled images, and Lanczos2 for undersampled data. NEAREST BILINEAR LANCZOS2 LANCZOS3 LANCZOS4 Qt::ClickFocus The sky projection type. TAN Azp STG SIN ARC zpN ZEA AIR CYP CEA CAR MER COP COE COD COO BON PCO GLS PAR MOL AIT TSC CSC QSC NONE Qt::ClickFocus The celestial type. EQUATORIAL GALACTIC ECLIPTIC SUPERGALACTIC PIXEL Qt::ClickFocus Switch on for empty fields, only. Large objects will bias the internal rms estimate. Rescale WEIGHTS Plate scale [ " / pixel ] COApixscaleLineEdit Sky projection COAprojectionComboBox Celestial type COAcelestialtypeComboBox PA [ deg ] COAskypaLineEdit Qt::ClickFocus Set the sky position angle from the images From image Qt::Horizontal QSizePolicy::Ignored 40 20 75 true true (3) Outlier rejection 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain Threshold per pixel [ sigma ] COAoutthreshLineEdit 80 0 80 16777215 The sigma threshold for an individual pixel to be considered an outlier. # of connected bad pixels COAoutsizeLineEdit 80 0 80 16777215 Minimum number of connected pixels above the threshold required for an outlier Additional border [ pixel ] COAoutborderLineEdit 80 0 80 16777215 Add a border of this width around clusters of bad pixels Qt::Vertical 20 48 0 0 0 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 100 230 230 58 78 98 100 230 230 100 230 230 58 78 98 58 78 98 75 true false color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); true 75 true true (4) Setup 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain An identifier for the current coaddition 0 0 Coadd these chips, only (blank- or comma-separated list) Edge smoothing true COAedgesmoothingLineEdit 100 0 100 16777215 Edge smoothing length in pixels. Should correspond to the max dither step size in pixels. 100 0 100 16777215 Image geometry (NAXIS1) of the coadded image NAXIS1 COAsizexLineEdit 100 0 100 16777215 Image geometry (NAXIS2) of the coadded image NAXIS2 COAsizeyLineEdit Unique identifier COAuniqueidLineEdit Coadd chips COAchipsLineEdit 75 true (5) Non-sidereal targets true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain PM units COApmComboBox 0 0 100 0 100 16777215 Qt::ClickFocus Units of the proper motion vector [ " / sec ] [ " / min ] [ " / hour ] [ " / day ] PM in R.A. COApmraLineEdit 100 0 100 16777215 Proper motion vector in RA (coordinate motion). Image coaddition will be with respect to the moving target. PM in Dec COApmdecLineEdit 100 0 100 16777215 Proper motion vector in Dec (coordinate motion). Image coaddition will be with respect to the moving target. 75 true (6) Absolute photometry true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Plain true Qt::ClickFocus Loads the flux calibration module after the coaddition. (Currently deactivated. Load by clicking on the top cloud symbol) Perform flux calibration Qt::Vertical 17 124 Qt::Horizontal 12 20 Qt::ClickFocus Defaults for this page 60 0 60 16777215 0 0 0 255 255 170 255 255 255 255 255 212 127 127 85 170 170 113 0 0 0 255 255 255 0 0 0 255 255 255 255 255 170 0 0 0 255 255 212 255 255 220 0 0 0 0 0 0 255 255 170 255 255 255 255 255 212 127 127 85 170 170 113 0 0 0 255 255 255 0 0 0 255 255 255 255 255 170 0 0 0 255 255 212 255 255 220 0 0 0 127 127 85 255 255 170 255 255 255 255 255 212 127 127 85 170 170 113 127 127 85 255 255 255 127 127 85 255 255 170 255 255 170 0 0 0 255 255 170 255 255 220 0 0 0 Qt::ClickFocus << 60 0 60 16777215 0 0 0 255 255 170 255 255 255 255 255 212 127 127 85 170 170 113 0 0 0 255 255 255 0 0 0 255 255 255 255 255 170 0 0 0 255 255 212 255 255 220 0 0 0 0 0 0 255 255 170 255 255 255 255 255 212 127 127 85 170 170 113 0 0 0 255 255 255 0 0 0 255 255 255 255 255 170 0 0 0 255 255 212 255 255 220 0 0 0 127 127 85 255 255 170 255 255 255 255 255 212 127 127 85 170 170 113 127 127 85 255 255 255 127 127 85 255 255 170 255 255 170 0 0 0 255 255 170 255 255 220 0 0 0 Qt::ClickFocus >> Page Qt::Horizontal 40 20 normalxtalkAmplitudeLineEdit rowxtalkAmplitudeLineEdit biasNlowLineEdit biasNhighLineEdit darkNlowLineEdit darkNhighLineEdit flatoffNlowLineEdit flatoffNhighLineEdit flatNlowLineEdit flatNhighLineEdit biasMinLineEdit biasMaxLineEdit darkMinLineEdit darkMaxLineEdit flatoffMinLineEdit flatoffMaxLineEdit flatMinLineEdit flatMaxLineEdit SPSnumbergroupsLineEdit SPSlengthLineEdit SPSexcludeLineEdit BACDTLineEdit BACDMINLineEdit BACmefLineEdit BAC1nlowLineEdit BAC1nhighLineEdit BAC2nlowLineEdit BAC2nhighLineEdit BACmagLineEdit BACdistLineEdit BACbacksmoothscaleLineEdit BACwindowLineEdit BACminWindowLineEdit BACgapsizeLineEdit COCDTLineEdit COCDMINLineEdit COCmefLineEdit COCrejectLineEdit COCxminLineEdit COCxmaxLineEdit COCyminLineEdit COCymaxLineEdit CGWdarkminLineEdit CGWdarkmaxLineEdit CGWflatminLineEdit CGWflatmaxLineEdit CGWbackminLineEdit CGWbackmaxLineEdit CGWflatsmoothLineEdit CGWbacksmoothLineEdit CGWflatrowtolLineEdit CGWbackrowtolLineEdit CGWflatcoltolLineEdit CGWbackcoltolLineEdit CGWflatclustolLineEdit CGWbackclustolLineEdit CIWminaduLineEdit CIWmaxaduLineEdit CIWaggressivenessLineEdit CIWbloomMinaduLineEdit CIWbloomRangeLineEdit CIWpersistenceTimescaleLineEdit CIWpersistenceMinaduLineEdit separateTargetLineEdit APIapertureLineEdit APIfilterkeywordLineEdit APIextinctionLineEdit APIcolortermLineEdit APIzpminLineEdit APIzpmaxLineEdit APIkappaLineEdit APIthresholdLineEdit APIminmagLineEdit APIconvergenceLineEdit APIWCSLineEdit CSCDTLineEdit CSCDMINLineEdit CSCmincontLineEdit CSCFWHMLineEdit CSCmaxflagLineEdit CSCsaturationLineEdit CSCbackgroundLineEdit ARCmaxpmLineEdit ARCpmRALineEdit ARCpmDECLineEdit ARCraLineEdit ARCdecLineEdit ARCtargetresolverLineEdit ARCminmagLineEdit ARCradiusLineEdit ARCselectimageLineEdit ARCDTLineEdit ARCDMINLineEdit ASTxcorrDTLineEdit ASTxcorrDMINLineEdit ASTposangleLineEdit ASTpositionLineEdit ASTpixscaleLineEdit ASTcrossidLineEdit ASTastrefweightLineEdit ASTsnthreshLineEdit ASTastrinstrukeyLineEdit ASTphotinstrukeyLineEdit ASTdistortLineEdit ASTdistortgroupsLineEdit ASTdistortkeysLineEdit APDmaxphoterrorLineEdit skyDTLineEdit skyDMINLineEdit skyKernelLineEdit skyMefLineEdit COAraLineEdit COAdecLineEdit COApixscaleLineEdit COAskypaLineEdit COAoutthreshLineEdit COAoutsizeLineEdit COAoutborderLineEdit COAuniqueidLineEdit COAchipsLineEdit COAedgesmoothingLineEdit COAsizexLineEdit COAsizeyLineEdit COApmraLineEdit COApmdecLineEdit THELI-3.1.3/src/dockwidgets/defaults.cc000066400000000000000000000464601417631501300176120ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "confdockwidget.h" #include "ui_confdockwidget.h" #include "mainwindow.h" #include "ui_mainwindow.h" void ConfDockWidget::populateDefaultMap() { // These are the defaults that will be used if an empty parameter field // would be passed onto the scripts // Only LineEdits defaultMap.insert("APDmaxphoterrorLineEdit", "0.05"); defaultMap.insert("APIWCSLineEdit", "10"); defaultMap.insert("APIapertureLineEdit", "10"); defaultMap.insert("APIcolortermLineEdit", "0.0"); defaultMap.insert("APIconvergenceLineEdit", "0.01"); defaultMap.insert("APIextinctionLineEdit", "-0.1"); defaultMap.insert("APIfilterkeywordLineEdit", ""); defaultMap.insert("APIkappaLineEdit", "2.0"); defaultMap.insert("APIminmagLineEdit", "0"); defaultMap.insert("APIthresholdLineEdit", "0.15"); defaultMap.insert("APIzpmaxLineEdit", ""); defaultMap.insert("APIzpminLineEdit", ""); defaultMap.insert("ARCdecLineEdit", ""); defaultMap.insert("ARCmaxpmLineEdit", ""); defaultMap.insert("ARCminmagLineEdit", "25"); defaultMap.insert("ARCraLineEdit", ""); defaultMap.insert("ARCradiusLineEdit", ""); defaultMap.insert("ARCmaxpmLineEdit", ""); defaultMap.insert("ASTanetpixscaleLineEdit", "1.05"); defaultMap.insert("ASTastrefweightLineEdit", "1.0"); defaultMap.insert("ASTastrinstrukeyLineEdit", "FILTER"); defaultMap.insert("ASTcrossidLineEdit", "1.0"); defaultMap.insert("ASTdistortLineEdit", "3"); defaultMap.insert("ASTdistortgroupsLineEdit", ""); defaultMap.insert("ASTdistortkeysLineEdit", ""); defaultMap.insert("ASTfgroupLineEdit", "1.0"); defaultMap.insert("ASTphotinstrukeyLineEdit", "FILTER"); defaultMap.insert("ASTpixscaleLineEdit", "1.05"); defaultMap.insert("ASTposangleLineEdit", "2"); defaultMap.insert("ASTpositionLineEdit", "2.0"); defaultMap.insert("ASTresolutionLineEdit", "800"); defaultMap.insert("ASTsnthreshLineEdit", "5,20"); defaultMap.insert("BAC1nhighLineEdit", "0"); defaultMap.insert("BAC1nlowLineEdit", "0"); defaultMap.insert("BAC2nhighLineEdit", "0"); defaultMap.insert("BAC2nlowLineEdit", "0"); defaultMap.insert("BACDMINLineEdit", ""); defaultMap.insert("BACDTLineEdit", ""); defaultMap.insert("BACbacksmoothscaleLineEdit", ""); defaultMap.insert("BACdistLineEdit", ""); defaultMap.insert("BACfringesmoothscaleLineEdit", ""); defaultMap.insert("BACgapsizeLineEdit", ""); defaultMap.insert("BACmagLineEdit", ""); defaultMap.insert("BACmefLineEdit", ""); defaultMap.insert("BACwindowLineEdit", "0"); defaultMap.insert("BACminWindowLineEdit", ""); defaultMap.insert("CGWbackclustolLineEdit", ""); defaultMap.insert("CGWbackcoltolLineEdit", ""); defaultMap.insert("CGWbackmaxLineEdit", ""); defaultMap.insert("CGWbackminLineEdit", ""); defaultMap.insert("CGWbackrowtolLineEdit", ""); defaultMap.insert("CGWbacksmoothLineEdit", ""); defaultMap.insert("CGWdarkmaxLineEdit", ""); defaultMap.insert("CGWdarkminLineEdit", ""); defaultMap.insert("CGWflatclustolLineEdit", ""); defaultMap.insert("CGWflatcoltolLineEdit", ""); defaultMap.insert("CGWflatmaxLineEdit", "1.5"); defaultMap.insert("CGWflatminLineEdit", "0.5"); defaultMap.insert("CGWflatrowtolLineEdit", ""); defaultMap.insert("CGWflatsmoothLineEdit", ""); defaultMap.insert("CIWbloomRangeLineEdit", ""); defaultMap.insert("CIWbloomMinaduLineEdit", ""); defaultMap.insert("CIWbloomMinareaLineEdit", ""); defaultMap.insert("CIWaggressivenessLineEdit", ""); defaultMap.insert("CIWmaxaduLineEdit", ""); defaultMap.insert("CIWminaduLineEdit", ""); defaultMap.insert("COAchipsLineEdit", ""); defaultMap.insert("COAdecLineEdit", ""); defaultMap.insert("COAedgesmoothingLineEdit", ""); defaultMap.insert("COAmaxseeingLineEdit", ""); defaultMap.insert("COAminrzpLineEdit", ""); defaultMap.insert("COAoutborderLineEdit", ""); defaultMap.insert("COAoutsizeLineEdit", "4"); defaultMap.insert("COAoutthreshLineEdit", "3"); defaultMap.insert("COApmdecLineEdit", ""); defaultMap.insert("COApmraLineEdit", ""); defaultMap.insert("COAraLineEdit", ""); defaultMap.insert("COAsizexLineEdit", ""); defaultMap.insert("COAsizeyLineEdit", ""); defaultMap.insert("COAskypaLineEdit", ""); defaultMap.insert("COAuniqueidLineEdit", ""); defaultMap.insert("COCDMINLineEdit", "5"); defaultMap.insert("COCDTLineEdit", "1.5"); defaultMap.insert("COCmefLineEdit", ""); defaultMap.insert("COCrejectLineEdit", "1.5"); defaultMap.insert("COCxmaxLineEdit", ""); defaultMap.insert("COCxminLineEdit", ""); defaultMap.insert("COCymaxLineEdit", ""); defaultMap.insert("COCyminLineEdit", ""); defaultMap.insert("CSCDMINLineEdit", "5"); defaultMap.insert("CSCDTLineEdit", "5"); defaultMap.insert("CSCFWHMLineEdit", "1.5"); defaultMap.insert("CSCbackgroundLineEdit", ""); defaultMap.insert("CSCmaxflagLineEdit", "8"); defaultMap.insert("CSCmincontLineEdit", "0.0005"); defaultMap.insert("CSCminobjectsLineEdit", ""); defaultMap.insert("CSCsaturationLineEdit", "1.e8"); defaultMap.insert("CSCrejectExposureLineEdit", ""); defaultMap.insert("SPSlengthLineEdit", "10"); defaultMap.insert("SPSnumbergroupsLineEdit", "3"); defaultMap.insert("biasMaxLineEdit", ""); defaultMap.insert("biasMinLineEdit", ""); defaultMap.insert("biasNhighLineEdit", ""); defaultMap.insert("biasNlowLineEdit", ""); defaultMap.insert("darkMaxLineEdit", ""); defaultMap.insert("darkMinLineEdit", ""); defaultMap.insert("darkNhighLineEdit", ""); defaultMap.insert("darkNlowLineEdit", ""); defaultMap.insert("flatMaxLineEdit", ""); defaultMap.insert("flatMinLineEdit", ""); defaultMap.insert("flatNhighLineEdit", ""); defaultMap.insert("flatNlowLineEdit", ""); defaultMap.insert("flatoffMaxLineEdit", ""); defaultMap.insert("flatoffMinLineEdit", ""); defaultMap.insert("flatoffNhighLineEdit", ""); defaultMap.insert("flatoffNlowLineEdit", ""); defaultMap.insert("normalxtalkAmplitudeLineEdit", "0.0"); defaultMap.insert("overscanNhighLineEdit", ""); defaultMap.insert("overscanNlowLineEdit", ""); defaultMap.insert("rowxtalkAmplitudeLineEdit", "0.0"); defaultMap.insert("saturationLineEdit", ""); defaultMap.insert("separateTargetLineEdit", ""); defaultMap.insert("skyDMINLineEdit", "10"); defaultMap.insert("skyDTLineEdit", "1.5"); defaultMap.insert("skyKernelLineEdit", "256"); defaultMap.insert("skyMefLineEdit", ""); defaultMap.insert("skyOverrideLineEdit", ""); defaultMap.insert("skyVertex1LineEdit", ""); defaultMap.insert("skyVertex2LineEdit", ""); defaultMap.insert("skyVertex3LineEdit", ""); defaultMap.insert("skyVertex4LineEdit", ""); } void ConfDockWidget::loadDefaults() { // qDebug() << "loading" << sender(); if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0) { /* ui->setupMainLineEdit->clear(); ui->setupBiasLineEdit->clear(); ui->setupDarkLineEdit->clear(); ui->setupFlatLineEdit->clear(); ui->setupFlatoffLineEdit->clear(); ui->setupScienceLineEdit->clear(); ui->setupSkyLineEdit->clear(); ui->setupStandardLineEdit->clear(); */ // TODO: why do we need this again? for (auto &it: mainGUI->status.listCheckBox) { it->setChecked(false); } mainGUI->ui->plainTextEdit->clear(); } // TODO: use default map! if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 0)) { ui->xtalk_nor_2x2ToolButton->setChecked(true); ui->xtalk_row_2x2ToolButton->setChecked(true); ui->normalxtalkCheckBox->setChecked(false); ui->rowxtalkCheckBox->setChecked(false); ui->normalxtalkAmplitudeLineEdit->setText(""); ui->rowxtalkAmplitudeLineEdit->setText(""); ui->overscanCheckBox->setChecked(true); ui->theliRenamingCheckBox->setChecked(true); ui->nonlinearityCheckBox->setChecked(false); ui->nonlinearityCheckBox->setChecked(false); ui->splitMIRcubeCheckBox->setChecked(false); ui->biasNlowLineEdit->setText(""); ui->biasNhighLineEdit->setText(""); ui->darkNlowLineEdit->setText(""); ui->darkNhighLineEdit->setText(""); ui->excludeDetectorsLineEdit->clear(); ui->flatoffNlowLineEdit->setText(""); ui->flatoffNhighLineEdit->setText(""); ui->flatNlowLineEdit->setText(""); ui->flatNhighLineEdit->setText(""); ui->biasMinLineEdit->clear(); ui->biasMaxLineEdit->clear(); ui->darkMinLineEdit->clear(); ui->darkMaxLineEdit->clear(); ui->flatoffMinLineEdit->clear(); ui->flatoffMaxLineEdit->clear(); ui->flatMinLineEdit->clear(); ui->flatMaxLineEdit->clear(); ui->saturationLineEdit->clear(); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 1)) { // qDebug() << "background"; ui->SPSnumbergroupsLineEdit->clear(); ui->SPSlengthLineEdit->clear(); ui->chopnodComboBox->setCurrentIndex(0); ui->chopnodInvertCheckBox->setChecked(false); ui->BAC1nhighLineEdit->setText("0"); ui->BAC1nlowLineEdit->setText("0"); ui->BAC2nhighLineEdit->setText("0"); ui->BAC2nlowLineEdit->setText("0"); ui->BAC2passCheckBox->setChecked(true); ui->BACDMINLineEdit->setText("5"); ui->BACDTLineEdit->setText("1.5"); ui->BACapplyComboBox->setCurrentIndex(0); ui->BACbacksmoothscaleLineEdit->clear(); ui->BACconvolutionCheckBox->setChecked(false); ui->BACdistLineEdit->clear(); ui->BACgapsizeLineEdit->clear(); ui->BACmagLineEdit->clear(); ui->BACmefLineEdit->clear(); ui->BACmethodComboBox->setCurrentIndex(0); ui->BACrescaleCheckBox->setChecked(true); ui->BACwindowLineEdit->setText("0"); ui->BACminWindowLineEdit->clear(); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 2)) { ui->COCDMINLineEdit->setText("5"); ui->COCDTLineEdit->setText("1.5"); ui->COCdirectionComboBox->setCurrentIndex(0); ui->COCmefLineEdit->clear(); ui->COCrejectLineEdit->setText("1.5"); ui->COCxmaxLineEdit->clear(); ui->COCxminLineEdit->clear(); ui->COCymaxLineEdit->clear(); ui->COCyminLineEdit->clear(); ui->BIPSpinBox->setValue(1); ui->BIPrejectCheckBox->setChecked(false); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 3)) { ui->CGWbackclustolLineEdit->clear(); ui->CGWbackcoltolLineEdit->clear(); ui->CGWbackrowtolLineEdit->clear(); ui->CGWbacksmoothLineEdit->clear(); ui->CGWbackmaxLineEdit->clear(); ui->CGWbackminLineEdit->clear(); ui->CGWdarkmaxLineEdit->clear(); ui->CGWdarkminLineEdit->clear(); ui->CGWflatclustolLineEdit->clear(); ui->CGWflatcoltolLineEdit->clear(); ui->CGWflatmaxLineEdit->setText("1.5"); ui->CGWflatminLineEdit->setText("0.5"); ui->CGWflatrowtolLineEdit->clear(); ui->CGWflatsmoothLineEdit->clear(); ui->CGWsameweightCheckBox->setChecked(false); ui->CIWbloomRangeLineEdit->clear(); ui->CIWbloomMinaduLineEdit->clear(); ui->CIWaggressivenessLineEdit->clear(); ui->CIWmaskbloomingCheckBox->setChecked(false); ui->CIWmaxaduLineEdit->clear(); ui->CIWminaduLineEdit->clear(); ui->separateTargetLineEdit->setText(""); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 4)) { load_default_stdcat(); if (instrument_type == "NIR") { ui->APIrefcatComboBox->setCurrentText("MKO_JHK"); } else { ui->APIrefcatComboBox->setCurrentText("SMITH_u'g'r'i'z'"); } ui->APIWCSCheckBox->setChecked(true); ui->APIWCSLineEdit->setText("10"); ui->APIzpmaxLineEdit->clear(); ui->APIzpminLineEdit->clear(); ui->APIapertureLineEdit->setText("10"); ui->APIcalibrationmodeComboBox->setCurrentIndex(0); ui->APIcolorComboBox->setCurrentIndex(0); ui->APIcolortermLineEdit->setText("0.0"); ui->APIconvergenceLineEdit->setText("0.01"); ui->APIextinctionLineEdit->setText("-0.1"); ui->APIfilterComboBox->setCurrentIndex(0); ui->APIfilterkeywordLineEdit->clear(); ui->APIkappaLineEdit->setText("2.0"); ui->APIminmagLineEdit->clear(); ui->APIthresholdLineEdit->setText("0.15"); ui->APInight1ComboBox->setCurrentIndex(0); ui->APInight1PushButton->setChecked(false); ui->APInight2ComboBox->setCurrentIndex(0); ui->APInight2PushButton->setChecked(false); ui->APInight3ComboBox->setCurrentIndex(0); ui->APInight3PushButton->setChecked(false); ui->APInight4ComboBox->setCurrentIndex(0); ui->APInight4PushButton->setChecked(false); ui->APInight5ComboBox->setCurrentIndex(0); ui->APInight5PushButton->setChecked(false); ui->APInight6ComboBox->setCurrentIndex(0); ui->APInight6PushButton->setChecked(false); ui->APInight7ComboBox->setCurrentIndex(0); ui->APInight7PushButton->setChecked(false); ui->APInight8ComboBox->setCurrentIndex(0); ui->APInight8PushButton->setChecked(false); ui->APInight9ComboBox->setCurrentIndex(0); ui->APInight9PushButton->setChecked(false); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 5)) { load_default_stdcat(); ui->ARCcatalogComboBox->setCurrentIndex(0); ui->ARCdecLineEdit->clear(); ui->ARCminmagLineEdit->clear(); ui->ARCmaxpmLineEdit->clear(); ui->ARCDTLineEdit->setText("5"); ui->ARCDMINLineEdit->setText("5"); ui->ARCraLineEdit->clear(); ui->ARCradiusLineEdit->clear(); ui->ARCselectimageLineEdit->clear(); ui->ARCtargetresolverLineEdit->clear(); ui->ARCmaxpmLineEdit->clear(); ui->ARCpmRALineEdit->clear(); ui->ARCpmDECLineEdit->clear(); ui->CSCDMINLineEdit->setText("5"); ui->CSCDTLineEdit->setText("5"); ui->CSCFWHMLineEdit->setText("1.5"); ui->CSCbackgroundLineEdit->clear(); ui->CSCmaxflagLineEdit->setText("8"); ui->CSCmincontLineEdit->setText("0.0005"); ui->CSCrejectExposureLineEdit->clear(); ui->CSCsamplingCheckBox->setChecked(false); ui->CSCconvolutionCheckBox->setChecked(true); ui->CSCsaturationLineEdit->clear(); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 6)) { if (instrument_type == "NIR") { ui->APDrefcatComboBox->setCurrentText("SDSS"); } else { ui->APDrefcatComboBox->setCurrentText("2MASS"); } ui->APDfilterComboBox->setCurrentIndex(0); ui->APDfilterComboBox->setCurrentIndex(0); ui->APDmaxphoterrorLineEdit->setText("0.05"); ui->ASTastrefweightLineEdit->setText("1.0"); ui->ASTastrinstrukeyLineEdit->setText("FILTER"); ui->ASTcrossidLineEdit->setText("1.0"); ui->ASTdistortLineEdit->setText("3"); ui->ASTdistortgroupsLineEdit->clear(); ui->ASTdistortkeysLineEdit->clear(); ui->ASTmatchMethodComboBox->setCurrentIndex(0); ui->ASTmatchflippedCheckBox->setChecked(false); ui->ASTmethodComboBox->setCurrentIndex(0); if (instrument_nchips == 1) { ui->ASTmosaictypeComboBox->setCurrentIndex(0); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } else { ui->ASTmosaictypeComboBox->setCurrentIndex(4); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } ui->ASTphotinstrukeyLineEdit->setText("FILTER"); ui->ASTpixscaleLineEdit->setText("1.05"); ui->ASTposangleLineEdit->setText("2"); ui->ASTpositionLineEdit->setText("2.0"); ui->ASTresolutionLineEdit->setText("800"); ui->ASTsnthreshLineEdit->setText("5,20"); ui->ASTstabilityComboBox->setCurrentIndex(1); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 7)) { ui->skyAreaComboBox->setCurrentIndex(0); ui->skyConstsubRadioButton->setChecked(false); ui->skyDMINLineEdit->setText("10"); ui->skyDTLineEdit->setText("1.5"); ui->skyKernelLineEdit->setText("256"); ui->skyMefLineEdit->clear(); ui->skyModelRadioButton->setChecked(true); ui->skyPolynomialRadioButton->setChecked(false); ui->skyPolynomialSpinBox->setValue(1); ui->skySavemodelCheckBox->setChecked(false); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 8)) { ui->COAcelestialtypeComboBox->setCurrentIndex(0); ui->COAchipsLineEdit->clear(); ui->COAcombinetypeComboBox->setCurrentIndex(0); ui->COAdecLineEdit->clear(); ui->COAedgesmoothingLineEdit->clear(); ui->COAfluxcalibCheckBox->setChecked(false); ui->COAkernelComboBox->setCurrentIndex(3); ui->COAoutsizeLineEdit->setText("4"); ui->COAoutthreshLineEdit->setText("3"); ui->COAoutborderLineEdit->clear(); ui->COApixscaleLineEdit->setText(get_fileparameter(&instrument_file, "PIXSCALE")); ui->COApmComboBox->setCurrentIndex(0); ui->COApmdecLineEdit->clear(); ui->COApmraLineEdit->clear(); ui->COAprojectionComboBox->setCurrentIndex(0); ui->COAraLineEdit->clear(); ui->COArescaleweightsCheckBox->setChecked(false); ui->COAsizexLineEdit->clear(); ui->COAsizeyLineEdit->clear(); ui->COAskypaLineEdit->clear(); ui->COAuniqueidLineEdit->clear(); } } THELI-3.1.3/src/dockwidgets/memoryviewer.cc000066400000000000000000000614231417631501300205310ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "memoryviewer.h" #include "ui_memoryviewer.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "../myimage/myimage.h" #include "functions.h" #include "../processingInternal/controller.h" #include "../processingInternal/data.h" #include "../datamodel/datamodel.h" #include "../threading/memoryworker.h" #include #include #include #include #include #include #include MemoryViewer::MemoryViewer(Controller *ctrl, MainWindow *parent) : QDockWidget(parent), ui(new Ui::MemoryViewer) { ui->setupUi(this); mainGUI = parent; controller = ctrl; // connect(ui->memoryTableView, &QTableView::clicked, this, &MemoryViewer::writeCheckBoxClicked); connect(ui->procstatusHDUreformatCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusProcessscienceCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusChopnodCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusBackgroundCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusCollapseCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusStarflatCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusSkysubCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(this, &MemoryViewer::refreshMemoryViewer, mainGUI, &MainWindow::refreshMemoryViewerReceiver); QFile file(":/qss/default.qss"); file.open(QFile::ReadOnly); QString styleSheet = QString::fromLatin1(file.readAll()); qApp->setStyleSheet(styleSheet); QIcon download(":/icons/download.png"); QIcon upload(":/icons/upload.png"); ui->downloadToolButton->setIcon(download); ui->uploadToolButton->setIcon(upload); // Not sure what this button actually would do (that cannot be done with the checkboxes) ui->uploadToolButton->hide(); } MemoryViewer::~MemoryViewer() { /* for (auto &dataModel : dataModelList) { if (dataModel != nullptr) delete dataModel; } if (workerInit) delete worker; */ if (workerThreadInit) { workerThread->quit(); workerThread->wait(); // delete workerThread; } delete ui; } void MemoryViewer::populate() { ui->datadirComboBox->clear(); ui->restoreComboBox->clear(); dataModelList.clear(); // Add data from the defined data directories addData(controller->DT_SCIENCE, "SCI"); addData(controller->DT_SKY, "SKY"); addData(controller->DT_BIAS, "BIAS"); addData(controller->DT_DARK, "DARK"); addData(controller->DT_FLATOFF, "FLATOFF"); addData(controller->DT_FLAT, "FLAT"); addData(controller->DT_STANDARD, "STD"); addDataWeights(controller->DT_SCIENCE); addDataWeights(controller->DT_SKY); addDataWeights(controller->DT_STANDARD); addGlobalWeights(); on_datadirComboBox_currentIndexChanged(0); } void MemoryViewer::clearMemoryViewReceived() { // ui->datadirComboBox->clear(); // emit beginResetModel(); ui->memoryTableView->clearSpans(); ui->memoryTableView->setModel(emptyModel); ui->memoryTableView->resizeColumnsToContents(); ui->memoryTableView->resizeRowsToContents(); ui->memoryTableView->sortByColumn(0, Qt::AscendingOrder); ui->memoryTableView->horizontalHeader()->setStretchLastSection(true); ui->memoryTableView->show(); for (auto &model : dataModelList) { model->deleteLater(); } dataModelList.clear(); ui->datadirComboBox->clear(); ui->restoreComboBox->clear(); } void MemoryViewer::populateMemoryViewReceived() { populate(); if (dataModelList.isEmpty()) return; // emit endResetModel(); ui->datadirComboBox->setCurrentIndex(0); ui->memoryTableView->clearSpans(); ui->memoryTableView->setModel(dataModelList[0]); ui->memoryTableView->resizeColumnsToContents(); ui->memoryTableView->resizeRowsToContents(); ui->memoryTableView->sortByColumn(0, Qt::AscendingOrder); ui->memoryTableView->horizontalHeader()->setStretchLastSection(true); ui->memoryTableView->show(); /* for (auto &model : dataModelList) { delete model; model = nullptr; } */ } void MemoryViewer::addData(const QList &DT_x, const QString &type) { if (DT_x.isEmpty()) return; QStringList list; for (auto &data : DT_x) { if (data == nullptr || !data->dataInitialized || !data->dir.exists() || data->subDirName.isEmpty()) continue; list << type+":"+" "+data->subDirName; DataModel *dataModel = new DataModel(data); dataModel->setParent(this); dataModelList.append(dataModel); connect(this, &MemoryViewer::beginResetModel, dataModel, &DataModel::beginResetModelReceived, Qt::DirectConnection); connect(this, &MemoryViewer::endResetModel, dataModel, &DataModel::endResetModelReceived, Qt::DirectConnection); connect(dataModel, &DataModel::refreshMemoryViewer, mainGUI, &MainWindow::refreshMemoryViewerReceiver); connect(dataModel, &DataModel::activationWarning, controller, &Controller::activationWarningReceived); connect(dataModel, &DataModel::activationChanged, this, &MemoryViewer::activationChangedReceiver); } if (list.isEmpty()) return; ui->datadirComboBox->addItems(list); ui->datadirComboBox->update(); } void MemoryViewer::addDataWeights(const QList &DT_x) { if (DT_x.isEmpty()) return; QStringList list; QString weight = "WEIGHT:"; for (auto &data : DT_x) { if (!data->dataInitialized) continue; QDir weightDir(data->mainDirName+"/WEIGHTS"); if (!weightDir.exists()) continue; list << weight+" "+data->subDirName; DataModel *dataModel = new DataModel(data, "weight"); dataModel->setParent(this); dataModelList.append(dataModel); connect(this, &MemoryViewer::beginResetModel, dataModel, &DataModel::beginResetModelReceived, Qt::DirectConnection); connect(this, &MemoryViewer::endResetModel, dataModel, &DataModel::endResetModelReceived, Qt::DirectConnection); } if (list.isEmpty()) return; ui->datadirComboBox->addItems(list); ui->datadirComboBox->update(); } void MemoryViewer::addGlobalWeights() { if (controller->GLOBALWEIGHTS == nullptr || !controller->GLOBALWEIGHTS->dataInitialized || !controller->GLOBALWEIGHTS->dir.exists()) return; DataModel *dataModel = new DataModel(controller->GLOBALWEIGHTS); dataModel->setParent(this); dataModelList.append(dataModel); connect(this, &MemoryViewer::beginResetModel, dataModel, &DataModel::beginResetModelReceived, Qt::DirectConnection); connect(this, &MemoryViewer::endResetModel, dataModel, &DataModel::endResetModelReceived, Qt::DirectConnection); ui->datadirComboBox->addItem("GLOBALWEIGHTS"); ui->datadirComboBox->update(); } void MemoryViewer::on_datadirComboBox_currentIndexChanged(int index) { if (dataModelList.isEmpty() || index == -1) return; if (ui->datadirComboBox->count() == 0) return; if (mainGUI->doingInitialLaunch || mainGUI->readingSettings) return; ui->memoryTableView->clearSpans(); ui->memoryTableView->setModel(dataModelList[index]); ui->memoryTableView->resizeColumnsToContents(); ui->memoryTableView->resizeRowsToContents(); ui->memoryTableView->sortByColumn(0, Qt::AscendingOrder); ui->memoryTableView->horizontalHeader()->setStretchLastSection(true); ui->memoryTableView->show(); if (iViewOpen) { if (dataModelList[index]->modelType == "weight") iView->weightMode = true; else iView->weightMode = false; iView->myImageList = dataModelList[index]->imageList; iView->numImages = dataModelList[index]->imageList.length(); if (ui->datadirComboBox->currentText() == "GLOBALWEIGHTS") { iView->dirName = controller->mainDirName + "/GLOBALWEIGHTS"; } else { iView->dirName = controller->mainDirName + "/" + ui->datadirComboBox->currentText().split(":").at(1).simplified(); } } showhideStatusCheckBoxes(dataModelList[index]->modelType); updateStatusCheckBoxes(dataModelList[index]->myData); // Populate the restore mode accordingly ui->restoreComboBox->clear(); if (dataModelList[index]->modelType == "calib") { ui->restoreComboBox->insertItem(0, "RAWDATA"); } if (dataModelList[index]->modelType == "science") { QString status1 = ""; QString status2 = ""; QString status3 = ""; // Must test for empty when having done full data reset, and then selecting the "science" tab in the memory viewer if (!dataModelList[index]->imageList.isEmpty()) { status1 = dataModelList[index]->imageList[0]->statusBackupL1; status2 = dataModelList[index]->imageList[0]->statusBackupL2; status3 = dataModelList[index]->imageList[0]->statusBackupL3; } ui->restoreComboBox->addItem("RAWDATA"); if (!status1.isEmpty()) ui->restoreComboBox->addItem(status1+"_IMAGES"); if (!status2.isEmpty()) ui->restoreComboBox->addItem(status2+"_IMAGES"); if (!status3.isEmpty()) ui->restoreComboBox->addItem(status3+"_IMAGES"); addBackupDirs(dataModelList[index]->myData->dirName); } if (dataModelList[index]->modelType == "weight" || dataModelList[index]->modelType == "globalweight") { ui->restoreComboBox->setDisabled(true); ui->restorePushButton->setDisabled(true); } else { ui->restoreComboBox->setEnabled(true); ui->restorePushButton->setEnabled(true); } ui->restoreComboBox->update(); updateStatusTipRestoreButton(); } // triggered when a processing task has created a new backup dir. Only for the currently visible science data void MemoryViewer::addBackupDirReceived(QString scienceDir) { if (ui->datadirComboBox->currentText() == "SCI: "+scienceDir) { repopulateRestoreComboBox(); } } void MemoryViewer::addBackupDirs(const QString &dirName) { QDir dir(dirName); QDir dirCopy(dirName); dirCopy.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); if (dirCopy.count() == 0) return; QStringList dirList = dir.entryList(QDir::Dirs); for (auto &it : dirList) { // add the dir to the combobox if it is a true backup dir, and not yet contained in the combobox if (it.contains("_IMAGES") && ui->restoreComboBox->findText(it) == -1) { ui->restoreComboBox->addItem(it); } } ui->restoreComboBox->update(); // Qt 5.9 /* QDir dir(dirName); QStringList dirList = dir.entryList(QDir::Dirs); for (auto &it : dirList) { // add the dir to the combobox if it is a true backup dir, and not yet contained in the combobox if (it.contains("_IMAGES") && ui->restoreComboBox->findText(it) == -1 && !dir.isEmpty()) { ui->restoreComboBox->addItem(it); } } ui->restoreComboBox->update(); */ } void MemoryViewer::writeCheckBoxClicked(const QModelIndex &index) { workerThread = new QThread(this); worker = new MemoryWorker(this); workerInit = true; workerThreadInit = true; int cbindex = ui->datadirComboBox->currentIndex(); if (cbindex == -1) return; DataModel *model = dataModelList[cbindex]; if (model->imageList.isEmpty()) return; // Not sure this is ever happening worker->myImage = model->imageList[index.row()]; worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MemoryWorker::MemoryViewerDumpImagesToDrive); QObject::connect(worker, &MemoryWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); } /* void MemoryViewer::activeStateCheckBoxClicked(QModelIndex index) { workerThread = new QThread(this); worker = new MemoryWorker(this); workerInit = true; workerThreadInit = true; DataModel *model = dataModelList[ui->datadirComboBox->currentIndex()]; worker->myImage = model->imageList[index.row()]; worker->path = controller->mainDirName + "/" + ui->datadirComboBox->currentText(); worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MemoryWorker::processActiveStatusChanged); QObject::connect(worker, &MemoryWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); } */ /* void MemoryViewer::on_L0ToDrivePushButton_clicked() { ui->L0ToDrivePushButton->setText("Writing data ..."); ui->L0ToDrivePushButton->setDisabled(true); QTest::qWait(50); int index = ui->datadirComboBox->currentIndex(); #pragma omp parallel for num_threads(controller->maxExternalThreads) for (int i=0; iimageList.length(); ++i) { // TODO: check if status string is properly set MyImage *it = dataModelList[index]->imageList[i]; if (!it->imageOnDrive) { it->writeImage(it->path + "/" + it->baseName + controller->statusNew + ".fits"); it->imageOnDrive = true; it->emitModelUpdateNeeded(); } } ui->L0ToDrivePushButton->setText("Write L0 data to Drive"); ui->L0ToDrivePushButton->setEnabled(true); } */ void MemoryViewer::on_downloadToolButton_clicked() { workerThread = new QThread(this); worker = new MemoryWorker(this); workerInit = true; workerThreadInit = true; worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MemoryWorker::MemoryViewerDumpImagesToDrive); QObject::connect(worker, &MemoryWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); } void MemoryViewer::on_memoryTableView_clicked(const QModelIndex &index) { int cbindex = ui->datadirComboBox->currentIndex(); if (cbindex == -1) return; // don't show the image if the "active/deactivate" column is clicked if (index.column() == 1) return; // don't show the image if the "dump to drive" column is clicked if (index.column() == 2) return; DataModel *model = dataModelList[cbindex]; if (model->imageList.isEmpty()) return; // Not sure this is ever happening // CHECK: uncommented on 2019-10-02; should have no impact since unused // MyImage *myImage = model->imageList[index.row()]; if (!iViewOpen) { QString dirName = ""; if (ui->datadirComboBox->currentText() == "GLOBALWEIGHTS") { dirName = controller->mainDirName + "/GLOBALWEIGHTS"; } else { dirName = controller->mainDirName + "/" + ui->datadirComboBox->currentText().split(":").at(1).simplified(); } iView = new IView("MEMview", model->imageList, dirName, this); iViewOpen = true; if (model->modelType == "weight") iView->weightMode = true; else iView->weightMode = false; connect(iView, &IView::currentlyDisplayedIndex, this, &MemoryViewer::currentlyDisplayedIndex_received); connect(iView, &IView::destroyed, this, &MemoryViewer::iViewClosed_received); connect(iView, &IView::closed, this, &MemoryViewer::iViewClosed_received); } bool sourcecatShown = iView->sourcecatSourcesShown; bool refcatShown = iView->refcatSourcesShown; iView->clearItems(); iView->loadFromRAM(model->imageList[index.row()], index.column()); // iView->loadFromRAMlist(index); iView->currentId = index.row(); iView->setCatalogOverlaysExternally(sourcecatShown, refcatShown); iView->redrawSkyCirclesAndCats(); iView->show(); // iView->raise(); } void MemoryViewer::iViewClosed_received() { iViewOpen = false; } void MemoryViewer::activationChangedReceiver() { emit activationChanged(); } void MemoryViewer::currentlyDisplayedIndex_received(int currentId) { // Deselect current selection QModelIndex currentIndex = ui->memoryTableView->selectionModel()->currentIndex(); ui->memoryTableView->selectionModel()->setCurrentIndex(currentIndex, QItemSelectionModel::Deselect); int cbindex = ui->datadirComboBox->currentIndex(); if (cbindex == -1) return; // Make new selection QModelIndex index = dataModelList[cbindex]->index(currentId,0); ui->memoryTableView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select); } void MemoryViewer::on_restorePushButton_clicked() { Data *data = getDataClassThisModel(); if (data == nullptr) return; QString backupDir = ui->restoreComboBox->currentText(); if (backupDir.isEmpty()) return; data->restoreBackupLevel(backupDir); // ui->restoreComboBox->removeItem(ui->restoreComboBox->currentIndex()); repopulateRestoreComboBox(); // header line only changes if we manually resize the viewer, or: // quickly load the monitor, then the memory viewer again: emit refreshMemoryViewer(); } void MemoryViewer::hideStatusCheckBoxes() { ui->procstatusHDUreformatCheckbox->setVisible(false); ui->procstatusProcessscienceCheckbox->setVisible(false); ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(false); ui->procstatusCollapseCheckbox->setVisible(false); ui->procstatusStarflatCheckbox->setVisible(false); ui->procstatusSkysubCheckbox->setVisible(false); } void MemoryViewer::showhideStatusCheckBoxes(QString type) { hideStatusCheckBoxes(); return; // Never needed this /* Data *data = getDataClassThisModel(); if (data == nullptr) return; if (type == "science") { ui->procstatusHDUreformatCheckbox->setVisible(true); ui->procstatusProcessscienceCheckbox->setVisible(true); ui->procstatusCollapseCheckbox->setVisible(true); ui->procstatusSkysubCheckbox->setVisible(true); if (data->instData->type == "OPT") { ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(true); } else if (data->instData->type == "NIR") { ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(true); } else if (data->instData->type == "NIRMIR") { ui->procstatusChopnodCheckbox->setVisible(true); ui->procstatusBackgroundCheckbox->setVisible(true); } else if (data->instData->type == "MIR") { ui->procstatusChopnodCheckbox->setVisible(true); ui->procstatusBackgroundCheckbox->setVisible(false); } ui->procstatusStarflatCheckbox->setVisible(false); } else { ui->procstatusHDUreformatCheckbox->setVisible(true); ui->procstatusProcessscienceCheckbox->setVisible(false); ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(false); ui->procstatusCollapseCheckbox->setVisible(false); ui->procstatusStarflatCheckbox->setVisible(false); ui->procstatusSkysubCheckbox->setVisible(false); } */ } void MemoryViewer::updateStatusCheckBoxes(Data *data) { ui->procstatusHDUreformatCheckbox->setChecked(data->processingStatus->HDUreformat); ui->procstatusProcessscienceCheckbox->setChecked(data->processingStatus->Processscience); ui->procstatusChopnodCheckbox->setChecked(data->processingStatus->Chopnod); ui->procstatusBackgroundCheckbox->setChecked(data->processingStatus->Background); ui->procstatusCollapseCheckbox->setChecked(data->processingStatus->Collapse); ui->procstatusStarflatCheckbox->setChecked(data->processingStatus->Starflat); ui->procstatusSkysubCheckbox->setChecked(data->processingStatus->Skysub); } // reflect a status update in the currently shown checkboxes (if they represent the Data class that sent the signal) void MemoryViewer::updateStatusCheckBoxesReceived(QString statusString) { // The statusString arg is used by another slot in mainwindow.cc int index = ui->datadirComboBox->currentIndex(); if (dataModelList.isEmpty() || index == -1 || mainGUI->doingInitialLaunch) return; Data *data = qobject_cast(sender()); if (dataModelList[index]->myData == data) statusDataToCheckBox(data); } // Reflect the processingStatus of Data class in the checkboxes void MemoryViewer::statusDataToCheckBox(Data *data) { ui->procstatusHDUreformatCheckbox->setChecked(data->processingStatus->HDUreformat); ui->procstatusProcessscienceCheckbox->setChecked(data->processingStatus->Processscience); ui->procstatusChopnodCheckbox->setChecked(data->processingStatus->Chopnod); ui->procstatusBackgroundCheckbox->setChecked(data->processingStatus->Background); ui->procstatusCollapseCheckbox->setChecked(data->processingStatus->Collapse); ui->procstatusStarflatCheckbox->setChecked(data->processingStatus->Starflat); ui->procstatusSkysubCheckbox->setChecked(data->processingStatus->Skysub); } // Reflect the processingStatus of the checkboxes in the Data class void MemoryViewer::statusCheckBoxToData() { Data *data = getDataClassThisModel(); if (data == nullptr) return; data->processingStatus->HDUreformat = ui->procstatusHDUreformatCheckbox->isChecked(); data->processingStatus->Processscience = ui->procstatusProcessscienceCheckbox->isChecked(); data->processingStatus->Chopnod = ui->procstatusChopnodCheckbox->isChecked(); data->processingStatus->Background = ui->procstatusBackgroundCheckbox->isChecked(); data->processingStatus->Collapse = ui->procstatusCollapseCheckbox->isChecked(); data->processingStatus->Starflat = ui->procstatusStarflatCheckbox->isChecked(); data->processingStatus->Skysub = ui->procstatusSkysubCheckbox->isChecked(); } void MemoryViewer::projectResetReceived() { ui->restoreComboBox->clear(); ui->procstatusHDUreformatCheckbox->setChecked(false); ui->procstatusProcessscienceCheckbox->setChecked(false); ui->procstatusChopnodCheckbox->setChecked(false); ui->procstatusBackgroundCheckbox->setChecked(false); ui->procstatusCollapseCheckbox->setChecked(false); ui->procstatusStarflatCheckbox->setChecked(false); ui->procstatusSkysubCheckbox->setChecked(false); } Data* MemoryViewer::getDataClassThisModel() { int index = ui->datadirComboBox->currentIndex(); if (dataModelList.isEmpty() || index == -1 || mainGUI->doingInitialLaunch) return nullptr; return dataModelList[index]->myData; } void MemoryViewer::repopulateRestoreComboBox() { QString dirName = controller->mainDirName + "/" + ui->datadirComboBox->currentText().split(":").at(1).simplified(); QDir dir(dirName); if (!dir.exists()) return; // should never happen QStringList filters; filters << "RAWDATA" << "*_IMAGES"; QStringList backupdirList = dir.entryList(filters, QDir::Dirs); ui->restoreComboBox->clear(); // Add the directory only if it is not empty! ui->restoreComboBox->addItems(backupdirList); ui->restoreComboBox->update(); } void MemoryViewer::updateProcessingStatusOnDriveAndInData() { Data *data = getDataClassThisModel(); if (data == nullptr) return; statusCheckBoxToData(); data->processingStatus->getStatusString(); data->processingStatus->writeToDrive(); } void MemoryViewer::updateStatusTipRestoreButton() { if (ui->restoreComboBox->count() == 0 || ui->datadirComboBox->count() == 0) { ui->restorePushButton->setStatusTip("Restores certain processing stages"); return; } QString backupDir = ui->restoreComboBox->currentText(); QString dirName = ui->datadirComboBox->currentText().split(":").at(1).simplified(); QString statusTip = "Restores "+backupDir+" in " + dirName + ". Images currently present in "+dirName + " will be deleted!"; ui->restorePushButton->setStatusTip(statusTip); } void MemoryViewer::on_restoreComboBox_currentTextChanged(const QString &arg1) { updateStatusTipRestoreButton(); } THELI-3.1.3/src/dockwidgets/memoryviewer.h000066400000000000000000000065741417631501300204010ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MEMORYVIEWER_H #define MEMORYVIEWER_H #include "../processingInternal/controller.h" #include "../processingInternal/data.h" #include "../datamodel/datamodel.h" #include "../threading/memoryworker.h" #include "../iview/iview.h" #include #include #include #include #include class MainWindow; // forward declaration to access GUI members class MemoryWorker; // Not sure why I need this forward declaration (otherwise compiler error; the controller doesn't require it, otoh) class Controller; // only because of including memoryworker class DataModel; // only because of including memoryworker namespace Ui { class MemoryViewer; } class MemoryViewer : public QDockWidget { Q_OBJECT public: explicit MemoryViewer(Controller *ctrl, MainWindow *parent = 0); ~MemoryViewer(); MainWindow *mainGUI; Controller *controller; Ui::MemoryViewer *ui; // public, so that we can access its members from outside QList dataModelList; QThread *workerThread; MemoryWorker *worker; bool iViewOpen = false; private: void addData(const QList &DT_x, const QString &type); bool workerInit = false; bool workerThreadInit = false; IView *iView; DataModel *emptyModel = new DataModel(this); void addGlobalWeights(); void addDataWeights(const QList &DT_x); void addBackupDirs(const QString &dirName); void showhideStatusCheckBoxes(QString type); void updateStatusCheckBoxes(Data *data); void repopulateRestoreComboBox(); void statusDataToCheckBox(Data *data); void statusCheckBoxToData(); Data *getDataClassThisModel(); void hideStatusCheckBoxes(); public slots: void populate(); void clearMemoryViewReceived(); void populateMemoryViewReceived(); void addBackupDirReceived(QString scienceDir); void updateStatusCheckBoxesReceived(QString statusString); void projectResetReceived(); private slots: void on_datadirComboBox_currentIndexChanged(int index); void on_downloadToolButton_clicked(); // void activeStateCheckBoxClicked(QModelIndex index); void writeCheckBoxClicked(const QModelIndex &index); void on_memoryTableView_clicked(const QModelIndex &index); void currentlyDisplayedIndex_received(int currentId); void on_restorePushButton_clicked(); void updateProcessingStatusOnDriveAndInData(); void updateStatusTipRestoreButton(); void on_restoreComboBox_currentTextChanged(const QString &arg1); void iViewClosed_received(); void activationChangedReceiver(); signals: void beginResetModel(); void endResetModel(); void refreshMemoryViewer(); void activationChanged(); }; #endif // MEMORYVIEWER_H THELI-3.1.3/src/dockwidgets/memoryviewer.ui000066400000000000000000000262451417631501300205640ustar00rootroot00000000000000 MemoryViewer 0 0 709 574 QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Memory viewer Data shown: Qt::Horizontal QSizePolicy::Fixed 20 20 0 0 100 0 Qt::NoFocus The processing state you want to restore. QComboBox::AdjustToContents Qt::Horizontal QSizePolicy::Fixed 13 20 Qt::NoFocus Writes out Level 0 data in memory (current processing status) Write ../icons/download.png../icons/download.png 32 32 Qt::ToolButtonTextUnderIcon 0 0 160 0 Qt::NoFocus The data type for which memory and processing status are displayed. 25 QComboBox::AdjustToContents Qt::NoFocus Restores the displayed data to the selected processing state. Restore 0 0 0 Indicates whether a task was done. Change manually if there is a conflict between FITS files on drive and status in RAM. Chopnod (M) 0 0 Indicates whether a task was done. Change manually if there is a conflict between FITS files on drive and status in RAM. Background (B) 0 0 Indicates whether a task was done. Change manually if there is a conflict between FITS files on drive and status in RAM. HDUreformat (P) 0 0 Indicates whether a task was done. Change manually if there is a conflict between FITS files on drive and status in RAM. Process science (A) 0 0 0 Indicates whether a task was done. Change manually if there is a conflict between FITS files on drive and status in RAM. Skysub (S) 0 0 Indicates whether a task was done. Change manually if there is a conflict between FITS files on drive and status in RAM. Collapse (C) 0 0 Indicates whether a task was done. Change manually if there is a conflict between FITS files on drive and status in RAM. Starflat (D) Qt::Horizontal 127 20 Qt::NoFocus Updates the current state in memory with that on the drive. Sync ../icons/upload.png../icons/upload.png 32 32 Qt::ToolButtonTextUnderIcon 0 0 THELI-3.1.3/src/dockwidgets/monitor.cc000066400000000000000000000024141417631501300174610ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "monitor.h" #include "ui_monitor.h" #include "functions.h" #include #include Monitor::Monitor(QWidget *parent) : QDockWidget(parent), ui(new Ui::Monitor) { ui->setupUi(this); } Monitor::~Monitor() { delete ui; } void Monitor::displayMessage(QString text, QString type) { mutex.lock(); message(ui->monitorPlainTextEdit, text, type); mutex.unlock(); } void Monitor::appendOK() { ui->monitorPlainTextEdit->moveCursor(QTextCursor::End); ui->monitorPlainTextEdit->insertPlainText(" OK"); ui->monitorPlainTextEdit->moveCursor(QTextCursor::End); } THELI-3.1.3/src/dockwidgets/monitor.h000066400000000000000000000020631417631501300173230ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MONITOR_H #define MONITOR_H #include #include namespace Ui { class Monitor; } class Monitor : public QDockWidget { Q_OBJECT public: explicit Monitor(QWidget *parent = 0); ~Monitor(); Ui::Monitor *ui; QMutex mutex; public slots: void displayMessage(QString message, QString type); void appendOK(); private: }; #endif // MONITOR_H THELI-3.1.3/src/dockwidgets/monitor.ui000066400000000000000000000030211417631501300175040ustar00rootroot00000000000000 Monitor 0 0 659 335 QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Monitor Qt::NoFocus Displays output of currently ongoing processing tasks Qt::LeftToRight QFrame::Panel false QPlainTextEdit::WidgetWidth true Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse THELI-3.1.3/src/dockwidgets/validate_confdock.cc000066400000000000000000000522431417631501300214360ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "confdockwidget.h" #include "ui_confdockwidget.h" #include #include void ConfDockWidget::validate() { QRegExp ri( "^[0-9]+" ); QRegExp ricomma( "^[0-9,]+" ); QRegExp ricommablank( "^[0-9,\\s]+" ); QRegExp rint( "^[-]{0,1}[0-9]+" ); QRegExp rx( "^\\S+$" ); QRegExp RA( "[0-9.:]+" ); QRegExp DEC( "^[-]{0,1}[0-9.:]+" ); QRegExp rx3( "^[A-Z0-9a-z-+._,:]+$" ); QRegExp rx4( "^[A-Z0-9a-z-+_]+$" ); QRegExp rx5( "^[A-Z0-9a-z-+._, ]+$" ); QRegExp rf( "^[-]{0,1}[0-9]*[.]{0,1}[0-9]+" ); QRegExp rf2( "^[0-9]*[.]{0,1}[0-9]+" ); QValidator* validator_int_pos = new QRegExpValidator( ri, this ); QValidator* validator_int_pos_comma = new QRegExpValidator( ricomma, this ); QValidator* validator_int_pos_comma_blank = new QRegExpValidator( ricommablank, this ); QValidator* validator_int = new QRegExpValidator( rint, this ); QValidator* validator_string = new QRegExpValidator( rx, this ); QValidator* validator_ra = new QRegExpValidator( RA, this ); QValidator* validator_dec = new QRegExpValidator( DEC, this ); QValidator* validator_string3 = new QRegExpValidator( rx3, this ); QValidator* validator_headerkeyword = new QRegExpValidator( rx4, this ); QValidator* validator_stringdir = new QRegExpValidator( rx5, this ); QValidator* validator_float = new QRegExpValidator(rf, this ); QValidator* validator_float_pos = new QRegExpValidator(rf2, this ); ui->APDmaxphoterrorLineEdit->setValidator( validator_float_pos ); ui->APIWCSLineEdit->setValidator( validator_float_pos ); ui->APIapertureLineEdit->setValidator( validator_int_pos ); ui->APIcolortermLineEdit->setValidator( validator_float ); ui->APIconvergenceLineEdit->setValidator( validator_float_pos ); ui->APIextinctionLineEdit->setValidator( validator_float ); ui->APIfilterkeywordLineEdit->setValidator( validator_string ); ui->APIkappaLineEdit->setValidator( validator_float_pos ); ui->APIminmagLineEdit->setValidator( validator_float_pos ); ui->APIthresholdLineEdit->setValidator( validator_float_pos ); ui->APIzpmaxLineEdit->setValidator( validator_float_pos ); ui->APIzpminLineEdit->setValidator( validator_float_pos ); ui->ARCdecLineEdit->setValidator( validator_dec ); ui->ARCmaxpmLineEdit->setValidator( validator_float_pos ); ui->ARCminmagLineEdit->setValidator( validator_float_pos ); ui->ARCraLineEdit->setValidator( validator_ra ); ui->ARCradiusLineEdit->setValidator( validator_float_pos ); ui->ARCselectimageLineEdit->setValidator( validator_string ); ui->ARCtargetresolverLineEdit->setValidator( validator_stringdir ); ui->ASTastrefweightLineEdit->setValidator( validator_float_pos ); ui->ASTastrinstrukeyLineEdit->setValidator( validator_headerkeyword ); ui->ASTcrossidLineEdit->setValidator( validator_float_pos ); ui->ASTdistortLineEdit->setValidator( validator_int_pos ); ui->ASTdistortgroupsLineEdit->setValidator( validator_int_pos_comma ); ui->ASTdistortkeysLineEdit->setValidator( validator_string3 ); ui->ASTphotinstrukeyLineEdit->setValidator( validator_headerkeyword ); ui->ASTpixscaleLineEdit->setValidator( validator_float_pos ); ui->ASTposangleLineEdit->setValidator( validator_float_pos ); ui->ASTpositionLineEdit->setValidator( validator_float_pos ); ui->ASTresolutionLineEdit->setValidator( validator_int_pos ); ui->ASTsnthreshLineEdit->setValidator( validator_int_pos_comma ); ui->ASTxcorrDMINLineEdit->setValidator( validator_int_pos ); ui->ASTxcorrDTLineEdit->setValidator( validator_float_pos ); ui->BAC1nhighLineEdit->setValidator( validator_int_pos ); ui->BAC1nlowLineEdit->setValidator( validator_int_pos); ui->BAC2nhighLineEdit->setValidator( validator_int_pos ); ui->BAC2nlowLineEdit->setValidator( validator_int_pos ); ui->BACDMINLineEdit->setValidator( validator_int_pos ); ui->BACDTLineEdit->setValidator( validator_float_pos); ui->BACbacksmoothscaleLineEdit->setValidator( validator_int_pos ); ui->BACdistLineEdit->setValidator( validator_float_pos ); ui->BACgapsizeLineEdit->setValidator( validator_float_pos); ui->BACmagLineEdit->setValidator( validator_float_pos ); ui->BACmefLineEdit->setValidator( validator_float_pos ); ui->BACwindowLineEdit->setValidator( validator_int_pos ); ui->BACminWindowLineEdit->setValidator( validator_int_pos ); ui->CGWbackclustolLineEdit->setValidator( validator_float_pos); ui->CGWbackcoltolLineEdit->setValidator( validator_float_pos ); ui->CGWbackrowtolLineEdit->setValidator( validator_float_pos); ui->CGWbacksmoothLineEdit->setValidator( validator_float_pos ); ui->CGWbackmaxLineEdit->setValidator( validator_float_pos ); ui->CGWbackminLineEdit->setValidator( validator_float_pos ); ui->CGWdarkmaxLineEdit->setValidator( validator_int ); ui->CGWdarkminLineEdit->setValidator( validator_int ); ui->CGWflatclustolLineEdit->setValidator( validator_float_pos ); ui->CGWflatcoltolLineEdit->setValidator( validator_float_pos ); ui->CGWflatmaxLineEdit->setValidator( validator_float_pos ); ui->CGWflatminLineEdit->setValidator( validator_float_pos ); ui->CGWflatrowtolLineEdit->setValidator( validator_float_pos ); ui->CGWflatsmoothLineEdit->setValidator( validator_float_pos ); ui->CIWsaturationLineEdit->setValidator( validator_float_pos ); ui->CIWbloomRangeLineEdit->setValidator( validator_int_pos ); ui->CIWbloomMinaduLineEdit->setValidator( validator_int_pos ); ui->CIWaggressivenessLineEdit->setValidator( validator_float_pos ); ui->CIWmaxaduLineEdit->setValidator( validator_int ); ui->CIWminaduLineEdit->setValidator( validator_int ); ui->COAchipsLineEdit->setValidator( validator_int_pos_comma_blank ); ui->COAdecLineEdit->setValidator( validator_dec ); ui->COAedgesmoothingLineEdit->setValidator( validator_int_pos ); ui->COAoutborderLineEdit->setValidator( validator_int_pos ); ui->COAoutsizeLineEdit->setValidator( validator_int_pos ); ui->COAoutthreshLineEdit->setValidator( validator_float_pos ); ui->COApixscaleLineEdit->setValidator( validator_float_pos ); ui->COApmdecLineEdit->setValidator( validator_float ); ui->COApmraLineEdit->setValidator( validator_float ); ui->COAraLineEdit->setValidator( validator_ra ); ui->COAsizexLineEdit->setValidator( validator_int_pos ); ui->COAsizeyLineEdit->setValidator( validator_int_pos ); ui->COAskypaLineEdit->setValidator( validator_float ); ui->COAuniqueidLineEdit->setValidator( validator_string ); ui->COCDMINLineEdit->setValidator( validator_int_pos ); ui->COCDTLineEdit->setValidator( validator_float_pos ); ui->COCmefLineEdit->setValidator( validator_float_pos ); ui->COCrejectLineEdit->setValidator( validator_float_pos ); ui->COCxmaxLineEdit->setValidator( validator_int_pos ); ui->COCxminLineEdit->setValidator( validator_int_pos ); ui->COCymaxLineEdit->setValidator( validator_int_pos ); ui->COCyminLineEdit->setValidator( validator_int_pos ); ui->CSCDMINLineEdit->setValidator( validator_int_pos ); ui->CSCDTLineEdit->setValidator( validator_float_pos ); ui->CSCFWHMLineEdit->setValidator( validator_float_pos ); ui->CSCbackgroundLineEdit->setValidator( validator_float ); ui->CSCmaxflagLineEdit->setValidator( validator_int_pos ); ui->CSCmincontLineEdit->setValidator( validator_float_pos ); ui->CSCrejectExposureLineEdit->setValidator( validator_int_pos ); ui->CSCsaturationLineEdit->setValidator( validator_int_pos ); ui->SPSlengthLineEdit->setValidator( validator_int_pos ); ui->SPSexcludeLineEdit->setValidator( validator_int_pos ); ui->SPSnumbergroupsLineEdit->setValidator( validator_int_pos ); ui->biasMaxLineEdit->setValidator( validator_int_pos ); ui->biasMinLineEdit->setValidator( validator_int_pos ); ui->biasNhighLineEdit->setValidator( validator_int_pos ); ui->biasNlowLineEdit->setValidator( validator_int_pos ); ui->darkMaxLineEdit->setValidator( validator_int_pos ); ui->darkMinLineEdit->setValidator( validator_int_pos ); ui->darkNhighLineEdit->setValidator( validator_int_pos ); ui->darkNlowLineEdit->setValidator( validator_int_pos ); ui->excludeDetectorsLineEdit->setValidator( validator_int_pos_comma_blank ); ui->flatoffMaxLineEdit->setValidator( validator_int_pos ); ui->flatoffMinLineEdit->setValidator( validator_int_pos ); ui->flatoffNhighLineEdit->setValidator( validator_int_pos ); ui->flatoffNlowLineEdit->setValidator( validator_int_pos ); ui->flatMaxLineEdit->setValidator( validator_int_pos ); ui->flatMinLineEdit->setValidator( validator_int_pos ); ui->flatNhighLineEdit->setValidator( validator_int_pos ); ui->flatNlowLineEdit->setValidator( validator_int_pos ); ui->normalxtalkAmplitudeLineEdit->setValidator( validator_float ); ui->rowxtalkAmplitudeLineEdit->setValidator( validator_float ); ui->saturationLineEdit->setValidator( validator_int_pos ); ui->separateTargetLineEdit->setValidator( validator_float_pos ); ui->skyDMINLineEdit->setValidator( validator_int_pos ); ui->skyDTLineEdit->setValidator( validator_float_pos ); ui->skyKernelLineEdit->setValidator( validator_int_pos ); ui->skyMefLineEdit->setValidator( validator_float_pos ); } void ConfDockWidget::connect_validators() { connect(ui->APDmaxphoterrorLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIWCSLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIapertureLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIcolortermLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIconvergenceLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIextinctionLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIfilterkeywordLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIkappaLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIminmagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIthresholdLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIzpmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIzpminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCdecLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCminmagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCraLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCradiusLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCselectimageLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCtargetresolverLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTastrefweightLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTastrinstrukeyLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTcrossidLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTdistortLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTdistortgroupsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTdistortkeysLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTphotinstrukeyLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTpixscaleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTposangleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTpositionLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTresolutionLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTsnthreshLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC1nhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC1nlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC2nhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC2nlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACbacksmoothscaleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACdistLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACgapsizeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACmagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACmefLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACwindowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACminWindowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackclustolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackcoltolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackrowtolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbacksmoothLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWdarkmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWdarkminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatclustolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatcoltolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatrowtolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatsmoothLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWbloomRangeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWsaturationLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWbloomMinaduLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWaggressivenessLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWmaxaduLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWminaduLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAchipsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAdecLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAedgesmoothingLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAoutborderLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAoutsizeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAoutthreshLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COApixscaleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COApmdecLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COApmraLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAraLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAsizexLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAsizeyLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAskypaLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAuniqueidLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCmefLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCrejectLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCxmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCxminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCymaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCyminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCFWHMLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCbackgroundLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCmaxflagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCmincontLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCrejectExposureLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCsaturationLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->SPSlengthLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->SPSexcludeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->SPSnumbergroupsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->excludeDetectorsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->normalxtalkAmplitudeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->rowxtalkAmplitudeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->saturationLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->separateTargetLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyKernelLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyMefLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); } THELI-3.1.3/src/functions.cc000066400000000000000000001517521417631501300155050ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "functions.h" #include "preferences.h" #include "instrumentdata.h" #include "tools/fitgauss1d.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include QString boolToString(bool test) { if (test) return "Y"; else return "N"; } QStringList datadir2StringList(QLineEdit *lineEdit) { QStringList list; QString entrystring = lineEdit->text(); if (entrystring.isEmpty()) { return list; } entrystring.replace(",", " "); entrystring = entrystring.simplified(); return entrystring.split(" "); } QString get_fileparameter(QFile *file, QString parametername, QString warn) { if (file->fileName().isEmpty()) return ""; // Suppressing an error when the user launches THELI for the very first time if(!file->open(QIODevice::ReadOnly)) { qDebug() << __func__ << file->fileName() << file->errorString(); return ""; } QTextStream in(file); while(!in.atEnd()) { QString line = in.readLine(); if (!line.contains(parametername+"=")) continue; else { QString value = line.split("=")[1]; file->close(); return value; } } file->close(); if (!warn.isEmpty()) { QMessageBox::warning(0, "Error reading parameter from config", "Did not find variable "+parametername+" in "+file->fileName()+" !\nReturning empty string."); } return ""; } /* // same as above, but for .head files with additional (undesired) comment strings, and a card length of 8 chars QString get_fileHeaderParameter(QFile *file, QString parametername) { if(!file->open(QIODevice::ReadOnly)) { qDebug() << "get_fileparameter: "+file->fileName()+" "+file->errorString(); return ""; } QTextStream in(file); QString filename = file->fileName(); while(!in.atEnd()) { QString line = in.readLine(); QString keyName = parametername; keyName.resize(8, ' '); if (!line.contains(keyName+"=")) continue; else { QString value = line.split("=")[1]; value.truncate(value.lastIndexOf('/')); value = value.simplified(); file->close(); return value; } } file->close(); QMessageBox::warning(0, "Error reading parameter from config", "Did not find variable "+parametername+" in "+filename+" !\nReturning empty string."); return ""; } */ QString sanityCheckWCS(const wcsprm *wcs) { double det = wcs->cd[0]*wcs->cd[3] - wcs->cd[1]*wcs->cd[2]; if (det == 0.) return "WCS matrix is singular: "+ QString::number(wcs->cd[0],'g',5) + QString::number(wcs->cd[1],'g',5) + QString::number(wcs->cd[2],'g',5) + QString::number(wcs->cd[3],'g',5); else { // Test for significant shear double pscale1 = sqrt(wcs->cd[0]*wcs->cd[0] + wcs->cd[2]*wcs->cd[2]); double pscale2 = sqrt(wcs->cd[1]*wcs->cd[1] + wcs->cd[3]*wcs->cd[3]); double meanPlateScale = 0.5*(pscale1+pscale2); // take out the pixel scale double cd11 = wcs->cd[0] / meanPlateScale; double cd12 = wcs->cd[1] / meanPlateScale; double cd21 = wcs->cd[2] / meanPlateScale; double cd22 = wcs->cd[3] / meanPlateScale; // CD matrix should be nearly orthogonal, i.e. det = +/- 1 det = cd11*cd22 - cd12*cd21; if (fabs(det)-1. > 0.05) { return "WCS matrix is significantly sheared"; } } return ""; } /* void listSwapLastPairs(QStringList &stringlist, int n) { // At some point during creation of the commandList, we need to swap pairs // or triplets of execution commands and log scans (meesage, run, scan). // E.g. Before: ... L3 L2 L1 L0 then: L1 L0 L3 L2 // E.g. Before: ... L5 L4 L3 L2 L1 L0 then: L2 L1 L0 L5 L4 L3 if (n<2 || n>4) { qDebug() << "listSwapLastPairs: n must be 2, 3 or 4, you have used " << n; return; } int l0 = stringlist.length()-1; int l1 = l0-1; int l2 = l0-2; int l3 = l0-3; int l4 = l0-4; int l5 = l0-5; int l6 = l0-6; int l7 = l0-7; if (n==2) { stringlist.swap(l2,l0); stringlist.swap(l3,l1); } if (n==3) { stringlist.swap(l3,l0); stringlist.swap(l4,l1); stringlist.swap(l5,l2); } if (n==4) { stringlist.swap(l4,l0); stringlist.swap(l5,l1); stringlist.swap(l6,l2); stringlist.swap(l7,l3); } } */ /* QString translateServer(QString downloadServer) { QString server; if ( downloadServer == "France" ) server = "vizier.unistra.fr"; else if ( downloadServer == "USA" ) server = "vizier.cfa.harvard.edu"; else if ( downloadServer == "Canada" ) server = "vizier.hia.nrc.ca"; else if ( downloadServer == "Japan" ) server = "vizier.nao.ac.jp"; else if ( downloadServer == "India" ) server = "vizier.iucaa.in"; else if ( downloadServer == "China" ) server = "vizier.china-vo.org"; else if ( downloadServer == "UK" ) server = "vizier.ast.cam.ac.uk"; else server = "vizieridia.saao.ac.za"; return server; } */ // UNUSED void selectFirstActiveItem(QComboBox *cb) { // This function selects the first enabled item in a combobox // (if the enabled status has changed from the outside) const QStandardItemModel* model = dynamic_cast< QStandardItemModel * >( cb->model() ); for (int i=0; icount(); ++i) { if (model->item(i,0)->isEnabled()) cb->setCurrentIndex(i); break; } } long numFilesDir(QString path, QString filter) { QDir dir(path); long numFiles; if (dir.exists()) { QStringList filterList; filterList << filter; dir.setNameFilters(filterList); QStringList fileList = dir.entryList(); numFiles = fileList.length(); } else numFiles = 0; return numFiles; } /* // Get the first vector entry from a parameter in the camera.ini files QString get_fileparameter_vector(QFile *file, QString parametername, QString warn) { if(!file->open(QIODevice::ReadOnly)) { qDebug() << "QDEBUG:: get_fileparameter_vector: "+file->fileName()+" "+file->errorString(); return ""; } QTextStream in(file); while(!in.atEnd()) { QString line = in.readLine(); if (!line.contains(parametername+"=")) continue; else { QString value = line.split("=").at(2).split(" ").at(0); value.replace(")",""); value = value.simplified(); file->close(); return value; } } file->close(); if (!warn.isEmpty()) { QMessageBox::warning(0, "Error reading parameter from config", "Did not find variable "+parametername+" in "+file->fileName()+" !\nReturning empty string."); } return ""; } */ /* // Get the full vector entry from a parameter in the camera.ini files // THE FILE IS OPENED / CLOSED EXTERNALLY to avoid repeated file handle operations // NOTE: already subtracting -1 to make it conform with C++ indexing QVector get_fileparameter_FullVector(QFile *file, QString parametername) { QVector result; // Reset file to beginning file->seek(0); QTextStream in(file); while(!in.atEnd()) { QString line = in.readLine(); if (!line.contains(parametername+"=")) continue; line = line.replace('=',' ').replace(')',' ').replace(")",""); line = line.simplified(); QStringList values = line.split(" "); for (int i=2; ishow(); } } void message(QPlainTextEdit *pte, QString text, QString type) { if (type == "ignore") { pte->appendHtml(text); return; } if (type == "append") { pte->moveCursor(QTextCursor::End); pte->appendHtml(" "+text); pte->moveCursor(QTextCursor::End); return; } QString color; if (type == "") { if (text.contains("STOP")) color = "#ee0000"; else if (text.contains("NOTE")) color = "#00aa00"; else if (text.contains("INFO")) color = "#0000dd"; else color = "#000000"; } else if (type == "stop") color = "#ee0000"; // red else if (type == "error") color = "#ee0000"; // red else if (type == "warning") color = "#ee5500"; // orange else if (type == "note") color = "#009955"; // green else if (type == "image") color = "#000000"; // black else if (type == "info") color = "#0033cc"; // blue else if (type == "data") color = "#0033cc"; // blue else if (type == "output") color = "#8800aa"; // purple else if (type == "controller") color = "#8800aa"; // purple else if (type == "config") color = "#006666"; // turquois else color = "#000000"; // black // if (type == "image") text.prepend("IMAG: "); // if (type == "data") text.prepend("DATA: "); // else if (type == "controller") text.prepend("CTRL: "); if (type == "error") text.prepend("ERROR: "); pte->appendHtml(""+text+""); } void fill_combobox(QComboBox *combobox, QString string) { QStringList list = string.split(" "); combobox->clear(); combobox->addItems(list); } void paintPathLineEdit(QLineEdit *linedit, QString name, QString check) { QPalette palette_exists, palette_notexists, palette_empty; palette_exists.setColor(QPalette::Base,QColor("#a9ffe6")); palette_notexists.setColor(QPalette::Base,QColor("#ff99aa")); palette_empty.setColor(QPalette::Base,QColor(255,255,255)); // White background if field is empty. Return if there is nothing else to do. if (name.isEmpty()) { linedit->setPalette(palette_empty); return; } // Green background if dir/file exists, orange otherwise if (check == "dir") { QDir dir = QDir(name); if (dir.exists()) linedit->setPalette(palette_exists); else linedit->setPalette(palette_notexists); } else { QFile file(name); QFileInfo fileinfo(file); if (file.exists() && fileinfo.isFile()) linedit->setPalette(palette_exists); else linedit->setPalette(palette_notexists); } } long remainingDataDriveSpace(QString maindir) { // Remaining space in MB on the data drive double GBfree_data = 0.; QStorageInfo storage_data(maindir); if (storage_data.isValid() && storage_data.isReady()) { GBfree_data = storage_data.bytesAvailable()/1024./1024.; } return long(GBfree_data); } /* // Execute a shell command, ignore output; // If you want to send it to the background and return immediately, append "&" to shell_command void exec_system_command(QString shell_command) { QProcess process; process.start("/bin/sh -c \""+shell_command+"\""); process.waitForFinished(-1); } */ // Execute a shell command, and retrieve single line output QString read_system_command(QString shell_command) { QProcess process; process.start("/bin/sh -c \""+shell_command+"\""); process.waitForFinished(-1); QString result(process.readLine()); return result; } /* // Execute a shell command, and retrieve multiple line output QString read_MultipleLines_system_command(QString shell_command) { QProcess process; process.start("/bin/sh -c \""+shell_command+"\""); process.waitForFinished(-1); QByteArray ba = process.readAllStandardOutput(); QString result = QString::fromStdString(ba.toStdString()); return result; } */ void initEnvironment(QString &thelidir, QString &userdir) { // If the THELIDIR variable is NOT set, try finding THELI in the system path if (!QProcessEnvironment::systemEnvironment().contains("THELIDIR")) { QDir thelidir1("/usr/share/theli/config/"); QDir thelidir2("/usr/share/theli/python/"); if (thelidir1.exists() && thelidir2.exists()) { thelidir = "/usr/share/theli/"; } } else { thelidir = QProcessEnvironment::systemEnvironment().value("THELIDIR",""); } QSysInfo *sysInfo = new QSysInfo; // Are we running "linux" or "darwin"? QString kernelType = sysInfo->kernelType(); // returns "linux" or "darwin" // Capitalize first letter kernelType.replace(0, 1, kernelType[0].toUpper()); // Are we 64-bit Linux? QString arch = sysInfo->currentCpuArchitecture(); if (kernelType == "Linux" && arch.contains("64")) kernelType = "Linux_64"; userdir = QDir::homePath()+"/.theli/"; // Simplify strings thelidir.replace("//","/"); userdir.replace("//","/"); delete sysInfo; sysInfo = nullptr; } QString findExecutableName(QString program) { QStringList sourceextractorlist = {"source-extractor", "sex", "sextractor", "SExtractor"}; QStringList scamplist = {"scamp", "Scamp"}; QStringList swarplist = {"swarp", "Swarp", "SWarp"}; QStringList anetlist1 = {"solve-field"}; QStringList anetlist2 = {"build-astrometry-index"}; QStringList pythonlist = {"python3", "python"}; QString commandname = ""; if (program == "source-extractor") { for (auto &it : sourceextractorlist) { commandname = QStandardPaths::findExecutable(it); if (!commandname.isEmpty()) break; } } else if (program == "scamp") { for (auto &it : scamplist) { commandname = QStandardPaths::findExecutable(it); if (!commandname.isEmpty()) break; } } else if (program == "swarp") { for (auto &it : swarplist) { commandname = QStandardPaths::findExecutable(it); if (!commandname.isEmpty()) break; } } else if (program == "solve-field") { for (auto &it : anetlist1) { commandname = QStandardPaths::findExecutable(it); if (commandname.isEmpty()) { QStringList paths; paths << "/usr/local/Astrometry/bin/"; commandname = QStandardPaths::findExecutable(it, paths); } if (!commandname.isEmpty()) break; } } else if (program == "build-astrometry-index") { for (auto &it : anetlist2) { commandname = QStandardPaths::findExecutable(it); if (commandname.isEmpty()) { QStringList paths; paths << "/usr/local/Astrometry/bin/"; commandname = QStandardPaths::findExecutable(it, paths); } if (!commandname.isEmpty()) break; } } else if (program == "python") { for (auto &it : pythonlist) { commandname = QStandardPaths::findExecutable(it); if (!commandname.isEmpty()) break; } } return commandname; } void killProcessChildren(qint64 parentProcessId) { QProcess get_children; QStringList get_children_cmd; get_children_cmd << "--ppid" << QString::number(parentProcessId) << "-o" << "pid" << "--no-heading"; get_children.start("ps", get_children_cmd); get_children.waitForFinished(); QString childIds(get_children.readAllStandardOutput()); childIds.replace('\n', ' '); if (childIds.isEmpty()) return; QProcess::execute("kill -9 " + childIds); } // Returns the memory in kB long get_memory() { QSysInfo *sysInfo = new QSysInfo; QString kernelType = sysInfo->kernelType(); QString memory; // TODO: use sysctl interface instead if (kernelType == "linux") { QProcess p; p.start("awk", QStringList() << "/MemTotal/ { print $2 }" << "/proc/meminfo"); p.waitForFinished(-1); memory = p.readAllStandardOutput(); memory = memory.simplified(); p.close(); } if (kernelType == "darwin") { QProcess p; p.start("sysctl", QStringList() << "hw.memsize"); // alternative: read output from /usr/bin/vm_stat // or 'hostinfo | grep memory | awk '{print $4}' // returns RAM in GB p.waitForFinished(-1); QString system_info = p.readAllStandardOutput(); QStringList list = system_info.split(' '); QString memory = list[1]; p.close(); delete sysInfo; sysInfo = nullptr; return memory.toFloat()/1024; // CHECK normalization! } delete sysInfo; sysInfo = nullptr; return memory.toLong(); } /* bool listContains(QStringList stringList, QString string) { bool test = false; for (auto &it : stringList) { if (it.contains(string)) test = true; } return test; } */ QString removeLastWords(QString string, int n, const QChar sep) { int i = 0; while (ilist.length()) return ""; else return list.at(n-1); } QString getLastWord(QString string, const QChar sep) { QStringList list = string.split(sep); return list.last(); } QString get2ndLastWord(QString string, const QChar sep) { QStringList list = string.split(sep); long index = list.count(); // if using 'int', the compiler throws a 'signed overflow' warning if (index < 2) return ""; else { return list.at(index-2); } } void removeLastCharIf(QString &string, const QChar character) { int n = string.length(); if (string.at(n-1) == character) string.truncate(n-1); } bool hasMatchingPartnerFiles(QString dirname1, QString suffix1, QString dirname2, QString suffix2, QString infomessage) { // This function checks whether e.g. all science exposures have a weight, or astrometric header QDir dir1(dirname1); QDir dir2(dirname2); QStringList notMatched; QStringList filter1("*"+suffix1); QStringList filter2("*"+suffix2); dir1.setNameFilters(filter1); dir2.setNameFilters(filter2); dir1.setSorting(QDir::Name); dir2.setSorting(QDir::Name); QStringList list1 = dir1.entryList(); QStringList list2 = dir2.entryList(); list1.replaceInStrings(suffix1,""); list2.replaceInStrings(suffix2,""); // If entries are equal, or list1 is fully contained in list2, then we can leave // Equal? if (list1.operator ==(list2)) { return true; } else { // Fully contained? for (auto & it : list1) { // If not contained in list2, add it to the list of missing items if (!list2.contains(it)) notMatched << it; } } if (notMatched.length() == 0) return true; else { QString missingItems; int i = 0; for (auto &it: notMatched) { if (i>19) break; missingItems.append(it); missingItems.append(suffix1); missingItems.append("\n"); ++i; } QMessageBox msgBox; msgBox.setText(infomessage); long nbad = notMatched.length(); if (nbad <= 20) { msgBox.setInformativeText("The following "+QString::number(nbad)+" files do not have a match:\n"+missingItems); } else { msgBox.setInformativeText("The following is a list of the first 20 (out of "+QString::number(nbad)+") files that did not have a match:\n"+missingItems); } msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); return false; } } void get_array_subsample(const QVector &data, QVector &datasub, int stepSize) { // Select the small array for (long i=0; i dim) listCopy.erase(listCopy.begin()+dim, listCopy.end()); QString summary = listCopy.join(" ").replace(" ", "\n"); if (numbad > dim) { summary.append("\n[...]\n\n"); summary.append("Total number of affected images: "+QString::number(numbad)+"\n"); } return summary; } // Masked mad double madMask(const QVector &vector_in, const QVector &mask, QString ignoreZeroes) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; QVector vector; vector.reserve(maxDim); long i = 0; if (!mask.isEmpty()) { for (auto &it: vector_in) { if (!mask[i] && ignoreZeroes == "") vector.append(it); if (!mask[i] && ignoreZeroes != "" && it != 0.) vector.append(it); ++i; } } else { for (auto &it: vector_in) { if (ignoreZeroes == "") vector.append(it); if (ignoreZeroes != "" && it != 0.) vector.append(it); ++i; } } QVector diff; diff.reserve(maxDim); if (vector.size() == 0) return 0.; else { double med = straightMedian_T(vector); for (int i=0; i &vector_in, const QVector &mask) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; QVector vector; vector.reserve(maxDim); if (!mask.isEmpty()) { long i = 0; for (auto &it: vector_in) { if (!mask[i]) vector.append(it); ++i; } } else { for (auto &it: vector_in) { vector.append(it); } } if (vector.size() == 0) return 0.; else { // https://en.wikipedia.org/wiki/Median_absolute_deviation#Relation_to_standard_deviation return madMask(vector)*1.4826 / std::sqrt(vector.size()); } } bool moveFiles(QString filter, QString sourceDirName, QString targetDirName) { QDir dir1(sourceDirName); QDir dir2(targetDirName); if (!dir1.exists() || !dir2.exists()) { qDebug() << __func__ << "ERROR: One or both of these directories does not exist:" << dir1 << dir2; return false; } QStringList filterList(filter); QStringList fileList = dir1.entryList(filterList); for (auto &it: fileList) { // In Qt5, an existing file must be removed first before a new one with the same name can be moved there QFile testFile(dir2.absolutePath()+"/"+it); if (testFile.exists()) { if (!testFile.remove()) return false; } QFile file(dir1.absolutePath()+"/"+it); if (!file.rename(dir1.absolutePath()+"/"+it, dir2.absolutePath()+"/"+it)) return false; } return true; } bool deleteFile(QString fileName, QString path) { QFile testFile(path+"/"+fileName); if (testFile.exists()) { if (!testFile.remove()) return false; } return true; } bool moveFile(QString filename, QString sourceDirPath, QString targetDirPath, bool skipNonExistingFile) { QDir targetDir(targetDirPath); if (!targetDir.exists()) { if (!targetDir.mkpath(targetDirPath)) { qDebug() << __func__ << "ERROR: Could not create directory " << targetDirPath; // mkpath() returns true if the directory already exists, // hence if we are here then something really went wrong return false; } } // In Qt5, an existing file must be removed first before a new one with the same name can be moved there QFile testFile(targetDirPath+"/"+filename); if (testFile.exists()) { if (!testFile.remove()) return false; } QFile file(sourceDirPath + "/" + filename); if (skipNonExistingFile && !file.exists()) return true; if (!file.rename(targetDirPath + "/" + filename)) { QString operation = "mv " + sourceDirPath+"/"+filename + " " + targetDirPath+"/"+filename; qDebug() << __func__ << "ERROR: Could not execute this operation:\n" << operation; return false; } return true; } void mkAbsDir(QString absDirName) { QDir targetDir(absDirName); if (!targetDir.exists()) targetDir.mkpath(absDirName); } QString hmsToDecimal(QString hms) { hms = hms.simplified(); hms = hms.replace(' ',':'); QStringList list = hms.split(':'); double hh = list.at(0).toDouble(); double mm = list.at(1).toDouble(); double ss = list.at(2).toDouble(); mm /= 60.; ss /= 3600.; double decimal = 15.*(hh+mm+ss); return QString::number(decimal,'f',12); } QString dmsToDecimal(QString dms) { dms = dms.simplified(); dms = dms.replace(' ',':'); QStringList list = dms.split(':'); double dd = list.at(0).toDouble(); double mm = list.at(1).toDouble(); double ss = list.at(2).toDouble(); // Cannot use sgn() function here, as it returns 0 when argument is (-0) int sign = 1; if (list.at(0).contains("-")) sign = -1; mm /= 60.; ss /= 3600.; double decimal = (fabs(dd)+mm+ss)*sign; return QString::number(decimal,'f',12); } QString decimalSecondsToHms(float value) { double h; double m; double s; value /= 3600.; value = 60.0 * modf(value, &h); s = 60.0 * modf(value, &m); QString hh; QString mm; QString ss; if (h<10) hh = '0'+QString::number(int(h)); else hh = QString::number(int(h)); if (m<10) mm = '0'+QString::number(int(m)); else mm = QString::number(int(m)); ss = QString::number(s, 'f', 3); return hh+":"+mm+":"+ss; } QString decimalToHms(float value) { double h; double m; double s; value /= 15.; value = 60.0 * modf(value, &h); s = 60.0 * modf(value, &m); QString hh; QString mm; QString ss; if (h<10) hh = '0'+QString::number(int(h)); else hh = QString::number(int(h)); if (m<10) mm = '0'+QString::number(int(m)); else mm = QString::number(int(m)); ss = QString::number(s, 'f', 3); if (s<10) ss = '0'+ss; return hh+":"+mm+":"+ss; } QString decimalToDms(float value) { QString sign = ""; if (value < 0.) { value *= -1.; sign = "-"; } double d; double m; double s; value = 60.0 * modf(value, &d); s = 60.0 * modf(value, &m); QString dd; QString mm; QString ss; if (d<10) dd = '0'+QString::number(int(d)); else dd = QString::number(int(d)); if (m<10) mm = '0'+QString::number(int(m)); else mm = QString::number(int(m)); ss = QString::number(s, 'f', 3); if (s<10) ss = '0'+ss; return sign+dd+":"+mm+":"+ss; } double dateobsToDecimal(QString dateobs) { // dateobs format: YYYY-MM-DDTHH:MM:SS.sss if (!dateobs.contains("T") || !dateobs.contains(":") || !dateobs.contains("-")) { qDebug() << __func__ << "ERROR: DATE-OBS string " << dateobs << "does not have YYYY-MM-DDTHH:MM:SS.sss format!"; return 0.; } QStringList list = dateobs.split("T"); QString date = list[0]; QString time = list[1]; QStringList datelist = date.split("-"); QStringList timelist = time.split(":"); if (datelist.length() != 3 || timelist.length() != 3) { qDebug() << __func__ << "ERROR: DATE-OBS string " << dateobs << "does not have YYYY-MM-DDTHH:MM:SS.sss format!"; return 0.; } double year = datelist[0].toDouble(); double month = datelist[1].toDouble(); double day = datelist[2].toDouble(); double hh = timelist[0].toDouble(); double mm = timelist[1].toDouble(); double ss = timelist[2].toDouble(); return year + month/12. + day/365.25 + hh/8766. + mm/525960. + ss/3.15576e7; } QVector getSmallSample(const QVector &data, const QVector &mask) { long n = data.length(); // A small sample for quick first estimates QVector sample; long step = 1; // A prime number whose integer multiples do not get close to pow(2^n) // and therefore it samples a typical detector in a random-like fashion if (n>10000) { step = 379; sample.reserve(n/379); } else sample.reserve(n); if (!mask.isEmpty()) { for (long i=0; i modeMask(const QVector &data, QString mode, const QVector &mask, bool smooth) { QVector sky; long n = data.length(); if (n == 0) return sky << 0. << -1.; if (!mask.isEmpty() && n != mask.length()) { qDebug() << __func__ << "ERROR: Mask is not empty but has different size than data vector." << n << mask.length(); return sky << 0. << -1.; } // Work with values within -3 MAD to 3 MAD (about +/- 2 sigma). Estimated from a small sample (at least 10000 data points) QVector sample = getSmallSample(data, mask); float medianVal = straightMedian_T(sample); float madVal = madMask_T(sample); float minVal = medianVal - 3.*madVal; float maxVal = medianVal + 3.*madVal; float skySigma = 1.3*madVal; // estimate of sigma based on MAD value (normally 1.48, but we want the clipped range without astrophysical objects) // Optimal step size for 100 bins, yielding an average S/N per bin of of 10 int numBins = 100; int sampleDensity = modeMask_sampleDensity(n, numBins, 10); // Clip data, use every sampleDensity data point only QVector dataClipped = modeMask_clipData(data, mask, sampleDensity, minVal, maxVal); if (dataClipped.isEmpty()) return sky << 0. << -1.; // Too few data points for mode: if (dataClipped.length() < 1000) return sky << medianVal << skySigma; // Build histogram (smoothed by default with a kernel 0.5*madVal wide) float rescale = 1.0; // the projection factor from the original data to normalized integer range corresponding to [minVal, maxVal] QVector histogram = modeMask_buildHistogram(dataClipped, rescale, numBins, minVal, maxVal, madVal, smooth); // Find the histogram peak with various methods (data dependent) float skyValue = 0.; if (mode == "classic") modeMask_classic(histogram, skyValue); else if (mode == "gaussian") modeMask_gaussian(histogram, skyValue); else if (mode == "stable") modeMask_stable(histogram, skyValue); else { // to be implemented } // Project back onto original scale skyValue = skyValue / rescale + minVal; // skySigma = skySigma / rescale; // if skySigma was estimated from the histogram return sky << skyValue << skySigma; } // MODE: Determine optimal sample density int modeMask_sampleDensity(long numDataPoints, int numBins, float SNdesired) { // We use only every n-th data point (n = sampleDensity) to speed up calculations. // The sample density is chosen such that it yields, on average, the desired S/N per bin (assuming Poisson distribution) long sampleDensity = numDataPoints / (numBins * SNdesired * SNdesired); if (sampleDensity == 0) sampleDensity = 1; // max density for few data points if (sampleDensity > 10) sampleDensity = 10; // min density; we don't mind good S/N in the histogram return sampleDensity; } // MODE: Clip data, use every sampleDensity data point only QVector modeMask_clipData(const QVector &data, const QVector &mask, int sampleDensity, float minVal, float maxVal) { QVector dataThresholded; long n = data.length(); dataThresholded.reserve(n/sampleDensity); if (!mask.isEmpty()) { for (long i=0; i minVal && it < maxVal && !mask[i]) { dataThresholded.append(it); } } } else { for (long i=0; i minVal && it < maxVal) { dataThresholded.append(it); } } } return dataThresholded; } // MODE: Build histogram QVector modeMask_buildHistogram(QVector &data, float &rescale, const int numBins, const float minVal, const float maxVal, const float madVal, const bool smooth) { // Project data onto integer values, spread numBins over normalized [minVal, maxVal] range rescale = float(numBins) / (maxVal - minVal); for (auto &it: data) { it = int (rescale * (it-minVal)); // Stay within bounds // It can rarely happen that it == numBins for it=max; floating point round-off issue, causing histogram[it] to fail; if (it < 0) it = 0; if (it >= numBins) it = numBins-1; } // Now accumulate the histogram (bin 0 corresponds to minVal, bin numBin to maxVal) QVector histogram(numBins); for (auto &it : data) { histogram[it]++; } // Optionally, smooth the histogram (true by default) // The smoothing is done with a Gaussian that is 'width' bins wide, where width is half the MAD value, but at least 3 bins wide int width = 0.5 * madVal * rescale; if (width < 3) width = 3; // if (histogram[20] == 0 && histogram[21] == 0 && histogram[22] == 0 && histogram[23] == 0) { // qDebug() << data; // qDebug() << histogram; // } if (smooth) smooth_array_T(histogram, width); // if (histogram[20] == 0 && histogram[21] == 0 && histogram[22] == 0 && histogram[23] == 0) { // qDebug() << " "; // qDebug() << data; // qDebug() << histogram; // } return histogram; } // Classical way to find peak in the histogram: look for the highest bin void modeMask_classic(const QVector histogram, float &skyValue) { float hist_max = 0.; int hist_x = 0; long i = 0; for (auto &it : histogram) { if (it > hist_max) { hist_x = i; hist_max = it; } ++i; } skyValue = hist_x; } // Find the peak in the histogram using a Gaussian fit // WARNING: Does not work if image contains large number of padded or constant pixels, // creating (multiple) huge histogram spikes, failing the GSL fit. void modeMask_gaussian(QVector histogram, float &skyValue) { int numBins = histogram.length(); // Starting values double amplitude = maxVec_T(histogram); double meanVal = numBins/2; double sigmaVal = rmsMask_T(histogram); // Arguments 2, 3 and 4 are starting values for amplitude, mean and sigma QVector fitResult = fitGauss1D(histogram, amplitude, meanVal, sigmaVal); skyValue = fitResult[1]; // skySigma = fitResult[2]; } // Robust way: determine 50% cut-on and cut-off values, and return the mean of data points in between // This will work if the data is not unimodular (e.g. if gradients are present in an image) void modeMask_stable(const QVector histogram, float &skyValue) { int numBins = histogram.length(); double amplitude = maxVec_T(histogram); // Locate the classic peak modeMask_classic(histogram, skyValue); // Extreme limits int cutOn = 0; int cutOff = numBins - 1; // Update limits // Take the peak and go left until the 50% value is reached for (int i=skyValue; i>=0; --i) { if (histogram[i] <= 0.5*amplitude) { cutOn = i; break; } } // Take the peak and go right until the 50% value is reached for (int i=skyValue; i= numBins) cutOff = numBins-1; } /* if (cutOn == 0 || cutOff == numBins) { qDebug() << "QDEBUG: functions:modeMask_stable(): Could not locate 50% cut-on and cut-off values for image statistics. Using full range."; } */ if (cutOn == cutOff) { qDebug() << __func__ << "Error determining 50% cut-on and cut-off values for image statistics. Using middle quantile."; cutOn = 0.25*numBins; cutOff = 0.75*numBins; } // qDebug() << cutOn << cutOff; // Calculate mean value within cutOn and cutOff skyValue = 0.; float weights = 0.; for (int i=cutOn; i<=cutOff; ++i) { skyValue += i*histogram[i]; weights += histogram[i]; } skyValue /= weights; } //*************************************************************************** // DUPLICATED from templates because I need them in connection with functors. // These functions may call template functions themselves, though //*************************************************************************** // Masked median float medianMask(const QVector &vector_in, const QVector &mask, long maxLength) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; // fast-track if (mask.isEmpty()) { return straightMedian_T(vector_in, maxLength); } // Usually, we take all elements in a vector. // However, in some cases it may be that elements are masked and the vector is not entirely filled. // In this case, an optional maxLength argument is provided if (maxLength > 0 && maxLength < maxDim) maxDim = maxLength; QVector vector; vector.reserve(maxDim); for (int i=0; i &data, const int nlow, const int nhigh) { long maxDim = data.length(); if (maxDim == 0) return 0.; if (nlow+nhigh >= maxDim) return 0; std::sort(data.begin(), data.end()); float med; if (nhigh > 0) data.remove(maxDim-nhigh, nhigh); if (nlow > 0) data.remove(0, nlow); // Calculate average of central two elements if number is even long dsize = data.size(); med = (dsize % 2) ? data[dsize / 2.] : ((float)data[dsize / 2. - 1] + data[dsize / 2.]) * .5; return med; } // Changes data! float straightMedian_MinMax(QList &data, const int nlow, const int nhigh) { long maxDim = data.length(); if (maxDim == 0) return 0.; if (nlow+nhigh >= maxDim) return 0; std::sort(data.begin(), data.end()); float med; if (nhigh > 0) { for (int i=0; i 0) { for (int i=0; i &vector_in, const QVector &mask, long maxLength) { long maxDim = vector_in.length(); // Usually, we take all elements in a vector. // However, in some cases it may be that elements get masked and the vector is not entirely filled. // In this case, an optional maxLength argument is provided if (maxLength > 0 && maxLength < maxDim) maxDim = maxLength; // fast-track if (vector_in.size() == 0) return 0.; if (mask.isEmpty()) { float meanVal = 0.; for (long i=0; i vector; vector.reserve(maxDim); for (int i=0; i data, float kappa, int iterMax) { long dim = data.length(); if (dim == 0) return 0.; QVector mask(dim,false); // Calculate first estimate of mean and rms; all masks are false float meanVal = meanMask_T(data, mask); float rmsVal = rmsMask_T(data, mask); if (kappa == 0. || iterMax == 0) return meanVal; int iter = 0; while (iter < iterMax) { // Calculate mean and rms meanVal = meanMask_T(data, mask); rmsVal = rmsMask_T(data, mask); // Recalculate mask bool masksChanged = false; long i = 0; for (auto & it : data) { bool currentMask = mask[i]; // reject an outlier if (!currentMask && fabs(it - meanVal) >= kappa*rmsVal) { mask[i] = true; masksChanged = true; } // include a previous outlier again if (currentMask && fabs(it - meanVal) < kappa*rmsVal) { mask[i] = false; masksChanged = true; } ++i; } // Leave if masks haven't changed if (masksChanged == false) break; ++iter; } return meanVal; } bool readData3D(QString path, QVector &x, QVector &y, QVector &z) { QFile file(path); if (!file.exists()) { return false; } if ( !file.open(QIODevice::ReadOnly)) { return false; } QTextStream in(&(file)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty() || line.contains("#")) continue; QStringList values = line.split(" "); if (values.length() != 3) continue; x.append(values[0].toDouble()); y.append(values[1].toDouble()); z.append(values[2].toDouble()); } file.close(); return true; } // Angles are always passed / returned in degrees double getPosAnglefromCD(double cd11, double cd12, double cd21, double cd22, bool lock) { // In case CD matrix is undefined (e.g. binned images) if (cd11 == 0. && cd12 == 0. && cd21 == 0. && cd22 == 0.) return 0.; // the pixel scale double pscale1 = sqrt(cd11 * cd11 + cd21 * cd21); double pscale2 = sqrt(cd12 * cd12 + cd22 * cd22); // take out the pixel scale cd11 /= pscale1; cd12 /= pscale2; cd21 /= pscale1; cd22 /= pscale2; // sqrt(CD elements) is very close to one, but not perfectly // as coordinate system is not necessarily orthogonal (shear + contraction) double nfac1 = sqrt(cd11 * cd11 + cd21 * cd21); double nfac2 = sqrt(cd12 * cd12 + cd22 * cd22); // make sure sqrt(CD elements) = 1, // so that we can do the inverse trig functions cd11 /= nfac1; cd21 /= nfac1; cd12 /= nfac2; cd22 /= nfac2; // due to flipping the rotation angle is ambiguous. // possibly, the following could be simplified with det(CD), // but at the moment i don't see how to identify the additional 2*PI easily double pa = 0.; double PI = 3.1415926535; // normal if (cd11 < 0 && cd12 <= 0 && cd21 <= 0 && cd22 > 0) pa = acos(-cd11); // 0 <= phi < 90 else if (cd11 >= 0 && cd12 < 0 && cd21 < 0 && cd22 <= 0) pa = acos(-cd11); // 90 <= phi < 180 else if (cd11 > 0 && cd12 >= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(-cd11); // 180 <= phi < 270 else if (cd11 <= 0 && cd12 > 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(-cd11); // 270 <= phi < 360 // flipped else if (cd11 >= 0 && cd12 >= 0 && cd21 <= 0 && cd22 >= 0) pa = acos(cd11); // 0 <= phi < 90 else if (cd11 < 0 && cd12 > 0 && cd21 < 0 && cd22 < 0) pa = acos(cd11); // 90 <= phi < 180 else if (cd11 < 0 && cd12 <= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(cd11); // 180 <= phi < 270 else if (cd11 >= 0 && cd12 < 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(cd11); // 270 <= phi < 360 else { if (lock) { // we are very likely close to 0, 90, 180 or 270 degrees, and the CD matrix is slightly non-orthogonal. // In this case, lock onto 0, 90, 180 or 270 degrees. Otherwise, exit with an error. double cd11cd12 = fabs(cd11/cd12); double cd22cd21 = fabs(cd22/cd21); if (cd11cd12 > 20. && cd22cd21 > 20.) { if (cd11 > 0. && cd22 > 0.) pa = 0.*PI/2.; if (cd11 < 0. && cd22 > 0.) pa = 0.*PI/2.; if (cd11 > 0. && cd22 < 0.) pa = 2.*PI/2.; if (cd11 < 0. && cd22 < 0.) pa = 2.*PI/2.; } else if (cd11cd12 < 0.05 && cd22cd21 < 0.05) { if (cd12 > 0. && cd21 < 0.) pa = 1.*PI/2.; if (cd12 < 0. && cd21 < 0.) pa = 1.*PI/2.; if (cd12 > 0. && cd21 > 0.) pa = 3.*PI/2.; if (cd12 < 0. && cd21 > 0.) pa = 3.*PI/2.; } else { // should print to command line only if in debug mode // qDebug() << __func__ << "ERROR: Could not determine position angle from CD matrix!"; } } } double rad = PI / 180.; return (pa / rad); // return in degrees } // Angles are always passed / returned in degrees void rotateCDmatrix(double &cd11, double &cd12, double &cd21, double &cd22, double PAnew) { double rad = 3.1415926535 / 180.; // the current position angle of the CD matrix double PAold = getPosAnglefromCD(cd11, cd12, cd21, cd22); // is the matrix flipped (det(CD) > 0 if flipped) double det = cd11*cd22 - cd12*cd21; double f11 = 0.; if (det < 0) f11 = 1.; else f11 = -1.; double f12 = 0.; double f21 = 0.; double f22 = 1.; // unflip the matrix matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22); // rotate the matrix to the new position angle double dPA = rad * (PAnew - PAold); matrixMult_T(cos(dPA), -sin(dPA), sin(dPA), cos(dPA), cd11, cd12, cd21, cd22); // flip the matrix matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22); } // Angles are always passed / returned in degrees void get_rotimsize(long naxis1, long naxis2, double PAold, double PAnew, long &Nnew, long &Mnew) { double n = naxis1; double m = naxis2; double r = 0.5 * sqrt(n*n+m*m) + 1.; double rad = 3.1415926535 / 180.; double phi = atan(m/n) / rad; QVector xarr(4); QVector yarr(4); xarr[0] = r * cos(rad * (PAnew - PAold + phi)); xarr[1] = r * cos(rad * (PAnew - PAold - phi + 180.)); xarr[2] = r * cos(rad * (PAnew - PAold + phi + 180.)); xarr[3] = r * cos(rad * (PAnew - PAold - phi + 360.)); yarr[0] = r * sin(rad * (PAnew - PAold + phi)); yarr[1] = r * sin(rad * (PAnew - PAold - phi + 180.)); yarr[2] = r * sin(rad * (PAnew - PAold + phi + 180.)); yarr[3] = r * sin(rad * (PAnew - PAold - phi + 360.)); long xmin = (long) minVec_T(xarr); long xmax = (long) maxVec_T(xarr); long ymin = (long) minVec_T(yarr); long ymax = (long) maxVec_T(yarr); Nnew = xmax - xmin; Mnew = ymax - ymin; } int gauss_f(const gsl_vector* x, void* params, gsl_vector* f) { size_t nx = ((struct dataGSL *) params)->nx; size_t ny = ((struct dataGSL *) params)->ny; double *z = ((struct dataGSL *) params)->z; double *sigma = ((struct dataGSL *) params)->sigma; // extract parameters from x double b = gsl_vector_get(x,0); double x0 = gsl_vector_get(x,1); double y0 = gsl_vector_get(x,2); double s = gsl_vector_get(x,3); for (size_t yi=0; yinx; size_t ny = ((struct dataGSL *)params)->ny; double *sigma = ((struct dataGSL *)params)->sigma; double x0 = gsl_vector_get(x,1); double y0 = gsl_vector_get(x,2); double s = gsl_vector_get(x,3); for (size_t yi=0; yi &data, const QString dir, const int naxis1, const int naxis2) { QVector copy; copy.resize(naxis1*naxis2); long k = 0; if (dir == "x") { for (int j=0; j §ions, const QString dir, const int naxis1, const int naxis2) { QVector copy = sections; if (dir == "x") { copy[1] = naxis1-1-sections[0]; copy[0] = naxis1-1-sections[1]; } else if (dir == "y") { copy[3] = naxis2-1-sections[2]; copy[2] = naxis2-1-sections[3]; } else if (dir == "xy") { copy[1] = naxis1-1-sections[0]; copy[0] = naxis1-1-sections[1]; copy[3] = naxis2-1-sections[2]; copy[2] = naxis2-1-sections[3]; } sections = copy; } // In case the user has deactivated some chips, we need to find one that is valid int getValidChip(const instrumentDataType *instData) { /* int testChip = -1; for (int chip=0; chipnumChips; ++chip) { if (!instData->badChips.contains(chip)) { testChip = chip; break; } } if (testChip == -1) { qDebug() << __func__ << "error: no data left after filtering"; } return testChip; */ if (instData->goodChips.isEmpty()) return 0; // error message is printed by MainWindow::updateExcludedDetectors(QString badDetectors) else return instData->goodChips[0]; // return the first valid chip } THELI-3.1.3/src/functions.h000066400000000000000000000402231417631501300153350ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef FUNCTIONS_H #define FUNCTIONS_H #include #include "fitsio2.h" #include #include "instrumentdata.h" #include #include #include #include #include #include #include #include #include #include #include #include #include struct dataGSL { size_t nx, ny; double* z; // pointer to values of 2D function double* sigma; // dito for sigmas }; QString boolToString(bool test); double getPosAnglefromCD(double cd11, double cd12, double cd21, double cd22, bool lock = true); void rotateCDmatrix(double &cd11, double &cd12, double &cd21, double &cd22, double PAnew); void get_rotimsize(long naxis1, long naxis2, double PAold, double PAnew, long &Nnew, long &Mnew); QStringList datadir2StringList(QLineEdit *lineEdit); QString get_fileparameter(QFile *, QString, QString warn = ""); // QString get_fileHeaderParameter(QFile *file, QString parametername); // QString get_fileparameter_vector(QFile *, QString, QString warn = ""); // QVector get_fileparameter_FullVector(QFile *file, QString parametername); QString findExecutableName(QString program); QString sanityCheckWCS(const wcsprm *wcs); void killProcessChildren(qint64 parentProcessId); long get_memory(); void showLogfile(QString logname, QString line = ""); void fill_combobox(QComboBox *, QString); void paintPathLineEdit(QLineEdit *, QString, QString check = "dir"); bool listContains(QStringList stringList, QString string); // void exec_system_command(QString); QVector getSmallSample(const QVector &data, const QVector &mask = QVector()); void initEnvironment(QString &thelidir, QString &userdir); // void listSwapLastPairs(QStringList &stringlist, int n); long numFilesDir(QString path, QString filter); bool hasMatchingPartnerFiles(QString dirname1, QString suffix1, QString dirname2, QString suffix2, QString infomessage); QString removeLastWords(QString string, int n=1, const QChar sep=' '); QString getNthWord(QString string, int n, const QChar sep=' '); QString read_system_command(QString); // QString read_MultipleLines_system_command(QString shell_command); // QString translateServer(QString downloadServer); QString truncateImageList(QStringList list, int dim); void message(QPlainTextEdit *pte, QString text, QString type=""); void selectFirstActiveItem(QComboBox *cb); void get_array_subsample(const QVector &data, QVector &datasub, int stepSize); double medianerrMask(const QVector &vector_in, const QVector &mask = QVector()); double madMask(const QVector &vector_in, const QVector &mask = QVector(), QString ignoreZeroes = ""); float meanIterative(const QVector data, float kappa, int iterMax); QString hmsToDecimal(QString hms); QString dmsToDecimal(QString dms); QString decimalSecondsToHms(float value); QString decimalToHms(float value); QString decimalToDms(float value); double dateobsToDecimal(QString dateobs); QString getLastWord(QString string, const QChar sep); QString get2ndLastWord(QString string, const QChar sep); void removeLastCharIf(QString &string, const QChar character); bool moveFiles(QString filter, QString sourceDirName, QString targetDirName); bool moveFile(QString filename, QString sourceDirPath, QString targetDirPath, bool skipNonExistingFile = false); bool deleteFile(QString fileName, QString path); QVector modeMask(const QVector &data, QString mode, const QVector &mask = QVector(), bool smooth = true); int modeMask_sampleDensity(long numDataPoints, int numBins, float SNdesired); QVector modeMask_clipData(const QVector &data, const QVector &mask, int sampleDensity = 1, float minVal = 0., float maxVal = 0.); QVector modeMask_buildHistogram(QVector &data, float &rescale, const int numBins, const float minVal, const float maxVal, const float madVal, const bool smooth = true); void modeMask_classic(const QVector histogram, float &skyValue); void modeMask_gaussian(QVector histogram, float &skyValue); void modeMask_stable(const QVector histogram, float &skyValue); float meanMask(const QVector &data, const QVector &mask = QVector(), long maxLength = 0); float medianMask(const QVector &data, const QVector &mask = QVector(), long maxLength = 0); float straightMedian_MinMax(QVector &data, const int nlow, const int nhigh); float straightMedian_MinMax(QList &data, const int nlow, const int nhigh); bool readData3D(QString path, QVector &x, QVector &y, QVector &z); long remainingDataDriveSpace(QString maindir); int gauss_f(const gsl_vector *x, void *params, gsl_vector *f); int gauss_df(const gsl_vector *x, void *params, gsl_matrix *J); int gauss_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J); void mkAbsDir(QString absDirName); void flipData(QVector &data, const QString dir, const int naxis1, const int naxis2); void flipSections(QVector §ions, const QString dir, const int naxis1, const int naxis2); int getValidChip(const instrumentDataType *instData); // template functions end in "_T" // This is to distinguish them from the same functions // which are needed explicitly because they are select through functors // Test if a RA/DEC coordinate is contained within an image //*************************************************************** // Template for matrix multiplication. // Stores the result in the elements of the second matrix //*************************************************************** template void matrixMult_T(const T1 a11, const T1 a12, const T1 a21, const T1 a22, T2 &b11, T2 &b12, T2 &b21, T2 &b22) { // qDebug() << "rot" << a11 << a12 << a21 << a22; T2 c11 = a11 * b11 + a12 * b21; T2 c12 = a11 * b12 + a12 * b22; T2 c21 = a21 * b11 + a22 * b21; T2 c22 = a21 * b12 + a22 * b22; // qDebug() << a21 << b12 << a22 << b22 << c22; b11 = c11; b12 = c12; b21 = c21; b22 = c22; } template QVector removeVectorItems_T(QVector data, QVector badIndexes) { int i=0; QVector removeFlag = QVector(data.length(), false); for (i=0; i filtered = QVector(); for (i=0; i T minVec_T(const QVector &qv) { if (qv.length() == 0) { // qDebug() << "QDEBUG: minVec(): vector has zero length."; return 0; } T extreme = qv.at(0); for ( const auto &i : qv) { if (i < extreme) extreme = i; } return (extreme); } template T maxVec_T(const QVector &qv) { if (qv.length() == 0) { // qDebug() << "QDEBUG: maxVec_T(): vector has zero length."; return 0; } T extreme = qv.at(0); for ( const auto &i : qv) { if (i > extreme) extreme = i; } return (extreme); } template T meanQuantile_T(const QVector &data, const long start, const long end) { T mean = 0.; long numpixels = 0; long naned = 0; for (long i=start; i (end-start) / 2) mean = nan("0x12345"); // return NaN return (mean); } template T straightMedian_T(const QVector &vector_in, long maxLength = 0, bool center = true) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; // Usually, we take all elements in a vector. // However, in some cases it may be that elements get masked and the vector is not entirely filled. // In this case, an optional maxLength argument is provided if (maxLength > 0 && maxLength < maxDim) maxDim = maxLength; QVector vector(maxDim); for (long i=0; i T straightMedianInline(QVector &data) { long dim = data.length(); if (dim == 0) return 0.; std::sort(data.begin(), data.end()); T med; med = (dim % 2) ? data[dim/2] : ((T)data[dim/2-1] + data[dim/2]) * .5; return med; } // Masked median template T medianMask_T(const QVector vector_in, QVector mask = QVector(), QString ignoreZeroes = "") { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; // fast-track if (mask.isEmpty() && ignoreZeroes == "") { return straightMedian_T(vector_in); } // slower median with masks, and potentially pixel with value zero that are to be ignored if (mask.isEmpty()) { mask.fill(false, maxDim); } QVector vector; vector.reserve(maxDim); int i = 0; for (auto &it: vector_in) { if (!mask.at(i) && ignoreZeroes == "") vector.append(it); if (!mask.at(i) && ignoreZeroes != "" && it != 0.) vector.append(it); ++i; } if (vector.size() == 0) return 0.; else { return straightMedian_T(vector); } } // Masked mean template T meanMask_T(const QVector &vector_in, QVector mask = QVector()) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; // fast-track if (mask.isEmpty()) { return std::accumulate(vector_in.begin(), vector_in.end(), .0) / vector_in.size(); } else { QVector vector; vector.reserve(maxDim); int i = 0; for (auto &it: vector_in) { if (!mask.at(i)) vector.append(it); ++i; } if (vector.size() == 0) return 0.; else return std::accumulate(vector.begin(), vector.end(), .0) / vector.size(); } } template T rmsMask_T(const QVector &vector_in, QVector mask = QVector()) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; if (mask.isEmpty()) { mask.fill(false, maxDim); } QVector vector; vector.reserve(maxDim); int i = 0; for (auto &it: vector_in) { if (!mask[i]) vector.append(it); ++i; } T rmsval = 0.; T meanval = meanMask_T(vector_in, mask); if (vector.size() <= 1) return 0.; else { for (auto &it: vector) { rmsval += (meanval - it) * (meanval - it); } return std::sqrt(rmsval / (vector.size()-1) ); } } // Masked mad template T madMask_T(const QVector vector_in, const QVector mask = QVector(), QString ignoreZeroes = "") { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; QVector vector; vector.reserve(maxDim); if (!mask.isEmpty()) { long i = 0; for (auto &it: vector_in) { if (!mask.at(i) && ignoreZeroes == "") vector.append(it); if (!mask.at(i) && ignoreZeroes != "" && it != 0.) vector.append(it); ++i; } } else { for (auto &it: vector_in) { if (ignoreZeroes == "") vector.append(it); if (ignoreZeroes != "" && it != 0.) vector.append(it); } } QVector diff; diff.reserve(maxDim); if (vector.size() == 0) return 0.; else { T med = straightMedian_T(vector); for (long i=0; i int sgn(T x) { if (x >= 0) return 1; else return -1; } // Check a QVector for duplicates template bool hasDuplicates_T(QVector data) { std::sort(data.begin(), data.end()); T old = data[0]; long j = 0; long nDuplicates = 0; for (auto &it : data) { if (j>0 && it == old) ++nDuplicates; old = it; ++j; } if (nDuplicates > 0) return true; else return false; } // Count the number of duplicates in a Qvector template int numberOfDuplicates_T(QVector data) { std::sort(data.begin(), data.end()); T old = data[0]; long j = 0; long nDuplicates = 0; for (auto &it : data) { if (j>0 && it == old) ++nDuplicates; old = it; ++j; } return nDuplicates; } // The index of the entry with the highest value template T maxIndex(const QVector &data) { long index = 0; T maxval = data[0]; long i=0; for (auto &pixel : data) { if (pixel > maxval) { maxval = pixel; index = i; } ++i; } return index; } // Convolve a 1D array with a Gaussian of width sigma (units of array elements) // The footprint of the Gaussian is +/- 1 sigma template void smooth_array_T(QVector &data, T2 sigma) { float ss2 = 2.*sigma*sigma; long dim = data.length(); float footprint = 1.0; QVector tmp(dim); for (long i=0; i= dim ? dim : i+footprint*sigma; for (long j=jmin; j T kth_smallest(QVector &data, int k) // WARNING: modifies input vector { T x; long l = 0; long n = data.length(); long m = n - 1; while (l < m) { x = data[k]; long i = l; long j = m; do { while (data.at(i) < x) ++i; while (x T fastMedian(QVector &data) { long n = data.length(); kth_smallest(data,(((n)&1)?((n)/2):(((n)/2)-1))); } #endif // FUNCTIONS_H THELI-3.1.3/src/icons/000077500000000000000000000000001417631501300142665ustar00rootroot00000000000000THELI-3.1.3/src/icons/Actions-process-stop-icon.png000066400000000000000000000066521417631501300217720ustar00rootroot00000000000000PNG  IHDR00W qIDATxY tU?f Ĉ`%bh+d%:J*%! VAAHH> I|{}'_Dcݼスs.4_\hZdkbfMJlDX`֮:xNx੬ u874:vg'iddI>JKKC&/, OL@h䫩$&!|U5<(NW뫫l>Z{ ؁)}a!Y^xȵ0n257CjE^QW\re^>iBY( 0oNIӧa4&m"b?_ t(B"@L@lTfq˽''¬uEwOM;#-$|9cLB7O>Cnu'#4QBwIs s@&˾!о: )<&?@O5*h[M!_o~̞CV̩gP}c a"U}#{n~V~4I&'x|6l 3F& ׅQd<%%?X(^"8QaK[L`,0Z`UbFÁ?-[ECzr+:dJ Wq1qBT|<7O%+яZ j:<v` 0>ØۡEDVF/*Кe5p\cd6{..^ƃ$'㳏ZGۀLb9 * y" H..~#L\0xsT.(=7D݆# FmܽDlG.~%_48)')!|%M6{5Oloy$'0er1n}ow}I-ohsObi_CJ΁qp,ӭ;eaS/%0!i.e.nh?b22jQ  )k0M,f>l&J,s< /kDl:μSxס\-dbⰙi}&AxM^q y& ek9r*]0_9m,b=L "5k&0ye8#t/ga°iO7Eh5*tH$vSė=/Nzi])"*Z- ρu*.l乍l#nX@U[+PgU87x-#cSAV/K(ٝQ)4dk1S+\={"㙹dq8dm@Kh" (VS]:VWT H͠Bn&P?G`(_szZ䢐gBAƙ(Cƒe0GF:>a{(ml9 5@aF'SA,"laH|,~\E%B{>WwT4i~:,*DN@y@`ga{a etƘԪfID z|nt;,U|H_A!w L+w%p`gvoU N!ӆl/.J4lvS'XN>05k ҩ!%}8%toG`72g{#| ZLLXy--rfJ8`uϞ%2u-'v!Y:|dޒIf}@(2F\ebلFBHt}˗aWԏ8kL`oкAg0Z#»B(%vxw_n`̧$nsAڥp82#P07r4b$.ze9GɊؗ3idk"mnwfl~= _C V-}<>[8c=\q]>l^V ͷ^X LJ/Y"e/ K^Eŭ썎 Y@ !͑gg֯(VՏC"bfw @*c0I"AtHa4[:p-א[񦪢K ,hNd.w9:w0}rq=1Dgְ8:9~~!\ d] J1Fl3Y_X.t7Xp-?3Y솋3=yٴ<3$ Nvau偠7ZX}\GnNR]T$?`6G!'^c~W sMga꟠dɚ.ŗEp;u| $4~x&՟lO.J֊ gXmOXCH90kl΋@''i{O=2pYjw{k'wpU bwQfoϋ<Ԛ 3fmL3l[gp>TGa٘<wb-_8d, XX& K_JВQ2> ll"IENDB`THELI-3.1.3/src/icons/Signal-yield-icon.png000066400000000000000000000033041417631501300202430ustar00rootroot00000000000000PNG  IHDR00WIDATx{LSW)U^275hb[l19 >PQL,1 Ƅ6-L1< ޶ sK[ݒ{w~9sϹ(?np  &^Fƻ{99`6:Z zWw7,{ XN5Ǭ\p!9Z[íSmn%-2c{p*6˗D]/} ~\HW­il=ztc>h\bۃbrr\gN(txsgEOu( ]D{t+ԙBNǧIN&95Շ#,*:Nwr4pH%+xqOv #֬)>-y^)tZ K\#srq0z5oTvQWM VxG(0lN"ub⤈ӓM nBH3kQաSSud= <(fEǗ.3sB[ΝdzPRE>.չEQʅo2*fUT1!mmv:Y&s7QEuY۶M@Kq1ֲ\ xΝc6  @Q- @B'8AOq cJT(}иyn.9-bG;Д! @{y9Y[ GI@Ch:̄cbh3`0l!,,73q@Ihƍ ּy3Y{ΩtMhLFcH/\v\MPd:2#Lxkj^D~7hrTE,_,ޜyxgVW\\@f ]od myZ;P]A}(H#P7l輼Qې /SaxQUUL,%HE> 5-GP7_?-Kh%dܻW6ցu Mb' dzzYMI֭[Ix *q'PGzíێ2&J1x $t ۺLEZ"K_Љ;. -FjH3CUǘ?QLeJ&P_/DĿ? c ^nwG8j-JyI!~;F:~;q?Ű3L܏go฀hP՚ݮ,C ett4/MN]rO*"=^Buu<;Z54D9W)JRP("ťLXt:/|RWT~QVAs=h !Q33 n`: #`u8=頑izfE Dq\4@tHkӿ,AN|M,.߬k%MM ކ҃nYӍ~0lZ%E\KB H'nyIuo83Q4%W/p7;qωZ •!Q\.¤¡ >' s9Q;ap,c^dPBޔsjjۍg<.xFlkko4O=[IENDB`THELI-3.1.3/src/icons/abszp.png000066400000000000000000000010721417631501300161130ustar00rootroot00000000000000PNG  IHDR TggAMA a cHRMz&u0`:pQ<-PLTEXXXў7&bKGD- pHYs+tIME\8IDAT(]m1 E%HC  +d+$ UB\eLa@]Ff$u:_+N"A) dL2`$܁[ [Ukk焬c.vIZEC(BK tua z2J@ZT%,uI m9ŌeZ^s1CS#.E2V*ҝ-㳢/z<ߴnbpPۡ%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/addInst.png000066400000000000000000000006101417631501300163570ustar00rootroot00000000000000PNG  IHDR TggAMA a cHRMz&u0`:pQ<PLTE000XXX~YVbKGDf |d pHYs+tIME\8aIDAT(c`D LJ(@FJ L8p3 cf#c'Tft-h[0N["C%6EAy|;1bpaE}|sU>>#;?v|Op=ˬOOwyG>WwկϯO{ֽmpW~zrZ dcw#y7kݱ<}ӫ~-B Wc -h!H;[D$A"mUV31v;W+؆EξE@~|*ǿݗ7W ԫSt؊'t|&E-lG"peg C%>CL/Nd!E2lm) n@H̱`$)o(IDDs)Kιd)-"%RjiEkJ͵Z[ZĵJ5Uդ̥W:z豧.=ko]iȣ:fPyYgJ+-YyUW[ڎ;my]wկQ?Nl\ݥF'b1#b!y"^,:X̮S 9Bt1J`b"FA#r7wnOsG䜅S~Qz6YS2~ XUC_;3hא>># _3:~qSߛnA?N#4\w4];8g61"}#iW` &`m-fi-XH Y#ԀAh/-i#.:__`egjӃQۈ_^~q(~7h$GfKZJj;3x,NJGµڨS2HDa䨗ҰJ"HZj_H-ňY޶Q 2fd9O~CΧR?|4sֺ̳؛$ȝr.cNJFeboOdq ,sb,94GY M̴}H]:E$,075)܀(ob&vqMrRcVB#c)rmYbNB'5ď\W<~\rY3#V:Mx8j: 9U[j_.K\9 "PA6X~urU1 h]?*N{I$8q 4}8 \mF$bG@6pq֔=rz2dSv MX-л7!0R5wtV?ArRbKGD pHYs+tIME=IDATHǽklSeǟN{֮ %zY!d}l\(&&2M4 j͐8!რӹ:˜ٖz=<~892o0F`<YFNͷq7GF[ۺ8a?s&)ɚC" ~##P2r[]Q_9,6? #ZWpz}rP]t]ikQۇd*QluQ?pO*4+ JVWpznyjٺJ9&NJ* ^WW׬67y'3=Wx^`W^\ EM5UŵL6'`N{ g';U*.ȏ|Ԭ2nkjV|bƒ}ǻ"I-Ð@/J-9wjʢi*/ga"+ը  n"B=!d;iΎArZ&LzL쉜}7(ݢT\~[у,}zV:[|.}T{aT$O.1LY4MaU$u$*R@Tp]M)ؼh3E/H| Fij~y8m,Xj5r@1Ҳ3T{ZeR="SֈU/S'-]*\ s^c\huBѰʇ=8sÖmw!3;#~n&7oQߟ#zb1D 4M'O(+17U|Mߘw"JwCbK,)L(ϣhLB$<װX蝈_)6D 1%K Vr# wmi\1G\rX`&0]n^n E%#rtD hxY<)7*;3LSD\K{x NСYĜz9:aD> ;";8(eN3MgB_+Wʐ)aYq#U\̙ޗSO)_aG$jiN`˗/Ӟ]_gAKC;nHC.W(dgZ5qqpZ-Da7'dR,v9ҪY ٦%ou :$!>r.xCN 8 D(OQY9Bs&-|rDl‹u4K*rsu,v&]tMUvѢmlw(1\~cJy§ʕ :T.W,|-Do}/ = 3O2DYCx~?}<5:7%tEXtdate:create2019-08-20T22:58:23+02:003v%tEXtdate:modify2019-08-20T22:58:23+02:00B`IENDB`THELI-3.1.3/src/icons/collapse.png000066400000000000000000000005731417631501300166030ustar00rootroot00000000000000PNG  IHDR..*ägAMA a cHRMz&u0`:pQ< PLTEw"bKGD- pHYs:|\tIME\8WIDAT(c`@p088aVZI g?$~d_Hկ9!8#9G:dC Yj+$S$ /Z\ɱ%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/collapse_x.png000066400000000000000000000005621417631501300171300ustar00rootroot00000000000000PNG  IHDR,,;gAMA a cHRMz&u0`:pQ<bKGD̿ pHYs:|\tIME\8eIDAT8c` 02!Z )&bLFR§b, ωpsTPf,@ CH1$Yg E, 3bCQhБ$J `%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/collapse_xxxx.png000066400000000000000000000005531417631501300177000ustar00rootroot00000000000000PNG  IHDR,,;gAMA a cHRMz&u0`:pQ<bKGD#2 pHYs9LtIME\8^IDAT8 Q'ᗹ˙K 5~Cmx: (5hdn#J'm"%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/collapse_xyyx.png000066400000000000000000000006621417631501300177030ustar00rootroot00000000000000PNG  IHDR,,;gAMA a cHRMz&u0`:pQ<bKGD̿ pHYs:|\tIME\8IDAT8 0 /Fyzah4M!Lp;V.:?(y1B l סug}:C ߓo|%D=>Y(u¬,JƂPsb=cCVg3Mv5n5~#7"5K%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/collapse_y.png000066400000000000000000000005001417631501300171210ustar00rootroot00000000000000PNG  IHDR,,;gAMA abKGD#2 pHYs9WZtIME\8_IDAT8c` 02܁0CB]`"䡬XvP8cTQC@1  -a8ab &'4<'$yH)& MQ%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/collapse_yxxy.png000066400000000000000000000006061417631501300177010ustar00rootroot00000000000000PNG  IHDR,,;gAMA abKGD̿ pHYs9WZtIME\8IDAT8A0M>ʏMh{i}@(L,+ M`j{qN;ם1y? b9 "cXRCxOn峧V >˸2rq,^(>QnɦXVi`"9]{%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/collapse_yyyy.png000066400000000000000000000005571417631501300177100ustar00rootroot00000000000000PNG  IHDR,,;gAMA a cHRMz&u0`:pQ<bKGD̿ pHYs9WZtIME\8bIDAT8A 0 ҧ}>ƃzP#A4 a; )ePC@a*3;pZN?P2B^s+o>ݖfM u>%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/color.png000066400000000000000000000006131417631501300161120ustar00rootroot00000000000000PNG  IHDR TggAMA a cHRMz&u0`:pQ<PLTEXXXQ bKGD- pHYs+tIME\8dIDAT(ύ @D141cja9uڸim V߇2dPKB2?z#!B s6sU%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/db-reset.png000066400000000000000000000075311417631501300165070ustar00rootroot00000000000000PNG  IHDR00W IDATxZ xT9g3g&d\PnKPPv^}45>n ZAԲXVrnuk+ՠlYIB $!H&Ιsf2k[F}|<29'g|ߙ:>S*% 8`6˼^-9JKˆ(P(ܓ'݅ɌW !]" dJEH<?z>Ѱ#?2&'09hm <_5zt5n9>e1`KiŲƎKbOOA㿿pM|?P(kEE: JQ!j`B>{{R]vmURڙ/Hc-f4RAv=@iz[=(AJA[[a;͟/TU92UM̃3 V˿ C=E @|so]48`ں+8S2)DO@KɎ+)-جgZ'رc].¹7̒?7=oxffeʦjgF(;$kߥ)'OX_J5R)M m_ֶԠB7EfmuUUKQqI&[DͰ]m0 Y] edB:숶2r9Y ĢĆ{}{ԩ?3-*Re`dԚYga> MG LW5ؗ3^]zY[r˟M֝X)S+ Uhbcg zĪ[sז\Q_͙#˯&%hf;D N b W ]:ӷ߸5/ `æ 5&6Ml*BF~6,Ÿ1蔢i)_$xd'57#G>j\58GdV/gƨFpY)Yr* (7; NtQQSj1Ș2xGR4/5 ^[.7\*e+R5l@H*e?g>'K9F~a#yqӆs?rs +gSfx*1`r*Z%mKڶKΙP%7Bk1jo_}=ee`azU3ISP*\0PH0A8A  F<ŇWK:!HIY%$AR)r'}&څ# )&i4&==0aXz?ݰ)g؅|mu&phܺicV~/ҴNvp8J].̴ l}}\=s&1 an/`[ B kN@d6f-Lv7{XS0v }fRPo:}FP.jh=9xz{{b :}bڰsDI(~`Nz41(:!i; hA-=kS@Zy9g/liÉSMH `9O3Ur"Dv=> SB+jQdס!%.`%JL;,{ot{,[dܸ[wl*ڬINMf(vWrjU| '٭¸R;0?ri\4Po(R(IGn@g0D ڧ wS,,=B8S,+4*t .' `!q4W6Pr:js3ttWPi$'}Q]L'Oh<{V?S4M\ ?߱#Q`1=1PL%*kDBruOypKZl45)5X_&ny` #!L.( @zֲ itY/g^WAva]}DcH–8'!e0pƌQ0LB zU(C ,GkyEvڪ3x#f/tc->sc@m  xtbuZ^|;~.?Ly҉@pv.>IлZ2j&N_>E]]]u }+dT\bP@+53;z y /UEݗ`Y㿖rp iSIaA!g-8>-H*3s$a4tk+dՠG2=yB֍Rb9;^i'yd/^C"QdUǟmNqQɍ /Clu + 4DR":6D x!4`&Edw,{lwii.)SWѝ!u藕oe7w=n$G|(w]@3 OxR^BDє $,s04an[7/]2Xܰ) {X ur݉l]fܷ6Zg:%A + a͡sPT] v !W pnCo">:P#8ׄ3us6;yu"g(>aԄ(9%PwE -&;h@ :r13BMIM '(eخܑ}y]?ψbq WS hu1^+U?z+ܸ!VIENDB`THELI-3.1.3/src/icons/db-restart-icon.png000066400000000000000000000103411417631501300177700ustar00rootroot00000000000000PNG  IHDR00WIDATx TWzfD6Et\2hrt$q4ILW%n+.ȸLƌfL5MDTPU}iޫͫf'rsqԣݪBڀR:rH}'Z[h % hn N.NL&_yЭv:6XWHdCdK jkĩF̞=B7~/*"j_^} ,<Z505tDy 2wF'<].FlN- Wtؔ)X!S\P܀\B,&{[Em,Y bJi;̇+j\_s1QvNH3/g6iCb=@ڄcFM7X|9GaGuh Y"aTМt܆?㉂|/Q8D0#t||Ο>,OW~:(W^}zKǯ4\)d6ȎT赐]{P㠯K_Ƚ{uݚu/?`cF7Oh4suAI|^/Dq1)X;fYuxM2Tk)^SYrFB8RQGR 36d#4| >k07ٰlCe6"W]s $A) @!VD| @b1P8)t !`ۧݍ8r~z1zrE`92MliMXuD649J sbԌW'^ &6fBdH |#I1ONb2>'@"W r[:u'y?9xi ;o}"53+ւx0ٌmmzh42>,+%&ߐMQxbs[wo=HK|ػwf)_t5 {: " ($N#|8[ Ә*|P7p逭R-6+Q?f!VPURHPed-LNLN ~Y=_*#O`FB|?Gye2aòض9p FoO}i:k# *BV2XV7`/^9isK?]:hA-f}% _a" Bwm{4 iCvϫ*u-˓7''v $o݀9={`0^9V\=6du[N{ }+/#+&<\+B`^֔.F4Nى,$$^` 'b!9{leU )Pi9GgJ@Yb%OgMLߙ~KUkVRRTzpMs@DNKmAۂl3T] Y:6! #A>O//^vhzsNxb&%I臦 0e$+"S ujحV^Gנ|hyl,DxK >"VeDGGx"o@ %b @td ik5Ov ю=&iIyBN^μXz/Vx*up*;B=@x|&J(]<M], `q?:9]maYqrp`S> v VRdU%t .1R_ mD"p'cD9 wN⩅@Yy_&7܇/\?[:L9,9z0ƷڤEqrL60r9nI>doTgpy_XɃ}-nS-3xA?`GCTV* vL)V#>m\gϨa?4Qaaݩ?ΧĮU ^^A-px [׃.օ>)zEw;l 2JސeSΈRmNYNAQ՜PSh-1_Z,hqi6v giD,pA#5$xI%<ܰրv2a>p}Q:; HF+%[d+(8KRS7hmNjV;%W{F`Z߹uɰ<">?x%%%"7Q];~9 ,Rxm$HgABY`|l\l(#2A%tDѼ2xyH4)m6Rӷ۟e[kjlzCH} 7գs <CӘ|[8cŧPjtKFq# vm^(-ZLGKDMQYHsY`,3 yP(JKJ ؇%1J-a|>?{gg6qf yDvo;R__jۿцښS=IENDB`THELI-3.1.3/src/icons/download.png000066400000000000000000000031541417631501300166060ustar00rootroot00000000000000PNG  IHDR DgAMA a cHRMz&u0`:pQ<PLTE;䱾~}|||wvvwwqpppqqqk{kzk{eufvevfveufuevfu_p`pZjZkZkZj[jUeTeTeTfTfUeO`N`O_O`N`N_IZI[CUDUDUDTCUCT>O>P=O>P=P=P=O>O8J8J,8K2E2D-?,?':'9':&9%9!5!43 3 3.//-.-)*((($%$$$#""##             SbKGD pHYs.#.#x?vtIME 7ӸIDAT8u?Sa%ۨ8iniRjQ..Tbc.dž.lKlb3mm-tZ4HPG}<>yh@A dR2}}Ng0 Ig2Йd0+  dفA`CJ A Nhh'p8XCQQk#]Ĭ T</.M8%oO@%}OLJ'm;v.R=B0]7=2:p03;P(D9"QNYD">r47X^^~~XL bD")CA‚"iqQҒLV$=!+Aiɲ2(TyyN8[Y-Dc*|տp_ \PࠬU]V^kPPE@R4juZԍ*JR#Y{Yۄ LۢբV{hӵډڈVD]](Q%;2N=AzC[ۣ ֋h76}oYM~hZFcٽrf]p8_]x ?.v |f>Iot0 \\w4e ٔ])HS(3<׼8}U88JPwoidYr= cHRMz&u0`:pQ<bKGD pHYs  ~tIMEE9 IDATHǵ[lϙ|8d 嚄UpE %ڇRTUoUUޒJqlY/k{]mvn;a]H><~;?('0t&z0_ߏ0` r7hFuu7CO>}ddkjRpy"۳R*Go AK˲$I|a+T%wXl hq$PFQ5M94L8gx7>̏/O@nŢ$ \NfVM]!d BB$GR(z$Q LeL(VUi`{fd !@mi. *Ui>L$@ضbu :ˤ]6k0OD:~3)6 mo ӼpyBմZM%sesdziKزg08u75G叟ZZJδ,s$W ORP߂?#Q~6>IjXxw0oY襥ط3 cn@:(Ҫͺ%3 :tN}–ŷ8)r.  nHssລ m%X(>[snFc4E5j&+lJn 'lՏk4_p B#"IRU [s4*vvcZ83[N7MvY|WLwT2{z} BX(g(rû\!R$-(u#˯*H$NVk`kkGYfoߐc>&[Btô,I JXߔ :1uej!ITs릕ˤ.[?x笏,ſՕ`3=nfںiuSv:Def8[3=6s%EQr-P@y UʥRzyIjw[ d﮷4jllq I, j}:2ٗ+`l!>`g?y|LbT])}$t{kN '2O`*ǩUV`O/y{'zgIp0,̤9%C;o7 ko'zׯI7 rpI+Q%Hcnuk*/$2Hf,)nm5l1۷E1,1 t.}9L!VI;^Fζks^i۳BCA*Q[r$ظip C,M rfXÇЎ o-k침qnY꜏B~HO|1ǮL3YG&!M!C!8vٽv? !DS%ycWC-͋2֮TxeiV}j2DSNjnݏwG6u1 =O?ZRje%_e+䗟z%兊Je)V!IJn@iiAB* pn"c ``b2p;g\8? 眽{ħ9w3wЯV /-m.* h.EBBTK41esH=3;P ?+6li#8Zٞw+%w-&Jc_rkRV-4B@옅~l7b'q0’Kw4# VWBϻEc%6}\SkZpzXo#g?j`< 6t&ŜskI)AuWp%iyiSc$hz(}dۦ_evJsoV4C}bԵZ5=1YmR϶ ~UA_ eL?Ĵࠤy~fߝ|z4<}ٕrm\{*b?U X\{\7RܐO[ЅT悞Y6>GONX:Xb{/믛iހq0hfuE+I)w~۰~F #i6IO{ = %6{\^ǎ_f&1{ <#}2}~- *B*wcx֒m#Aaߧ@FhaM4QhӮv1}1Ͽ"8ӫ}v 9)tIza@Iu'ѱ>5ЬMǫRjI[Mr\Xh]1cyԔ/&팈 Dr]bG0 8v0΁eDZrI-VuVoc|)hѴꧽy,A?$}Ae]Q?"y4ОnoBQ\pz&,OM:wt+iI)BYtve8>$sۀJ|юY[<6h9aY)?"D+f>͌{\_1c޹ݩf#!^gvOCkwuhAM>L&5qQ>83"4йΦ&ZTcZ\6_Bj;;ܖ䗩Al)".F-g'5l;J3ƶfiASL*?̚`&k'%q`m9O:El> QFe:{qv"e!m)Z8a"@ į3t5s'<< sg }כ6C֠wjOJ; ~#ZPsKY \AM(0ԠE8f͔|feo6 E਴e05#eE @+b]Fsa|mUظL5I/ kNYuP|G^O{ *Hnyx<@) ;V(Iv{2YDI"4s2*|ŰQAy C3 d;|+Ӌ:*W,3?1͌k յ8tp q1q:AЄ)ܘa !<.S~%O % 7S!2 M M&~, \|(2^8в!N-ӹr5!f$dVaBq&A^@ oy ݻ|S%ιBV_NLٺe0e8wU Y!gXyq]r0LXQmXΝ 9װ?9e GsC!YI,pd%4i8g\2K&p]'Wue-/gv#]ɎIlMx BnI/I 6]s9-D0}i =sȰ_K/ sҐB55mG{EcwtK* LIDbaA6nˁ5Y ZaM2Y_(7˷;\; JF6 =md3^Ne6p8hV8A:rNAzMh; E\CS.='Ʉ/&:ooau@~TofB+w:/_ smJVb#T!ZRgTzfu~Fт@L%.Qt4kvI/ Ik}8 _虋hGяLkv󪼶^ ~1X=SB=Zo/i;eH uOG_Arn@ԃ# Dejs-WBgǩ%Mn*b:颱*>PM(Uϲ_6Q]sgX W< V_{ԳpB&PX-q~ZtMǗBl?4`k g?](N IENDB`THELI-3.1.3/src/icons/hand.png000066400000000000000000000010251417631501300157040ustar00rootroot00000000000000PNG  IHDR V%(gAMA a cHRMz&u0`:pQ<bKGD̿ pHYs+tIME\8IDAT8͒ CI4ºˤEU8E}[Gs=~]l5ݢ*);&̷)UpL "۳hZ=_rPVe[ v#KIJ|'/k]^Q(1G?e+B^N %tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00TtEXtsvg:base-urifile:///home/mischa/TEST/THELI/images/Hand-595b40b85ba036ed117dc5df.svgNIENDB`THELI-3.1.3/src/icons/icon_back.png000066400000000000000000000111051417631501300167020ustar00rootroot00000000000000PNG  IHDRF^F1zTXtRaw profile type exifxYv0߹^a9);37?vD,q )5翗/~qZr,1j~|Vd}~h뼩7$oUW;j֠-o5ȫ!gys}VŞ75~׮wg0笲aߞW/x_s>=O0i6d o[󈌽l?hO[k]QaxM6 t+xʺSmJ7>c2 S2s iGk;>s%[lߦ2&79i{2=Õ>~|}=4b\V0spYMöQ砟ımnAq'^LW1hx"ht63:o0A;E=km4#.gy|$2*C1C 5c1(SJ9T>s9\- ĒJ.JWڪ\_9lsͷbK-j>cO= (@8ȣ:J0L32k-Š+ʪw]^}ڳ~f5Ntk$V|ފgX Qq01<觱a><Wm /M6Vb:7r2A3By 74|tu%H<6uI0D5[5#Kr\/\~81?AV fMMeuƲG]eAi񙡀CQ1ZJE`6˳Obh)3r``,[V`Te*+_)͋~]vǘ dD8/~FZWKpۘb<3a'mGAfZV9Oh_3XԿgC`QP"ANQ؁ɍ}KljBOIfFh1Ps=zq猤tMG$빂~5E%CyFʦ1xQ{>ԘA/:vXF$ sA-9Z 3 Hc1-tk;n@:0: De\tiR"o&qM!(MTeе3D̕G[\g/ܥpt,j7o.e3L_,Qy=R#ZِT^OSOq'9 X|JPLaSEp Tᑭ#R%1IbBg$ f3rƆV39'Fː=3ogAp>fU]sڃ!Oﶫ&CN3mB3Ol$6H:(5oͅ.tkF,1C#i ; ӔHĢ@p %@MG4tiT~l)^"tRozVx̬2"lTpl.d@Sz vZ1U?aT-C8 Ӎ+'Z5!@$@H;&`zCWRϕ3#HޣK?~O{=oXT zuQIП>? G-KqSʷ~V}_8S_jo1X}$D5ߵA3dVA|^Z(x1Jf.J7dSV&^@i * z̲G!sЈYX;HVkܯee$[doX’O\w$n UUT (fuY j}@U?k1W_>W*:~]@ um֬nF(=7 (]&FLa,DHyyu\/{+&uЧ:]j,BA QIq3Gk(/KGir2#S M/q BkrS(Tkۻ;wv!.KrP!f. ykNRs#d<ӟzJ|>zH|GQwadecu9&zZ ,$ψֲ,QQT˦\ 0 \DQsX}z;{ݴk=wxygjqmz9贗̜nWivؼ4~M%BC]Lx=0Qim ntW~^B<@xC׻/n*4B-_(4ԧ7,mǮ_:~65Eu)~c|2zakتp=ܾzakتs>%`yA|^qJVߣ;O#/~GK*6ZԩJ]UiCCPICC profilex}=H@_S"-vP,:jP! :\!4iHR\ׂUg]\AIEJ_Rhq?{ܽziV(鶙N&lnE B@!LaPf1+I){zY5o1 0ô׉'7m>qdxĤ ?r]segFLz8J,XicV25 ☪/d=V9oqUּ'a8//qX"$PPʰU'B>~/K!9QnN/1vFqq+ԁOk--vl-M.w'C6eW  )ݫ^o}>*uE^ywW{oiwr  PLTE000u~ pHYs+tIME A JIDATc01B F1B F1B F \ @KY1w*8< g9IENDB`THELI-3.1.3/src/icons/icon_end.png000066400000000000000000000143361417631501300165610ustar00rootroot00000000000000PNG  IHDRF^F1kzTXtRaw profile type exifxڭgv#;cxsfo%@'"~Wj5*LHRRW+R%F͗/ʛy5/r|n7,/Mz?zz]~i'_ܸ6g˛q!gus]{0O<{? c@{*;qzoOON~/JS7=17~8 ]r݄Vzj1C?~=oךgvGeRשw|acw'>wUw6jSK1/0,3k7!z;mڎZv1q^ͲI2xqbvELIkh V/֒07F盭b9O.6 ۾FK`fLvhcm?;I&`:L4:YTFn z"Vdgm2#)p 邳>o*C1C 5c1(8UK>SJeC9KUbI%Rj+mU>_lsͷbK-j'|Ǟza@qGuI(M?Ì3<ˬX[nV\iUVyկ^^3(\{)]0'A|Ǭ7x<h+>xos3]S(8gذww7u7sJ\_xNXak nlWM6 Tu?m5uxnacHm ~Q_~Yݽ֩|jUY6V8'@Hm = m_\ѯ=2Eu}I_YOvuS\oy1,n߇,n߇,n߇,n߇,n߇,n߇ֹ}+:hU@X3}2r <mtګ*<-9&cպqLILO[r@o;טq02tK. C-<(oTx}WǴj]aa*svzFlչ'C baRD!䡱Cu~1 Ă|}pLqSW~᝜ wa⵵Q•eW.AZdD'z \GYy VDԙuDO R)b1z̚bxݬ=SϘ> Qs{^5ltAjfb₪ikEDL(;qkY&Hx"餔 qv\n2ތ2me!b*A_Ip=zDwd;O)(u4|iWG"(USA!\sw|]w̕f qW įάMOcRChΆԽmF$Z;:mV_eo`wp}rw@*[[dpM̴62gxe2}臭Ll=lzl#LMw.og.\?EJZ@:"|sk'HTId.8T8$}pmB:btT'O8٧<oPC7Yu`LG\3<'`mbyH? ֨\JbIf)Sw,v3,V hl <*tA>!-މ<4%@;m̠鬇ӼR̐(P#Emj\C5 %?y9GuϹmr(IC޴"PaB ౌ/`4ZR[I\'@? _(1|`Ky0'2-GӨI ODorF$o!nŴUZcSK/bl XFHa<1i0EѺ^j<y}JЦ=_`I{{cm7Ԯz򗄧RBƞzYJF š>ɸ.PӌLi Až ݉5 P6Q#I}՗٢d)l% )) i$4M-ux  Ȍ"Y\Zr#k|(o\tp\p6`ۂ| ]Vˮɥ$R\/0cңAfBLL*#aDcBEAdhPL,[#\,ux2OEC gڥ,Ⱥ/&6 ,+R /SZWcrIp oGnsD+]DT0E&-N^ZȲNuYlyLu-}Mp"-g$t uORŢ /PL[sr6 `'H uLjAHPZUC1&q0NGa䔥'(hb"ȏl<+ yWTo+SbϿzŞW3՛ȿ~#^KSpԴ@p A:H3AXd$ 9ڨNAj*/.6vAWq;Jik$LpרUxe'NxTC: h;1#%-Q-! lQ"1pD &oKNf< Mnx½(@UdߘBUT?/TJBU}>U5W",ep] 񲔹=K=6$YdEh.gB?fDR4(0:VHGnn0l"!57B!n1$%*(QxD!IԹ)<>v#5E+3+4'Ne@0 jO1~s1^#u/2efL!x I `5$#;4)+pR(PEFS'rJ?}ت}ت}ت-oR%<ݜWfd?qwLș)7警ə)#"S(Q٨N& e.j ͊Z5uK5u(kE$ـ˞jiY lʅ8`{T >Xz[)h(VS|R2~q?' cx9!Fg%\{BW(=(l:KtPO v@ݎHyTe .8 "o2b"O4K."h[#TN"?2˺-,տhgE =G/ZY>BPIi ڟR؝pzeRˁ"EZq̒%2zǍ,[[4 5Ƞŀ=59 C]ޑ Uj]t vCv@׽@{R(ѐjP%H3!hzʲlM>7pEs@,>gt4h9>A([L*}!,)[{[vŝ塖Mxyli;)[L0x#gFZ#Er3]YʹAH/)#QVB7")Ǭ= JSPY`4*C))=肬^益CNi hrwzB@.[x0"4H\2%&DK[Tbnb3:d}GPM= d,*OEN1lMo6t)ʡm JUE Uƨ_(}'t6V!MҕS\vwʜC?9=Y>9Z2ѲNeDDamРEr9щ,8G:9YKrè6P3Q&K@da-&b!CRce7?lFe}#!m89B![:f=3$ED\>(Ew"+k`ZtԠ_dUs=xcrha)3eJr qËT%!{Ԝ8Ux}l+hV3ePq:q<@je>J/3g*{n̾Z819qM|[9Q?rs(;uW|ZuMDXlّo{ĩHIէcqwCfWr!D!ҨJAHM>g//ŒThWoz"+^2뫆Lǫh6|2%ګ. =`5Zne+A,iU9\.;,_(uk$3Դ`(uQj(!~iYh,¾~m|/Tqi~;O}qNG{=|?%Rim mO7:<|΢p~-\}ҳx4o.s;UNV>try%=k}3xmڣ7ê/}9Eyw_-v_M~8m߇,n߇,n߇,n߇,n߇,n߇z6d~qg߁Rr6X-w]?\\q#!lF꩓DK:T|(n~^a~piCCPICC profilex}=H@_SEZ ␡:Yq*BZu0 GbYWWAqssRtZxp܏wwQe5hmfRI1_CEA2f%) u_<ܟ#,Df6:Ԧmp'tAG+q.,̘LjR+ʦFwV?՝rhEt PLTE000u~bKGDH pHYs+tIME ÷ UIDATuб!@ ?J [ hgSo?hRcӀ 2T0 P/ .^UY Y#IENDB`THELI-3.1.3/src/icons/icon_forward.png000066400000000000000000000111241417631501300174470ustar00rootroot00000000000000PNG  IHDRF^F1zTXtRaw profile type exifxڭiv0sr8;xĎK\eٲ wʇcQ/!8e莯:4gˇql9b5~7>ahYe3Nw{qu+eq{~O]MOw"c=#Dyy̮0W<'uą s}[ʺSmJ7c2 S2s iGk;>s%[l2&79i{2=Õ>}}4W[1.+b9y*biӰkqX6sfUAqG40}cѸ` dm2;fSu6<` v0J띋8'[{` .k}x@!ĐB%袏!ƘTM.RL)TR.r)\r-8h,K*R+V_ir}D5B-JtC=K75H#24(M?Ì3<ˬ - +*^vzk{5sznGukN҄: 3#- ۪LcnG}vgwZWeLX׏>FݝW7 = m'.[kA7aU=lg}[nV}U=lg}[us]9A Bš$#\F*!y`{R%=z5 5GcnFܣv&SӖ6ێ5fܰ0b%|nR*:w|p4yLZhZxZXyLf lչ'C baRD&o#%Mc7ձozb@Ă'Y6! 3=&HV՝j$Ihd2H 1ӲDb6_{BZC,૗qUV<Q;]>p#Js;fM17 i$ey #LȘײb9QTgFMCvʽU6fokFgދt;{B6Ō -)K&地"Q ZmC >v9\+ $OW"U\Q"%?U;.xm8\(I挼zDTRPG"Y[cY]v.sr+R솒&6Wyo^րUWftŌaH]9 p&hEDSg >3_NI CF0>Uo@NcA4Ž+ut;0}Xv̑lWo;ƪ4LE 9hu6Fkqb~|%k׾ (zl&6 ej⯼UB\T/`^>&a=n!|gWf2& =hWDYN^.̲ 6~?5sݳ(ke;Oop_KM^  S z c(SH%T -_BlȪ`/u?[RDwrc,C̠n1"'+h}.QmHQSe8hNFٶ"=M%ThxRUhMV 4B+:3^KXPFa<Tq:%O팰P1 (`V 2T,t>u/)*(n3iDuL?ʚ* 3yXrh30/SI7x,0Ue'u@ZL:Y;Y3qˤW 68!4|$񇳢K |X Ak%W~Ήw:Qsc{&[F1-jJgPhf1T{FٶZrpD yF\Nz#sѽd]y ,$5)kG69{m\'6e`Q"H3]2_Ts'xP7d bȗh`AYZ:oh_l] xxK Aj_@N,is(@^:a>{@A,+4 4Μg["R2zhThH 7ô=f eVr`d7A88{`zL[rzP#d4vA2SM2AO#|У\a}+ :oՎG z<7fתRE՜|m$ѷ.HFNR4S.~\T dK"jUJoz>$e%ռBIW65J8sYT{q]ҌەHwb!屇z,,tC:X9c礣uz:8I"J" }FON;>͘`+y0%M#JpI'Ҥ1K <=\Jd2emϭA6APq&¢;u^+`E*\1]KCz]| Z=@BUvXuҖ4tV;O }%ݱSu[Q2s)*ѢVTÊM~J>qDnL#jՀVuR{ï.vӲIk$`˵@|\({TZ He&iQ V/K1ĽhQP#ri$u-f9S$fMx/}dx7#Y>C^ν2b69FU<D]7Lqge]8L!Pylqzf@gy}(t( ?EB$ d +^-e~>'Q`O0" DlH [&CDO 3BߨYֱO3МL~ZFiIXe<:;kEh2A+zg9xhyE0S5.8Lڀtls1@۾K\ɔ#OST1k M7AvLt<`' #MOm0HǖLM: RV"~v|~.n%@\ J^ꓭOvN?BMj@7kNQtsNjVYv}2B,b2uc+^i@.~8[H{h!~-U=۔ѦD*Mjrxhθv~{dMsy%> Gtg6~[KGra4G6Mg6OS1󡍳KG{z$5+?}鲋qe{bGSt}ݴj7fׇ>Um_Np?jtQå-3ܾ a>{تp3ܾz[7#3$g ä%OyNSsnO cfRFQRG7@iCCPICC profilex}=H@_SEZ ␡:Yq*BZu0 GbYWWAqssRtZxp܏wwQe5hmfRI1_CEA2f%) u_<ܟ#,Df6:Ԧmp'tAG+q.,̘LjR+ʦFwV?՝rhEt PLTE000u~bKGDH pHYs+tIME /EIDATuй ! DQ'&oeE^`^QdWz#@H PY5 t.<'| `RIENDB`THELI-3.1.3/src/icons/icon_next.png000066400000000000000000000133021417631501300167610ustar00rootroot00000000000000PNG  IHDRF^F1RzTXtRaw profile type exifxڭiv#sr8;2%Yw-9d@ ]ʇcQ_lMy5y}fKWwuS7$]oU86'[ތk@Ξ[{a9y?Y'19t۞'9ϸ_+e_ }}u0趬Nu߶{82L}Z#5ꪏ skQw|acO ?YW`MX,7TܯtWk;>k%[ly1&7x9e{-<y0|?yh-1:mżi7!f]6 ۾F8͜Y` тy`m?;_ċId:L4:YTfn z"V=`eG]5 >He TUpbH!jtcLQx&| )r*a>s9\- ĒJ.CU~B5B-JtC=K75H#24(M?Ì3<ˬ - +*޽vyk=5%Kq9F$'3V<'>:\2sA? }܏~SXOfSo6[$QMaHGjs]5n4izʬ?n`!Ybj疒{TWaP+1VۘZ|.VKi*3&NוKnb&/kd62}-ldx>~6YX55j ct+Ǧa &ǟ6ɺ*f۾ga[iw?G|'wT# kZ\rvx y۫*)$x[sLǮ= u3e#6Y䚵Xc )[rijFy#ox5yLZhZxZ XyLfتs/ʇ,-ꥦMzcFJ:7ձorOlmCf*~;H!5tErKGWtTJdЬ{R*)^.MgI'"ȎU9@@Hetw;l"jS@\ҝ6_| V;f_>,=YB[&@˃VxTm@4c*Wgh +6P#F_vr6tX`A$~rYFqV0Q3zWM .Ko^:ӺMba< m3B*FagsaTevu0v,I[$>}%!4cMI?6CrxhyHE(Ѱ= V4q i7PX4QHL\ÁC#W*2c+͡FN%jk0c_cڊsg),2mmQDmk X $=p%V %hj2Pl4`[3ӯCi[k8mj\y3{;p'X݈p/qm)R`CjLj|jtRK@ƤKsV !݀w`!siuz8NcL-NQ`+:3])QdBaS!d+T̕K#8V9$\Pv@`sYVGLbUR.7 KZ  x AhiWAтvOT ԡ[fJ Jx% l͎jo ,* rIA'tv57`D{aPvf**1vv=OX͆+;(ҲX76J jBJ@xv5V4Jd bέz]; V"Hqz#H:&=Bu vN߲KV"N_ns6XڡC{xOz'!Ya=xj*Y~oCsD 6$~3G}2}tvJ!Yuʷ(NTo_~"7W->\Gd UޒPyAK HF$#a"Udc(lbuXś E$lHO%c?p$=(͡חpQ[ﰔ?)mp#Q _ts6 9g0WT6Pj:diX0M BD!jjt! 7R&R^% X;kK+t{*{f2TPm*#)'BόlPxXjVI$ Tme&kiS:^g088Bj XINE\%)w'ZD:pfi ]J hD36%Q|O: !ҝ w"tj!̓LBN`em& GxXQr9{K*Xq`F( oų]MEilOeet5zЋ< * UleRuo7V#Y!GhRvX!+;J?!LM V0#$}I͌㻃ˀ) "%+cMB\ϭھ[OBSDץ2}(B-8 $;I@QCV$#qPk{]L'9GwtCYҨ ֒$Ak-'Dn/Č쐦UΙ C$⚩NV1R(+!{+{]h]=΄}Y,h02Nw$8J_9 1k-C8ėͻ /Z@V)(6d,38@w*p$+)Vw6mlh^Q+O#[}ԮcIg mYl=?P~/&<;Htd0o5 #΅9;BGs4p@5,lhE6 >#6h ܇w;) bB&>q8R `X΃2 $="MμȆnİ]xhr۬X&, ETTWëݖwFz/pI~RW€j5`#?,%J {0(wPNTd"o'MC'>b~ew64aMsk+䡔筣WY%|g2@L)UNR2#Xi!K?SHg A֓]"$Fk(w=u4 Y|ņbLMn^C=ЭP6Iܶo{\ :C=H)`  /[ 'r'>8Az};;}qZ[?[^:Լ' q@F",\ٶSE i)+(pW?i3=!xκ8srW'^#Y5%ӈ'c^AK{)5#oCI_{ѡTu$:ԟD_ȟy:j9k i׺CETFϒeCK Ը֖HrmN C4$}9rHѸ ؚ]B˰{| (-o¸·vxXxi1CUχv9-ÔT|P9v+u>s.~?x-P=lw[>x=V+ϣ_P7> N _ǰe_.ѭ.~k}Eͫ~p귶c?-Su+~ƺ`kتp=ܾzakتp/!@y" E_ ֆLLui*"j?:i\Up+&Bi ݏ2iCCPICC profilex}=H@_SEZ ␡:Yq*BZu0 GbYWWAqssRtZxp܏wwQe5hmfRI1_CEA2f%) u_<ܟ#,Df6:Ԧmp'tAG+q.,̘LjR+ʦFwV?՝rhEt PLTE000u~bKGDH pHYs+tIME @RIDATc0` 1B`R0eA@EPT"+kEn)N;aKeMU4ckIENDB`THELI-3.1.3/src/icons/icon_previous.png000066400000000000000000000130551417631501300176640ustar00rootroot00000000000000PNG  IHDRF^F1zTXtRaw profile type exifx՛Yv<߹^a9);NTEJ{ʇcQ/&u^c^!ǫ;븩$oԯq5m@'w$=*a9׿v]﬿Uv:mϝ3;>}G>OMĀw_u} t[Vb 8#cw3`F^kUעnK8aN/|'ާ]κKmJ7(bee~3EoMZ.b;7˷Y6)0\?9\̾oq̝Lk V_V xN~s1i5_X6sfU3D [n8/&kLĽ1h\0dm2;fSu6<` v0K띋8'[7$ϵ .k}x@!ĐB%袏!ƘTM.RL)TR.r)\r-8h,K*R+72Vʁfk[jV;龇{깗^n@jđFei&P~gyYX[nV\iUV{g}^3v>nC >c<ڊt6[Ls2 F<46,s݇~ºo甸9%{w=ڨnvD!6!jLݮi+Y(5|/1BV<-%Xɩ>O.VG55$7c1$]X ŭ VNjp*3&NוKnb&/},F& ǟ}FK6^ ayԚ9aDUzY#Y7@_۬0pC0l^2{Ǟu;}]T>5, +K]vOWԟlS@K<ٲǰnkXzrOa%Lkتp=ܾzakتpf[&r\5 IFX;T@C<7UK<-kzBj݌gYM$g,9fmn;XqFaf\AZPH۫zu&i\ MX 9@Us+ɌS[uEЂXE4|HoHIrX:E?@. |F醙RHXnAqXLB- Ybcb |$rJAҮ5RBMwS|B:$TL܏{\ضo { Úg@)9W{ &)[قC=Ei6_Tx+d!}Ѝ~ëz WQ8qUnh)Ayy-͒|GEx'{[3갎ڛSmrO ^ wxAgÚ:"5Y8GkRdf` zMscnM s54^ fF@ JӐO]Q>p%hм5X} stSWD8Eř <]m$51S|zuu-yFb@= !CFdM/Eɰto''2V&w1E9@'j$Fr$&팍' 5s>J'UcR)IDxٓl^+"?BYZrԑӘ}y ? C脹60Tt*E-P !W bDߕX%9U;&~ղ|I $ >)50^=#qt@ICh(KHpa'"OA.eoYNG0b[k2(FڼeZ]47 Fu36#&uTj:me$TDF#U1ƤWi+z:5CA%@ÔxzOk=Zjk5E@ :Or+d*1(ȑL#pYc;lԭĉ 4xagq5-D=Ujf;-2ȭLci?Cz"[.h$P9 0A(hHT=f\,a^C=Z}&9ݐ9I+T@gKsyC#oLq>.&Cdcu@ >vƉ h3jSjˋڐ`Ϟ eM 3r/zGSI񨧒Gw<y ePjeHr1- 'XRmvI@ cK7ov\ nMxwR!t]M q3"4ܲnLa)s;#w{Bo |CȦ&AYM"0$_/eIwMA}mf$?K&`IrP2Y}^\#i),₂o! ;M% 61B;L¦D`~bB+%RBHr 3HPfCč5Q_Ƒ~G?]Jw+4b-GF>jM:(P- ]@:,t]D^hJבZl4_0$3x; PU\]Tc:) WR) ǡNCɅU9JxRݡ}jR3C TXPP~̹oo_g) !1ȬR1ՒrtY&M,]J>3H$`<pBj7j'Č]%L9/b8z ,u"HHE.ȤA"l>>dXU ȋE[8Nl|$0' M6ye%j)V T=CsJ]!9Ȯq`>=4Cu)E%cqtJSd*diO)Ӿ{ uDWsA uqgp @ ,Sj,3"DF _0&[W~eb"6I"RD+4d>&kf]Α&LE%,FX`8"hTmCC` ~$y)";ZslCPutB yR%iY~ӭ;#^U=48>ɔ*{gYU#W]KPvL$nu@r6)iSA<,I{S{t7Q۽)V1kjI2v-K60 NKϕRsEIJ7i"[ZK>QzHj4FWL.)$f+,B^#iAk#͇=4uT g&׆OnbDQZrLxd+vmOY<֒R%o5TR i !,`1" kOv0bvSwsyL=ɇ6t!w8ٰ&Ma7se'51$g[iӇHVSW@X$!6',ԟóhP^fopS3)݊套H9۶4KM,ou |ZaG^7v'4%:C:wc6SD:PH[Bg/,Ky-[er(_emɱ5LJ ?.l}r٬)UH }m2H$X&~S'Hs, "+Q\$s!jk [*_XV(Rs,ws?Gz]xD5/LC.by98S X&eX%RSR6׳ݴѶ~]fٯ8u?p=ܾzakتp=ܾfY7$h.džwV?՝rhEt PLTE000u~bKGDH pHYs+tIME  QSIDATu1 qpw?>AC%2]USӆ\) JԒZ:1LQ US^QIENDB`THELI-3.1.3/src/icons/icon_start.png000066400000000000000000000142711417631501300171460ustar00rootroot00000000000000PNG  IHDRF^F1EzTXtRaw profile type exifxYv#D^a9y;u (Q%2`U>K/_|7Yj߿|>>\rg@Jj'_ ]tҳ͸y5nUMwӹ~Y'19t۞Wkz_w>LĀu}4tV|u݄V=gZ#5쪏 skRw0F;xw;;^L)fj6jmr-d8/f٤ptHeB!ĐB%袏!ƘTM.RL)TR.r)\r-8`,K*R+V_irB5B-J龇{깗^njđFei&4 34,.bmWXqWYkWzs{\^Qr_S5aN YoxV|ފgX Qq01<觱a}zG)OfyN )qݝFp붃$ )H?n6UcvM^Cq{)鷔cS}^]BLÏjjHnXmc0k ]X ŭ VNjp+#&OQ&uRKZn-WۂJ>-ˍ^ ^S0vcKrljưimic~=D_۬0pC0l^|cgwZWeLX<׷>FݝW_loxmvwjc/ST9~Nq=?nخnsq?/Ӫuتuتuتuتuتuتm|wT- k&ZCFX;T@Cy@{RBc0vMQX(ɔ%׬ s7,0LlP #CҜ2ƒFJ^իx5yLZhZx Z=Wc38/b=)Z 3&o$uc? %lmCf*(2u,l%p/_w8WPMP Ln05"Pds{Vf݋mDRv0j8;$V/!y8C?x@#Xg5.tsc%L"9*  OLba1~`"x肜k*1L ضYe"ߢ}6{ !?y٣a\\ 8=XB' " tz ]ȁ-A/^[=iGjK\`uVWUJ /k *#jm d(9c_!JҳD?lD ݖ[/]PӶ0 _wD๒;0)uk]qw'-{w3>{oj%o'-"~_2nبv2IuwI/)3d YRj8Ri&L[ dk\`Ɛ;O~xUrr aH^"-534jҖ +F#[cb}M 52MM(JhLytRhV!@<2ZTr⬼xMGbuILP6Y@aL|Zc@Zy: h-^dHJkskǦT~I1NaD$h^Oҩo%w1Yd]uaɒ c @GW!~U|xs"Ue,"t/)  '}c1@j'Oh1aG1ތW8J{5[t(+>&; В91b)5WK`$CgOjޣݏqH+?'suNH$%}uܑ=dmp` #8Y%'rfIS)PVJTPV_HWݱ& N$ދZWn)ӧ+*TӺH2L%J\pFlUglv(MכjS"T:$(~D=p>*`?5&2BVdQكc'J,3A~,Hb&\(fݻ^AG81 #cOy@u(gҩG";-U U[z&#KCm%A@kZ֍dD  = P&D%ѢugvBݩUBL>PeY!iֆi-`G2qI}_%_NYmCpUJ"7roE$cP} B) *tl1d/8z.A%:#"$8dCJ^H2lR(UQLߤZL cf=ujM7h | vώaN?l'DV[;49aK~G5Wt"u6^MUZT$ߎ!t1՟.<V`}%$9CXirKǙp~SvTY[KجqP-VY* OhLT%TrzLuڅ,힉yp-Aț9B%-ԕS<(zx Q]((FOR+>5{f"4)ppC)ɊHfKFM!Շ$:s<{PDqF^ #l'ʬ@Ȑ:j@M&M/6Ǒx[~H e:bA  ctb ':6зZTPRޝtN[Iy_|EYЗ;O$\hqPf#/w{xTl3x+kNf,k~'%GZ?6〯yHU "'ki A9j1I&A^٠]^գRV zd"j)Y'>G([H EU* yK}ɐ|L&Ϥ|J?yƍB@Uk 3l3_E$vSVI:2TI]E /muN~'(,Db ~+b &Ol@cAW1x_ *vDWA.nz)J}@XДb2wo<y摊0Y@;@m_~t_PJ˧bF Jb5S d΃ Br?zʂ:(G`Iud/0VAr/w۬ihO7W$UqDీ58Q%:`QTAA,"<Ȣi8RR!*Ѷs(\K6o%ۺVH޵2|aieRXά^6 ]f[ނ]d9Dgz!P:w^ø ,zㅖ_7 䎬ْN!˹s8A#/V}X.)J,X_l Q "9w,PL6Nd(4MxM!rp*54C%"@1Y9#ZM"Q"w,2ya664E (>NVqU"%>OFU 󈇇''`<Չ1yUw>%'p>.&аrۨv>tX sϨ0B)7[$V$7"!hk;J>dA&GJth&BC1 M $HQi#Xu )l|[Ԙe8YHa#:& eudgزF3Vu)Y@Nxd p əC#9:4t\0É1VƉ1VƉ1A Kd>]ccJJ60X Zp >V9o !R'+3R=)+YOx4OG5JӮ_˙ѹNGK)+k"8N{HܝeOt[Ӭ}4~o-_ ?δrTud8lͯ-lVtĠg }\P9>5'iPA]fiWqYE#:3WwV?՝rhEt PLTE000u~bKGDH pHYs+tIME  oCVIDATc0R0F(e@PF(TP Ta@PAJPp)bvp+wܩ ,*tIENDB`THELI-3.1.3/src/icons/iview.png000066400000000000000000000010301417631501300161110ustar00rootroot00000000000000PNG  IHDR DgAMA a cHRMz&u0`:pQ<]PLTEXXX ﱗ{bKGD- pHYs+tIME\8IDAT8ݒ EKq_3mBcgO̜C*_ Dž@sC!e&0ED^Jk^oTF*yG3L`^+o q8 Y{QN?+۳S(MZ-A$ȰDƝITB!_8 jq%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/key.png000066400000000000000000000006051417631501300155650ustar00rootroot00000000000000PNG  IHDR>gAMA a cHRMz&u0`:pQ<PLTEXXMvtRNS@fbKGDhQ pHYs  tIME\8QIDATM DQL'[69P+[7MqV H ! Id\ko`8Ò3={^. 3~n6 %tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/magnifyer.png000066400000000000000000000213201417631501300167530ustar00rootroot00000000000000PNG  IHDRשZzTXtRaw profile type exifxڭgr%cx؈,\\nI$ud1 c?ťlb*5-bwy_߹__x.cޟ;ӏ>~n<~f}yPlt>fCO[  \ ~хs~{bm\?=kZu\w#rOwΪ7ɣgR_Sq`9XomIS~hγE\wu߾I t⛟ᅀbB +T"1\mz/y9_/y9Jsl^+_ CYtיG D0eL1[9d5W/X"ޝ Dfsc%> .1P Ww>wx!)PM `Řb*)M )r*z9s.Y8K(K)kkڛoKVZmK{Q7PKz$ŌxQHhbbf&eRpSĈ`Χc#r7q97"g"g"j_ 7@B 7}XlW,f3}㦙+1XM;F8@9> eol,vxj T-q66XVw (=fgQxF-# pOBXG|@&2eƩ>}:,-DgͲ2Sk/Asp~zA،/ƾ}|=̯kY+"Bj(517P#Ew߫/YobʒOuw}{١‰ZF56k[(Ss5I͈SDY c۾IVlJvjx9Ha@jb]xawʟ1)E)67OJVVw,2pWʵawsĭF+eb`5fWG%ct,~=%Xxu6?}v00MDq- ޕ_F49~}H\>!N]ej˘ņI`^y/4C)Ŭ43'^w#1`x&BH& x5A5`l[v l+ $`ʁ=4$ZfBm. (lNIoLZKvtp#yӑF&dAꖡ GCq|Ъƒs+d>PȠRbifa65vvIn|&ʲ >;?\338ss1`# 'CUR>j.g7$~ )4&r'DQ͈7Ijвjl<3ɨ pf_Q+>jvBV;:YOV,*R KT1OuI,l(DͮD7 r+$ %xYWv CDGnK:ioo5[Pؾn4x*ev qIJZ[>$ Sx, Kvv-ϺW1*x0yM5$c\\Ƃ gN^ ȼU /S+>IGezNEMRe@SBA(-!g(,f\ᒀ! $LHVh{/RB o%OH7$)p9`5ȺsC'j-0&&Į _j܀v*i*cȽs3)B>wc 9EARj g\/֕:."i| -2ڀ֒+ h-eLSl^ջ¾4uPp+bX~P2i=z0bÃJ5JI{ƄV+ FGPY_SNx|y =Lv­#d)/}"}nsgČe%e'%|&pUySRs,KIKˍ V'6K"W@=UMJh/hu|i.+"v^?3A$CJY)ƈ^Y7`cjM)gu sՈjlk\`IW+xݎLsޒ(&!QFA\H״xBU4NF` Gj`8"Pr(xP { [ɵ(Lԯɱyヹ&GA.tt6adWs(쀴DŢ5:rd_}6 gm CNSݦڳ fzQi"1sf#Š*}g Vʕ nyl$G7hYfD甓jk*J1A@A%)80OA 鴅ٌ  *` q(+Y]Aj2Vy8'+qX2iO "BP\WߍK7Ãg/E+WҺ(B"b> XKY6%'KrpmcVj ͫ^T`RkXN0ZCbVOWd@=6[<O/$slWW0Ve^ OܰJ1~Gu)~L>vo!QVzePCޡ= dބmhlQR$ XA5~ kX5R&x򪝆BJG8RA`p e \Xڨk)@9"Vzg ZNph]6 kL6:GgeKh1A SZ05ٮ`L T)Ym] SIlpjҫGR5 BL;,j oZI!`'6>ύ;0SݡƂ&IZGi $' aA_ R] sjw Vl)XIhA4QzIYT JE pBNj>rֳ.QPk,7F#\/OC;_cl&EH?4+Cj%$ڰ8'K =c! PIWqs!AM_mjZ]g<_E;M"63C\ncJ&Q1}\b<Xh@f ?5ċNq]ǰ!w>!jN~4 `a=;XJj! m< <"M#Jy:n[Q &(Ⱦ AIȻmEm}R62p5 ^4'5dTuCxOHԫ/QS&׆LxfvP'*%+} ]*)o*s!lJjBIN +51%ޖ,"L/J@h,b`aLXb;A"߮[Z/qOUTN^l\Yxyc:8.rڞZa56A# K˭ JIoSxd@)t`ԣnS*hՍUo$V&'fyrٰ-K_ft+_qO U^ @tEBD~3aC_V;Bձ*Q8$F>*$<mBZuIham7aZk5< 'dE,C*,NC|::04G q啩5B.N֏AЛ>;מ&pzՁhBIkDڗӧx{'*1ɡRw>໌_l)/'wNj#͚*(!NZ  ͷ*դlV&}҂cr,(&] ?Sgw,WRAnw4JYH %L-:*혍7e?mp ZH?5wܑ|KF_| WLmJ#H#uJְdʡ !YIcm0.5 YNo*PZ5]IdӂP(+Cm&;{! o!x_?g6vgKm1.U_8 ׃.UY}{lcﰏEAT*.P_5{r*1I2BHU2!ܒMu?x$ɝXhư^ N]j|OHფTI2Q86R,;%_4B@ڕׯꁘ8Htq{x<ƅg(L9cYb~5: W(,BߴzĄȞhh6k"ͭOr+F$Ǹ/A]4 u(w"*Z<#i{U]B2JGh/ɂJQ$9}wTajzv-;h!,䠦~y@R`1Vl:0a,(.ukM#ˊc和1?*"Sv >z9AKY@W{2Pv!2?tsmmzx% []?LBN wkLŎơȭ,5 ۯR{/ [qx$,mEKf}64]?^iCCPICC profilex}=H@_SE;HP,8jP! :\MGbYWWAqssRtZxp܏wwQa5hm 1[{^! 0YƜ$;]gsռŀH< & ޴ VUs1.Hu7E13yX`YԈcSXYXuCHbK BA eT`#NN4'|Q/K!W BwVarK %zvfqy+6Om-vomM.w'C6eW  ) }k^o}>*uE^ywogoi r53PLTEV˲Ƹ̼vqszСЧȸmhfmʙjc_jѰ̧h맧Ŷg`]ݧ̼aaap뜖ɯtttx񗖕Ƭ񕔔ĵ```~闓]XV{ס~v𨨨϶YVUÖ픉ZS軼zGȄfcbɼܿ߹Եξz9PՆǯ]Vģzvt{{{߆z9O1t3唉;´܆zލ9J݅zه{ۍ9Jڅz])JօzT9/JӅzI16 І{tRNS@fbKGDH pHYs:|\tIME 1c"uIDAT(c`` ACWPTRCHkhjih"$ML-,4mlN.n6^>~0 PװȨXD\|BbRHpKrJprjZ:L"#>3+;'7/?* ɭ&QRZV^QYU]S[SW `jimkwIL>}Fi3g͞;oO2e˖3$V\zu7lذq-[a>߶}]ݷC'N:}{.\t ,د^~@ݹ{>Năo?!(5ě޽g" $po;ŞvIENDB`THELI-3.1.3/src/icons/open_project.png000066400000000000000000000063251417631501300174710ustar00rootroot00000000000000PNG  IHDR00W IDATxYypUνo{$ !$aq@J(X-P-N m#FnLǽJ+8VűUh@E `$H$!!YrY{/ 8,3}=~ c)!0f>h߱ 5goސC"p۰H<~ K q#ME/|pqXr O?ri sm|4CK}%nn(^0h{;?E[LкŧwͼŗNdTƻPY`:gcu8+G8ql7"+s7}bb 1w.,Ӈ*k7(G 7R~/gFteb6j0r3 QkÍWtff`ˌ>,ĶǾång4b{GΕə9;xi_ Th[ >_66" t"s|6ԴWv|w< cD: /=*Dw>~rةMU[^XMȕrgc;?\Fo̟4gبwt\#Q{Z+4Vvɰ~mh@1A%ٞS5.=1??WM_ɽwyTGˏ)%G1/\X05U_|G!_N +02pu.~Ov_$$6LS,uPT*\8{VLyض=v@~A5&}><7ƻڂ Wbh%xOvOh7f^[XQmP8?jZ+ ΋~PvEajF!--MMN'Xx4&%%06^p֮\֕KylA~g iB\gۍK. D'R6 }B#%L HOzG@F-[1aXғ] 97$p'(De0m A!DܸdiXA!=;4G(&.%2ET;{Dleak10c'ϞWw%"3>Lxi"Xcݣs%1"X:w]:wi{(y yL`Aܓ{;{Ƕm|bt#_E߻ܩ'=hBJ>n3iBiuK'6/ȉq+ A1X|q*vꚵSy6 dGfYhkӝr"A[y?ޡ6lqiQ9F9' k NLb(&c(hŌ'Cdt. S) #mͱpbDbnʼ& Υ$!&hb-$`䝎\屘A@+՗`IC)>=yr-)ײa1|~*"0Q ]2v;F^t ɺ]$$(jAW^w x~iM%5A=F˒D]5UAz'K@qIX,7_Hf WLyu7Ž5D Ef x Q92xb$$)EV:!QsJp'=e6ޡb,j&w&w 22*v$Rҽe tϤ'%-Ao@RHUQaq$@s:)iYe:G$Aj?};J'/ &֫B ȮŖ-;X\,ZaK6:V2Emcl}l+sO|R[ԏR^OFS]e(խD>v^ZA,:⮊&2-&<@ZB*$-J|.w1!!"У_AlEK' =oYvn>eJ KsԪdL^F,Xr8 g$`5ĕPəxCg:En9flƿDx+Q4-yEql)Xgd qUezr([T?i}e,&)Mr:ϕyJw1 m#e?H%s?t+v murVk҅Oe6LI D!6<)s'_zěPCk L% L@{a-YDO i--Ihd2dS&{(|S7:4Y?uJH *KIB?BvXG OuX ۵-¤0I 6u 9wҴ+>)!("MyzR&Дq -!% J˅&-oxgI/pփo߼Heٰ_##=_PxO,õm(dw50h x`s$cD{ucy%gHx@y-j;?aK:{Nۧ Fs4cyY3])R̻. /T:Ωy]6[ꏶo\V~kwF3J)`z>iksM@g:R X6 <pa2G^DBwLJa.6<"ڞu{^pe'  ϡ3 >yC@2d$iXP;gjB~G3=3?AA4 "3|aa `PJ N:v3eh;u*(.-PeS\:SAE%{{[-ANϹKN#{;Y{^- <6:5IّN FP#œs >h CCȡB4㐷V5yB{g'tzlmm;soENmI'=zez??ؑ,<6Q~Ʊw׿w(炽A8u4tuuސTED@:7N:_ܝsO(Hj Ak6y>B N=BZPYӻY>'Co>w L܍O?p/u'E$|ĭ_fH0c j 0F)QBkk+{r>D@[[ aLL #F4SY ?|ٞ-lOS˷Z튕e(zo828q@"u:+UXIXg, Ϝh=k@wWRU@fz6;o턝EwW]3"EA)C~ӟĉ`nA@(גc96Eܢp miiӧT:e>|HY_-/()o^dt]0H4 ΁^)ZIʒ]V\z Ϝ= *~y3%P?j-&O>`Jjr-w3g|!;JP.56/^]v@3;;Rk+xzB=\+ĬY8zfv\6)(v$jYTYy*{!%%u)aovI@]}Y!qr2\vMJ&W]k>qwMN;EFQI3j K<Z7g ʪ0?^AP.@A*7oz[Qw ߍ47'Lii3!&vYWt<Rn&E@R+H+5@$'Qh ^~A -Ԕ)n מ:~_Pyœ\34x`e.U_vU4*a޼@k:g? {e1Ϳs/)˜naȐ! ??"-C ~岗<\ 5iva.AbJ!J79(kؿ`vyMrCbjj*կ=w ^< 996#]&x+)I +Q[\MTCuM̓٪wf>Cq|ϥK(9~99P?W@ff+PH_E RY0PVc]m ɓQO4WЭΝ'{Wq*13%,F)>[`ɲeV23A{ %{ />d &r`ҤDߦs!kB3Ύ"2֛o_A>c!3# fHC,TMPZV酧<|C}k L0T9/ժ:H ƍ'SnN.Zd %utehjd"cv2~"<Z3} Y}}-p:#JȺMGGiu cv !d9FRPL1:@bҗBuu5rΙKt IoDL-X7uܠ|ot4֢}=Du&a, tt󖏠lkW?$IdLںZܳ0,IX'ҹ@H-|V!Pp7nj+.3.\-j},/ Bd. (3HEQF1ǏǥK0jb`.UT7:-nUW_ E6yKyg?9źkM2GGn1qD\f/j$@Y`,w-\{bc%mEi0 : ]rt I_$7|ߏvuX,Ȕ+u=J,UX0lTŪ۬Sᕶ+b!0iK(E& t+Ɵ?KcQq[uANix5-PRZLȖ}!~@;›BEPvϿnt%B>4\-.)LiF= 02mفǎNtZޥ=җN&F C-*\}͔2nkB `]/q1P_`6;pFh ۑ{x/yz8pDO=+ &'?r:֑^v+i 0 O' ٽA4QL*Au_Y?J_ 9!u᭍N b $-A*^((@#BÇ6l FP3zE9 po8?wr!-kop ĶH ]]o+.IENDB`THELI-3.1.3/src/icons/pipette.png000066400000000000000000000035221417631501300164500ustar00rootroot00000000000000PNG  IHDR D cHRMz&u0`:pQ<PLTEЮzҥ`֨`ͤeʬʟ]dytўOɟ^l|uymzvɠ^εΝSТ[ĤЧhjϮzѹΟUwxȘOڪb}t˩sd}Ρ[gzѤ`mzv̠Zgŝ\nvʣƝ\mͤǞ]șOģΞSɣҡ숬ӻ˱ϡꦺו鈬ikbKGD pHYs+tIME\8RtEXtRaw profile type exif exif 22 45786966000049492a00080000000000000000000000 A9zTXtRaw profile type xmp8UA sk{]O$ojXh$HWלpE]J6bnh"{\.]4,Q!ko5i͹7݋ p:vɸzոZ"9j#R Z}0y+BrJN4X@T0_(Ji*c^= m8ntq/|'dA"j/I^u坱1%`D^}g"| @Fg}BL1̂X*BlJTy[NaX%T* OiV!{6==ˀ$8\K8yhn^.9Fe'v0FJt5e&#:(G 2[ `iTQoFdM'QQ=??a+7'Y9R{ͱEDѢ)K7`U:AρyH<ѿFt~pUˇbov&M@|0isD@p: k#_'=EwNHS'%r#Okw4qIDAT8c``ddd 8$RyxJ32KHHJ rb(`+((J p0`PVVVQUSWPD7AZDK[GW,Tdž@"//nƊj=H^]N}G'g kW7w(73O/o _?w{ A!>a~nv@yapd Q1q>a& I)>i:xB͋ 0 |~~NrAUaD|~vRq4Y%NJ` ̄r }fPG {]M ~P8DVy6u x[pRمS/1`+'L4#k vy֩ӦwϨUb mͳ`ŌlnmbU?#՜n~%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/qt5_logo.png000066400000000000000000000013571417631501300165330ustar00rootroot00000000000000PNG  IHDR@+~ugAMA a cHRMz&u0`:pQ<QPLTEARVeL\p|樇ߒ{܇Xgp}L\drdq㞕|܈ IpbKGDH oFFs  pHYs~tIME  (4J vpAg3nE%$\IDATHŕz SΠ"qcW$A7 bO  1~FJl頽.j۔K,-XoILgAMA a cHRMz&u0`:pQ<PLTEXXmE_tRNS@fbKGDa pHYs+tIME\8]IDATc`(`dR62L\\ Lg (Ġbb(ի A Lpf @3T Dd013Y;!K 㽗%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/satellite-icon.png000066400000000000000000000110161417631501300177070ustar00rootroot00000000000000PNG  IHDR szz zTXtRaw profile type exifxڭWrDY\,6-Nl#sUD a*m?K)Y~b7n~=?~)p ׿iz!ǻl7y{c3l^=PW7^RKo۹KvuWG`La_{k.sm: G>5~o?; 5c[Sv'D}E?gV?o{׵!\c+玎p^H|2}>ʧfMFguy"]t5:K~VBՏh>P $s-[u>&+<=c001@{kl+_,Cӿʉ3~Q` sak.ŭppV ]y@[X `v}v8i܇;81'My'׋B`(1o 5#A$RJKTRNS-s.VBEJ*RKdLLM5RkmI[lh辇s/6ψCFyQG~feٖ[Pi%+ʪmÎ[vy]w{v5wP/P9ND3сxV Wlq1zEN1xV) tlq3DOq!gQސ7v64 ) H?|iը+Xk%ͥ""]ˍZ%qkaFmWXRTi^1֩s( K1>`3c% Fr6?,s.10Wwpnd'මqIT=N (";@;t^M9CQI%֓aLn23 vաw3+(1F"-=2\ס@tQ`R+u.j]E!Jln;7A.~A`M# h.:t>3 6]ٗ)ē4֔C2-tgU9ݑG4uCy^arJoz5ˊFLv.۠UM8䝨u{)%͂lu8 F3[zl!!Z86'+z VĸY)Xh%l" r$CM=R(FU&r-zdMG9rVf̜\I#?KXpc(31ZqS "Q6/nj¾Wj-6AcvTcGԔD}T4c=MT[MVNݠpRy܎ ABp Ij#JaR&(!ׄжI4I O5G?%*RK] ;\I8:,CiuQQY= 5 +1][s[wTC\WD91\(A:.2^ -P5, LMT? |3^yM~~'er*8ðF2>*Z:ۘ ﹷX)Q✅*uHRA:DJXY/N'KfLҜE DnN Ik9|H8`Vʃ~"ʐZ`I_ .R'C"a8*\*ڃ0Q/Š@sj\(?݇uDc"JG5@Ia|!˓>~ 8jЊ7gL* ]JGwM_ fpAюZWUƺ2KxPUY6=NH*TGcJ TU:N!ND2d̘ FgSXYt~'ct U{m藇D=-6Xl#r?#'`'!XO`,>Cx0JǟCv^@\ӍNJ/Tck׆\&U,R}1t,|->饓!Ok fx Sҍ,2 s0%uC80aF&YNơ ,0:Eq<;lЄJ` f`S^:{).AOGv{`Y•N.Z\lwe EE$Uc#CwH!tnoD:Bx)a /G"2!^8I[9t=J.dEqWbv7̖ D[}dmvIXӓ0V.!K[k;f);3p,0DS+ $.t7C.l"+Ȅi!1m(Kx X_{ uB.lVpqMEh-\IENDB`THELI-3.1.3/src/icons/settings-icon.png000066400000000000000000000056521417631501300175720ustar00rootroot00000000000000PNG  IHDR00W qIDATxYiT_= `iĀɏT4USIJ";ɌCPamط0 1?bi*ZI~XhD-T`zzߜz{gTy{rs=;1?o;=/.YfێDԷek[6l\ZRT "b5lFK͏_ g ~mc(L,^xM2 ݜ[U"e*xl9hb/y=#4]G(Ω~;c8,/ Hi6B[4W_)KzDC- nq!ΨD#˭m Rr4x\aSneh'Ć>{ +yk\2O KCTDa<[e->O}z$rnxQaLcqK -mpT&"by'K}3&%)kag(D:Qr\35t]ɲ|5''dǤ}{IK @́3%Wܹިa$gu ?3vke[Llweɡ`;bQ56g `D`.PiĂbc8U6X[б[`;`)XUDIXt3('9 {*R3A_U6^  $P,$B0uK09E:oYZq 'ZDY@8aMf\@;P$Qհ,?EQܲqIM#\qYM2&.Am  ᐟQoO4ejY(E-Xxv"˂aH$>vsWFGM%'J'*T'Zi`5:̲)\lۉ%YðlzǵXbPZ9=y,rJ^ᮆ˧/4e iz Qpd.-Q0d: i㜬,o-)y1wHW䰼(8SħK<+l !ʩYszcL)(;5ZڻrNff[KEӲ)pk~k;Nb J1k$;a"zꅿlƬ`Xn^eB3tp"(G䐿ziFt[ץp0XAiff+m[ܲgLF`s )eOar'Bt<¡P;OP"[[8}')n 1P xIdcS3d J,o,,}y>܍8E.\lPq[OĒ߇|r!;J*N-ہfڹ<{*ѽͭ; uq2KoP#]u#:up i{b>HD3]"o>ހ$ٽQ^G#V?ca?^Ox {DɫvzKa21B@B-\͂+=Xrԯ?8~p~;rNޏjvNP@Um{9[i(Q9> Z z!hqDi$Nĉx:睱; ]P\ӻkKnQtO>&pO] @]WZJ$Ym$eqğ' ufTpIJbOSs#\9C$cH07R3ꙕS;IN5c };tD!IENDB`THELI-3.1.3/src/icons/sigma.png000066400000000000000000000005771417631501300161050ustar00rootroot00000000000000PNG  IHDR V%(gAMA a cHRMz&u0`:pQ<bKGD̿ pHYs+tIME\8rIDAT8˽Q0C !sچ lK}RjVXypqsöxG&tM/5  8cdplg`S` dQ˘ iƘvߘ y WPGY)To &4(sN9knQK)N5\K^GZnZoΐL[} ,:\f<̳:s,J+j!QX $E424(LIf-Zia5cKXfƝՏ}f~kM\Nsb `:0-9葉9G2;9104l݃/y#W̑Sȩ{bW^&c-o )AKl#c-QTM6;kZyDbn1C㬶UAŰ[-FK*gicV@$eauM5 &Gu3k6\Da5?\ϼ2=3ϰ6iK8@`9MaN5 g{e\H`TevͰ#3V߇!g)/oXi%uz{,d +q 302:!>aN˱ w*лEuU8Z:#[a<E]U7bVU栽)&{c_M|p8.k^ T& Pq>Q2a~lT؂6&gKf јnfŰ:~~pi8qS#V`L Br?c%Ip:-{aG ?t|#~A1`GNWpOQa[QRK[ ;;H~G\赺ku{qB9={=Ud^f̢ja 0%1vcI\WE8(Ҡڣz %e2 6e|gw2E__}SK_}V/zV+TlkBISPVJ[\U^TlԡZfi?bTI(ؗgN;cQO{4dfۮls 2iCCPdefault_rgb.iccxgPY<@BPC*%Z(ҫ@PEl+4EE\"kE t,ʺqQAYp?{ossp e{bRɎ(tջ{i常r)teJOYLgWX\2XyKο,]~ )sT8بlOrTzV $G&D~SGfDnr&AltL:5204_gK!FgE_zs zt@WOm|:3z @(U t08|A $`(E`8@-hM<.L@ށA2@F 7 Bh( ʀrPT UAuP t݄84 }aXև0v}p4 ^O6< "@]p$BV)GVC!Bd h(&JerFTVT1 uՁECDh2Z@Ёht]nDѓw aa0Θ Lf3sӆL`X VkaӱJI%vG)p`\.Wk] p xq:o—;IA"X| q B+aH$͉^XvbqD%iRi/82! L ے&US{1O,BlXXؐ+ NP6Pr(3;Yq8WJ)Hq"HJ IKIJGJJIKa8y"Ֆ͒="{MvV.g)Ǘ+;-Hז,L_~NAQI!ER¬"CV1NLMZ)VL $L`V0{"eyeg :JJU*[5JLGU殖֢HVQ?ާ>حѩ1͒fX9֘&YF3U^FuX6m]}G1Չ93 |UҪU$]nnCM/OS~~>&   .y݆i񍪍&v\mu:ƑGLMv|253Θ՘lOv19|y-Եl^Zä́UUКij}ZhlfSoV6¶vʼn伲3صs-[{'BCSGhGfhgWΣ<lqu%V>svu.֪MZ26,b&*4r**4j:*@LMLyl,7*us\m|GD\bh$jR|Robrv`NJA0"`H*hL֧uӗ? ͌]֙ՙdKd'eo޴gTcOQ{rswol m ڳMu[NO [A^i۝;OrR V (m? Yrˆ[EEE[?Xި%%Ga%oDDiNe̲²7Yn\^{p(㐰­Rr_bULp]u[|͞iU-x4:zccǞ77Q'z̚KZ!'lsWnk]8q/v=s}ٚvZ{aԱC) _}ABEKr.]N<{%DƞWzuW8}nX8[[Mowf[@;]wv8d3tyoy02*|`a׏2-<>+|"ߵ~o /ۏ?yx??'󟓟O)M5MMqb݋ɗ)/f 櫳/ M^̛oy=}na>|ZZ.V|R?B,%Q 2iCCPdefault_rgb.iccHgPY<@BPC*%Z(ҫ@PEl+4EE\"kE t,ʺqQAYp?{ossp e{bRɎ(tջ{i常r)teJOYLgWX\2XyKο,]~ )sT8بlOrTzV $G&D~SGfDnr&AltL:5204_gK!FgE_zs zt@WOm|:3z @(U t08|A $`(E`8@-hM<.L@ށA2@F 7 Bh( ʀrPT UAuP t݄84 }aXև0v}p4 ^O6< "@]p$BV)GVC!Bd h(&JerFTVT1 uՁECDh2Z@Ёht]nDѓw aa0Θ Lf3sӆL`X VkaӱJI%vG)p`\.Wk] p xq:o—;IA"X| q B+aH$͉^XvbqD%iRi/82! L ے&US{1O,BlXXؐ+ NP6Pr(3;Yq8WJ)Hq"HJ IKIJGJJIKa8y"Ֆ͒="{MvV.g)Ǘ+;-Hז,L_~NAQI!ER¬"CV1NLMZ)VL $L`V0{"eyeg :JJU*[5JLGU殖֢HVQ?ާ>حѩ1͒fX9֘&YF3U^FuX6m]}G1Չ93 |UҪU$]nnCM/OS~~>&   .y݆i񍪍&v\mu:ƑGLMv|253Θ՘lOv19|y-Եl^Zä́UUКij}ZhlfSoV6¶vʼn伲3صs-[{'BCSGhGfhgWΣ<lqu%V>svu.֪MZ26,b&*4r**4j:*@LMLyl,7*us\m|GD\bh$jR|Robrv`NJA0"`H*hL֧uӗ? ͌]֙ՙdKd'eo޴gTcOQ{rswol m ڳMu[NO [A^i۝;OrR V (m? Yrˆ[EEE[?Xި%%Ga%oDDiNe̲²7Yn\^{p(㐰­Rr_bULp]u[|͞iU-x4:zccǞ77Q'z̚KZ!'lsWnk]8q/v=s}ٚvZ{aԱC) _}ABEKr.]N<{%DƞWzuW8}nX8[[Mowf[@;]wv8d3tyoy02*|`a׏2-<>+|"ߵ~o /ۏ?yx??'󟓟O)M5MMqb݋ɗ)/f 櫳/ M^̛oy=}na>|ZZ.V|R?B, bKGD pHYs N Nw#tIME "AIDATHcd%`a``X&;S O 8,SitD&ҥ`ԂQ F-,D)b.џ O3ϰɎiAPFD9#-S iL'tF~,<a-MG-0Һu '4IENDB`THELI-3.1.3/src/icons/star_icon.png000066400000000000000000000100371417631501300167560ustar00rootroot00000000000000PNG  IHDR  zTXtRaw profile type exifxڭi*^`9z ;#^yi1 ݫ+K%ל/>rݟtOxq߽"xo x)Dσ lgD1wRy~y|}O30_ .u{h?۹6~>ڌ<=u?px;_{>ȇ{ϲk);ܕL9-vkzo5@mbjwWO~_:`)\C``}%jaD .8A$rڋ?V[ +Ovk~?M|žmrQS9\_?lA9n.خ~Oſs+%|&E-lG⳿4?i<:xq& ) JyG$ @HQX)I[BI$"YTTi9%tiԤYUVmhX*RrRJ-1q5WԘ1C=uk/6HCF:ʨ0DSguTZiKWYu vi[wujQܯQje5Uߦ&'bXH0O)rUCt1J`bLo`Z>/ޑ)n)nG9@tPm<YS2~ XbFJ}z_ ,s܆}5 mpjMf}4sFd_PJC&Yi5A4, vO``0F[l)}UH&>be]<ɲ{k͕i>F/P'XX55xmug܉(8Xݢ#I"ei<CͶHjZ^~e So hOUd~@~k|w ӰJ@[UPIJCTPŤVLHŘٍ3|l:{%`qUKښԍ&nojj[|=}LQy]~uwŴYu*TEf+b7)}:@W^CnU<ް09b Ds!Z-5 2-ktpjpBƮɊLǀ#9"Mm0and|v{p멵yL9f) = C'$[K/D4?b[ t;۴Pk!eѲz* č_9ǀD#g6\eWprwFiR8c.pשR(`.Tv3IHInsN1#3Rr}L\)f<*M܏u`&mh<*ՏKrR>qp❬wыvuiCCPICC profilex}=H@_S*"v␡:Yq*BZu0 4$).kŪ "%/)=B4ctL%b&*vB@(3˘$|=|,s>5g1 2ô77m>qex̤ ?r]segtj8L,XicV45)⨪/dF]QscigJo+u`ZKuKS`ɐMٕ4|x?o@[s@Jh}ۿgCr8BbKGD pHYs+tIME PIDATHǵV]LTG>g.-+] VMieѵJ*TAAJ4}iZ1?TLhڂ)XZYO(م;s0p]"=NsΜφ "Z^T&!|f ?8RJ9!"1u5IacLvڅ  8&&&^}>#%zc󚚚FϗȄJ'iФ f'NpXJ)`”₌_ڂ|%$II,(,,u]oܸvH"}Quݧ{q (Q<ɺwuu-_J6<<DIyyydEr(Zzu(jii|riiiNNN8...zHp~P.cѓQݱ-7"8,.SuR榦Ύ@ P[[v t]gI)UB6xS/./q`2IR188Kb%$l}_(lRk:;j5gzH*z*jFhA\q܏'咢l%vDikm9\whÒkbhlM4={ l 9&.p!aǎ=^_kmJRHFB F&bt'vlU~˥e),Kęql5s0Gә87 Dq]=sOmZxQq9Ijן6ߨx"ߓ 4@,hoj,dĐ?82=;<B;cLK])5YZVu}P?nOޝzf;vDBpS"zSĬji #g& !}2\4MS,w6[YҥKp4M!Dooo0TuHO{Vo2n,,ze j'Onr=Hrt(gF@U;?g>d>pfcIIIVםF x,rssU2rUzl{M 5[A2;;HN|.,//boVVzOOX^[9#}*{tLmq]""JMh/^)R!rh\22N%i9 L0Kd3o^~ֈii*yy61&yH!C Ba^w4}BHD0MmNL࿿ZAru.IENDB`THELI-3.1.3/src/icons/upload.png000066400000000000000000000027371417631501300162710ustar00rootroot00000000000000PNG  IHDR DgAMA a cHRMz&u0`:pQ<PLTE====>>>ABBGFFGGFFG;"K#K#K"K#L#L(P(O)P)O(O.T.U.U.T-U-T3Z3Y4Y3Z4Z4Z3Y:^9]:^9^9^:]:]?b?c@c?c?b@bEgDhEhDgJlKlJlKlPqQqPpQpQpQqPqVuVuVvWv[z\z\z\{bab~ba~aggghhghmmmnsssrrrsyxxyxyxy~~~,NsbKGDg( pHYs.#.#x?vtIME  ~!IDAT8u[Q'ȴU@0bb -"EӂԠLԢ|Ce %"++BjlswΜp:(,)P  PZVV;7xxo\$$DUGDHDX\%,'*EiL^S}T.KeRVL&ǒUKkdS]}B98(cuqTjyTr9jTj$UpJC5Pr$)JӨi4g@՝MZ~VtN{^ zh-GBo0z l2#n銩Zmf_9mfs{;X:,]]ݖkpjް$jYV:> p8vw65zG?~y ghf0b&&bL 2 sht>h.<EXx!x"\|'xaǓ°OTQx++ŁW:&Rt: kkokO0/Ł6!d 6Lv+[Xxc˱<c?, o$袡dtEXtCommentCreated with GIMPW%tEXtdate:create2019-05-10T15:12:05+02:00TB%tEXtdate:modify2019-05-10T15:09:18+02:005IENDB`THELI-3.1.3/src/icons/wcs.png000066400000000000000000000010121417631501300155620ustar00rootroot00000000000000PNG  IHDR DgAMA a cHRMz%u0`:o_F3PLTER ]]HHޭȬй00y ooƮ6bKGDH pHYs  tIME  9 IDAT8͓K D 㘁C4]DjT OcD,#1.H+sȉgɳP"# Ș*}+PgT4T3E5oR9!!#5pWP1>Zv*օ]VLjԊv`F[-o-A9 Yc}TMw9ਲ਼{ }M%tEXtdate:create2019-12-18T01:09:27-03:00S%tEXtdate:modify2019-12-18T01:09:27-03:00"KGIENDB`THELI-3.1.3/src/icons/xtalk_col_1x2.png000066400000000000000000000005201417631501300174430ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEaXXX}bKGD-tIME\8>IDAT8c`Ĩh!IB3v aC&..ΤI4 帝K0"K{`<%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_col_2x1.png000066400000000000000000000005271417631501300174520ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEaXXX}bKGD-tIME\8EIDAT8c`A@@PPII  WB3v aC&..ΤI4 帝K U Rr%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_col_2x2.png000066400000000000000000000005551417631501300174540ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEaXXX}bKGDH pHYsGJitIME\8FIDAT8c`A@@PPII @M>$I(0q.!bUř4 Fsi|OT%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_nor_1x2.png000066400000000000000000000005431417631501300174710ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEXXXa[rbKGD-tIME\8QIDAT8c`!!CB"V ecc#$prΥVH('B..X%T\\HiN.]EQ%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_nor_2x1.png000066400000000000000000000005401417631501300174660ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEXXXa8D bKGD-tIME\8NIDAT8c`@ WBH!,lrQDH+$T\FP !8i9nR+Hp-Fˏ_@%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_nor_2x2.png000066400000000000000000000005771417631501300175010ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEXXXa[rbKGD-tIME\8mIDAT8c`@B %d e#"BBJ(!$<"8i9nR+HFS u$pF\5]($PT5iN.]Iy%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_row_1x2.png000066400000000000000000000005271417631501300175040ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEaXXX}bKGD-tIME\8EIDAT8c`Q ,LJXKɇ$ aCl4q..FX%L\\Iiq:A JyTKVq%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_row_2x1.png000066400000000000000000000005531417631501300175030ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEXXXa[rbKGDH pHYsGJitIME\8DIDAT8c`@ WBH1#HEi8a9NR1HpSl9%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/icons/xtalk_row_2x2.png000066400000000000000000000005361417631501300175050ustar00rootroot00000000000000PNG  IHDR// gAMA a cHRMz&u0`:pQ<PLTEaXXX}bKGD-tIME\8LIDAT8c`@" Kɇ$ aCl4q..FX%L\\Iiq:A zTvQl%tEXtdate:create2019-02-17T22:00:27+01:00d%tEXtdate:modify2019-02-17T22:00:27+01:00IENDB`THELI-3.1.3/src/imagestatistics/000077500000000000000000000000001417631501300163505ustar00rootroot00000000000000THELI-3.1.3/src/imagestatistics/imagestatistics.cc000066400000000000000000000500421417631501300220550ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagestatistics.h" #include "ui_imagestatistics.h" #include "../instrumentdata.h" #include "../functions.h" #include "../qcustomplot.h" #include "../iview/iview.h" #include "../myimage/myimage.h" #include "../processingStatus/processingStatus.h" #include #include #include #include #include #include #include // ImageStatistics::ImageStatistics(QVector> &imlist, const QString main, const QString sciencedir, // const instrumentDataType *instrumentData, QWidget *parent): ImageStatistics::ImageStatistics(QList &datalist, const QString main, const QString sciencedirname, const instrumentDataType *instrumentData, QWidget *parent): QMainWindow(parent), mainDir(main), instData(instrumentData), dataList(datalist), ui(new Ui::ImageStatistics) { ui->setupUi(this); initEnvironment(thelidir, userdir); makeConnections(); QStringList dirnameList; for (auto &it : dataList) { dirnameList.append(it->subDirName); } ui->scienceComboBox->insertItems(0, dirnameList); scienceDirName = mainDir + "/" + sciencedirname; scienceDir.setPath(scienceDirName); ui->scienceComboBox->setCurrentText(sciencedirname); scienceData = getData(dataList, sciencedirname); // dataList corresponds to DT_SCIENCE in the Controller class scienceData->populateExposureList(); myExposureList = scienceData->exposureList; // if (!myExposureList[instData->validChip]->isEmpty()) statusString = myExposureList[instData->validChip]. // else statusString = ""; // ui->filterLineEdit->setText("*_1"+statusString+".fits"); ui->statPlot->setMultiSelectModifier(Qt::ControlModifier); // ui->statPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); ui->statPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iMultiSelect); setWindowIcon(QIcon(":/icons/sigma.png")); init(); } void ImageStatistics::init() { allMyImages.clear(); for (int k=0; knumChips; ++chip) { if (instData->badChips.contains(chip)) continue; auto &it = myExposureList[k][chip]; it->loadHeader(); // if not yet in memory it->getMode(true); allMyImages.append(it); } } processingStatus = new ProcessingStatus(scienceDirName); processingStatus->readFromDrive(); statusString = processingStatus->statusString; ui->statPlot->plotLayout()->clear(); // Plot data right away on_statisticsPushButton_clicked(); } ImageStatistics::~ImageStatistics() { delete processingStatus; processingStatus = nullptr; delete ui; } // cloned from Controller class Data* ImageStatistics::getData(QList DT_x, QString dirName) { for (auto &it : DT_x) { if (QDir::cleanPath(it->dirName) == QDir::cleanPath(mainDir + "/" + dirName)) { // check if it contains mastercalib data it->checkPresenceOfMasterCalibs(); return it; } } return nullptr; } void ImageStatistics::makeConnections() { numericThresholdList << ui->skyMinLineEdit << ui->skyMaxLineEdit << ui->airmassMinLineEdit << ui->airmassMaxLineEdit << ui->seeingMinLineEdit << ui->seeingMaxLineEdit << ui->rzpMinLineEdit << ui->rzpMaxLineEdit << ui->ellMinLineEdit << ui->ellMaxLineEdit << ui->imageMinLineEdit << ui->imageMaxLineEdit; // For a mouse-click in the plot connect(ui->statPlot, &QCustomPlot::plottableClick, this, &ImageStatistics::dataPointClicked); connect(ui->chipsLineEdit, &QLineEdit::editingFinished, this, &ImageStatistics::plot); // Validators connect(ui->raLineEdit, &QLineEdit::textChanged, this, &ImageStatistics::validate); connect(ui->decLineEdit, &QLineEdit::textChanged, this, &ImageStatistics::validate); for (auto &it : numericThresholdList) { connect(it, &QLineEdit::textChanged, this, &ImageStatistics::validate); connect(it, &QLineEdit::editingFinished, this, &ImageStatistics::numericSelection); } // Connections for iView can only be made when iView is instantiated further below. } void ImageStatistics::clearAll() { // if (numObj == 0) return; clearData(); clearSelection(); badStatsList.clear(); ui->statPlot->clearItems(); ui->statPlot->clearGraphs(); ui->statPlot->plotLayout()->clear(); plot(); ui->statPlot->replot(); numObj = 0; statisticsDataDisplayed = false; } // clicking on "update images" void ImageStatistics::on_statisticsPushButton_clicked() { if (!scienceDir.exists()) { QMessageBox::warning( this, "Bad selection", "The selected directory does not exist.\n"); return; } QString chips = ui->chipsLineEdit->text(); // Could be any text, but we just make it a list of detector IDs chips = chips.replace(',', ' ').simplified(); QStringList chipList = chips.split(' '); QVector chipID; if (!chips.isEmpty()) { for (auto &it : chipList) { // instData = instrumentData; chipID.append(it.toInt()); } } filteredImageList.clear(); filteredMyImages.clear(); // Filter for sky coordinates QString ra = ui->raLineEdit->text(); QString dec = ui->decLineEdit->text(); for (int k=0; kchipName; filteredMyImages << allMyImages[k]; } } numObj = filteredImageList.size(); if (numObj == 0) { QMessageBox::warning( this, "No images found", "No images found, check chip filter or sky coordinates if provided.\n"); ui->statisticsPushButton->setEnabled(true); ui->statisticsPushButton->setText("Get statistics ..."); return; } readStatisticsData(); plot(); // Push the filtered list of images to iView if (iViewOpen) { iView->myImageList = filteredMyImages; iView->numImages = numObj; iView->clearAll(); } } bool ImageStatistics::isImageSelected(MyImage *myImage, const QString &ra, const QString &dec, const QVector &chipID) { // RA / DEC filtering if (!ra.isEmpty() && !dec.isEmpty()) { if (!myImage->containsRaDec(ra,dec)) return false; } if (chipID.isEmpty()) return true; // Chip filtering bool correctChip = false; for (auto &chip : chipID) { if (chip == myImage->chipNumber) correctChip = true; } if (correctChip) return true; else return false; } void ImageStatistics::makeListOfBadImages() { // check for bad data on drive QDir badStatsDir(scienceDirName+"/inactive/badStatistics/"); if (badStatsList.isEmpty()) { QStringList filter; filter << "*.fits"; badStatsList = badStatsDir.entryList(filter); } // check for bad data in memory (should always be the same as on drive, but nonetheless) for (int k=0; kactiveState == MyImage::BADSTATS) badStatsList << it->chipName; } filteredImageList.removeDuplicates(); } void ImageStatistics::readStatisticsData() { // Must flag bad images makeListOfBadImages(); clearData(); // Compile the statistics data numObj = 0; // check for bad data in memory (should always be the same as on drive, but nonetheless) for (auto &it : allMyImages) { // for (auto &it : myExposureList[chip]) { // skip bad images if (it->activeState != MyImage::ACTIVE) continue; if (badStatsList.contains(it->chipName)) continue; // only include images that match the sky coordinate filter // (always true if no sky coords given) if (!filteredImageList.contains(it->chipName)) continue; dataName.append(it->chipName); dataImageNr.append(numObj+1); // Default values and flags if data not available // Background if (it->skyValue == 0.0) { // poor default of -1e9 in myimage.h skyData = false; dataSky.append(0.0); } else dataSky.append(it->skyValue); // In case GUI is launched, catalogs are present, and statistics is requested, // we need to fetch the data from the catalogs (or the MyImages) if (it->fwhm == -1.0 || it->ellipticity == -1.0) { if (it->objectList.length() > 0) it->calcMedianSeeingEllipticity(); else { QString catName = it->path+"/cat/"+it->rootName+".scamp"; QFile cat; cat.setFileName(catName); if (cat.exists()) { it->calcMedianSeeingEllipticitySex(catName, 2*it->chipNumber + 1); // LDAC_OBJECTS table in extensions 3, 5, 7, etc } } } // Do we have GAIA seeing? we should have, at least if catalogs exist if (it->fwhm == -1.0) { // No. Do we have median estimate? if (it->fwhm_est == -1.0) { // No seeingData = false; dataFWHM.append(0.0); } else { dataFWHM.append(it->fwhm_est); seeingFromGaia = false; } } else { dataFWHM.append(it->fwhm); seeingFromGaia = true; } // Do we have GAIA ellipticity? if (it->ellipticity == -1.0) { // No. Do we have median estimate? if (it->ellipticity_est == -1.0) { // No ellipticityData = false; dataEllipticity.append(-0.1); } else { dataEllipticity.append(it->ellipticity_est); seeingFromGaia = false; } } else { dataEllipticity.append(it->ellipticity); seeingFromGaia = true; } // Airmass if (it->airmass == 0.0) { airmassData = false; dataAirmass.append(2.5); } else dataAirmass.append(it->airmass); // Relative zeropoint if (it->RZP == -1.0) { rzpData = false; dataRZP.append(-0.5); } else dataRZP.append(it->RZP); ++numObj; } } void ImageStatistics::clearData() { dataName.clear(); dataImageNr.clear(); dataSky.clear(); dataFWHM.clear(); dataRZP.clear(); dataAirmass.clear(); dataEllipticity.clear(); numObj = 0; } void ImageStatistics::on_exportPushButton_clicked() { if (numObj == 0) return; if (!scienceDir.exists()) return; QString chips = ui->chipsLineEdit->text(); // Could be any text, but we just make it a list of detector IDs chips = chips.replace(',', ' ').simplified(); chips = chips.replace(' ', '_'); QString chipString = ""; if (!chips.isEmpty()) chipString = "_chip_"+chips; QString name = "statistics"+chipString+".png"; QString saveFileName = QFileDialog::getSaveFileName(this, tr("Save .png Image"), scienceDirName+"/"+name, tr("Graphics file (*.png)")); if ( saveFileName.isEmpty() ) return; QFileInfo graphicsInfo(saveFileName); if (graphicsInfo.suffix() != "png") { QMessageBox::information(this, tr("Invalid graphics type"), tr("Only .png format is currently allowed."), QMessageBox::Ok); return; } else { ui->statPlot->savePng(saveFileName,0,0,1.25); } } // "Clicking on "display images" void ImageStatistics::on_showPushButton_clicked() { if (!scienceDir.exists()) return; if (!ui->showPushButton->isChecked() && iViewOpen) { iView->close(); iViewOpen = false; return; } if (ui->showPushButton->isChecked() && !iViewOpen) { if (!imgSelected && !statisticsDataDisplayed) { iView = new IView("FITSmonochrome", scienceDirName, "*.fits", this); connect(this, &ImageStatistics::imageSelected, iView, &IView::loadFITSexternalRAM); connect(iView, &IView::destroyed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::closed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::iviewNewImageShownReceiver); // iView->clearAll(); } else if (!imgSelected && statisticsDataDisplayed) { // QCPDataRange range(0,1); // selection.addDataRange(range); // imgSelectedName = dataName[0]; // imgSelected = true; imgSelected = false; lastButtonClicked = Qt::LeftButton; // plotSelection(0); // iView = new IView("MEMview", allMyImages, scienceDirName, this); // dirname is needed to overlay catalogs iView = new IView("MEMview", filteredMyImages, scienceDirName, this); // dirname is needed to overlay catalogs connect(this, &ImageStatistics::imageSelected, iView, &IView::loadFITSexternalRAM); connect(iView, &IView::destroyed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::closed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::iviewNewImageShownReceiver); // To be implemented // connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::currentlyDisplayedIndexReceived); iView->scene->clear(); } else { if (lastDataPointClicked != -1) { // iView = new IView("MEMview", allMyImages, scienceDirName, this); // dirname is needed to overlay catalogs iView = new IView("MEMview", filteredMyImages, scienceDirName, this); // dirname is needed to overlay catalogs connect(this, &ImageStatistics::imageSelected, iView, &IView::loadFITSexternalRAM); connect(iView, &IView::destroyed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::closed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::iviewNewImageShownReceiver); // iView->loadFromRAM(allMyImages[lastDataPointClicked], 0); // '0' refers to dataCurrent (compared to backup levels L1-L3) iView->loadFromRAM(filteredMyImages[lastDataPointClicked], 0); // '0' refers to dataCurrent (compared to backup levels L1-L3) iView->currentId = lastDataPointClicked; } } bool sourcecatShown = iView->sourcecatSourcesShown; bool refcatShown = iView->refcatSourcesShown; iView->clearItems(); iView->setCatalogOverlaysExternally(sourcecatShown, refcatShown); iView->redrawSkyCirclesAndCats(); iView->show(); iViewOpen = true; } else if (ui->showPushButton->isChecked() && iViewOpen) { iView->scene->clear(); iViewOpen = false; } } // To be implemented void ImageStatistics::currentlyDisplayedIndexReceived(int currentId) { qDebug() << currentId; // indicate displayed image, e.g. by a ring around the data point } void ImageStatistics::on_ClearPlotPushButton_clicked() { clearAll(); } void ImageStatistics::uncheckIviewPushButton() { if (ui->showPushButton->isChecked()) ui->showPushButton->setChecked(false); iViewOpen = false; } void ImageStatistics::clearSelection() { selection.clear(); imgSelected = false; for (auto &it : numericThresholdList) { it->clear(); } } void ImageStatistics::validate() { QRegExp RA( "[0-9.:]+" ); QRegExp DEC( "^[-]{0,1}[0-9.:]+" ); QRegExp ripos( "^[0-9]+" ); QRegExp rf( "^[-]{0,1}[0-9]*[.]{0,1}[0-9]+" ); QRegExp rfpos( "^[0-9]*[.]{0,1}[0-9]+" ); QRegExp ricommablank( "^[0-9,\\s]+" ); QValidator* validator_int_pos_comma_blank = new QRegExpValidator( ricommablank, this ); QValidator* validator_ra = new QRegExpValidator( RA, this ); QValidator* validator_dec = new QRegExpValidator( DEC, this ); QValidator* validator_float = new QRegExpValidator(rf, this ); QValidator* validator_float_pos = new QRegExpValidator(rfpos, this ); QValidator* validator_int_pos = new QRegExpValidator( ripos, this ); ui->raLineEdit->setValidator(validator_ra); ui->decLineEdit->setValidator(validator_dec); ui->skyMinLineEdit->setValidator(validator_float); ui->skyMaxLineEdit->setValidator(validator_float); ui->airmassMinLineEdit->setValidator(validator_float_pos); ui->airmassMaxLineEdit->setValidator(validator_float_pos); ui->seeingMinLineEdit->setValidator(validator_float_pos); ui->seeingMaxLineEdit->setValidator(validator_float_pos); ui->rzpMinLineEdit->setValidator(validator_float); ui->rzpMaxLineEdit->setValidator(validator_float); ui->ellMinLineEdit->setValidator(validator_float_pos); ui->ellMaxLineEdit->setValidator(validator_float_pos); ui->imageMinLineEdit->setValidator(validator_int_pos); ui->imageMaxLineEdit->setValidator(validator_int_pos); ui->chipsLineEdit->setValidator( validator_int_pos_comma_blank ); } void ImageStatistics::on_readmePushButton_clicked() { imstatsReadme = new ImstatsReadme(this); imstatsReadme->show(); } void ImageStatistics::on_fwhmunitsComboBox_currentIndexChanged(const QString &arg1) { plot(); } void ImageStatistics::on_actionClose_triggered() { close(); } void ImageStatistics::on_scienceComboBox_activated(const QString &arg1) { scienceDirName = mainDir + "/" + arg1; scienceDir.setPath(scienceDirName); scienceData = getData(dataList, arg1); // dataList corresponds to DT_SCIENCE in the Controller class scienceData->populateExposureList(); myExposureList = scienceData->exposureList; init(); } void ImageStatistics::on_chipsLineEdit_editingFinished() { on_statisticsPushButton_clicked(); } void ImageStatistics::on_raLineEdit_editingFinished() { on_statisticsPushButton_clicked(); } void ImageStatistics::on_decLineEdit_editingFinished() { on_statisticsPushButton_clicked(); } void ImageStatistics::activationChangedReceiver() { // has no effect. in readStatisticsData()->makeListofBadImages(), images are recognized as bad even when they are not. scienceData = getData(dataList, ui->scienceComboBox->currentText()); scienceData->populateExposureList(); myExposureList = scienceData->exposureList; allMyImages.clear(); for (int k=0; knumChips; ++chip) { if (instData->badChips.contains(chip)) continue; auto &it = myExposureList[k][chip]; it->loadHeader(); // if not yet in memory it->getMode(true); allMyImages.append(it); } } on_statisticsPushButton_clicked(); } void ImageStatistics::iviewNewImageShownReceiver(int newDataPoint) { lastDataPointClicked = newDataPoint; highlightClickedDataPoint(); } THELI-3.1.3/src/imagestatistics/imagestatistics.h000066400000000000000000000126471417631501300217300ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IMAGESTATISTICS_H #define IMAGESTATISTICS_H #include "../readmes/imstatsreadme.h" #include "../iview/iview.h" #include "../qcustomplot.h" #include "../instrumentdata.h" #include "../processingStatus/processingStatus.h" #include #include #include "../processingInternal/data.h" #include namespace Ui { class ImageStatistics; } class ImageStatistics : public QMainWindow { Q_OBJECT public: // Constructor passing a list of MyImages // explicit ImageStatistics(QVector > &imlist, const QString main, const QString sciencedir, // const instrumentDataType *instrumentData, QWidget *parent); explicit ImageStatistics(QList &datalist, const QString main, const QString sciencedir, const instrumentDataType *instrumentData, QWidget *parent); ~ImageStatistics(); void keyReleaseEvent(QKeyEvent *event); bool iViewOpen = false; signals: void imageSelected(int index); public slots: void currentlyDisplayedIndexReceived(int currentId); void activationChangedReceiver(); void iviewNewImageShownReceiver(int newDataPoint); private slots: void dataPointClicked(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event); void numericSelection(); void on_statisticsPushButton_clicked(); void on_exportPushButton_clicked(); void on_showPushButton_clicked(); void on_ClearPlotPushButton_clicked(); void on_restoreDataPushButton_clicked(); void on_clearSelectionPushButton_clicked(); void on_invertSelectionPushButton_clicked(); void on_readmePushButton_clicked(); void on_connectDataPointsCheckBox_clicked(); void uncheckIviewPushButton(); void validate(); // void currentlyDisplayedIndexReceived(int currentId); void on_fwhmunitsComboBox_currentIndexChanged(const QString &arg1); void on_actionClose_triggered(); void on_scienceComboBox_activated(const QString &arg1); void on_chipsLineEdit_editingFinished(); void on_raLineEdit_editingFinished(); void on_decLineEdit_editingFinished(); private: QString mainDir; QString statusString; ProcessingStatus *processingStatus; const instrumentDataType *instData; QList dataList; Data *scienceData; Ui::ImageStatistics *ui; QString thelidir; QString userdir; QVector> myExposureList; QList allMyImages; QList filteredMyImages; QStringList dataName; QStringList badStatsList; QString scienceDirName; QDir scienceDir; QVector dataImageNr = QVector(); QVector dataSky = QVector(); QVector dataAirmass = QVector(); QVector dataFWHM = QVector(); QVector dataRZP = QVector(); QVector dataEllipticity = QVector(); bool skyData = true; bool seeingData = true; bool seeingFromGaia = false; // A flag whether the seeing was estimated from medians of all sources, or from a match with GAIA point sources bool airmassData = true; bool rzpData = true; bool ellipticityData = true; bool imgSelected = false; bool statisticsDataDisplayed = false; QString imgSelectedName = ""; int numObj = 0; int lastDataPointClicked = -1; enum Qt::MouseButton lastButtonClicked = Qt::LeftButton; enum Qt::Key lastKeyPressed = Qt::Key_Left; bool initKeySelection = false; QString directionSwitched = "noSwitch"; IView *iView; QCPGraph *skyGraph; QCPGraph *seeingGraph; QCPGraph *airmassGraph; QCPGraph *rzpGraph; QCPGraph *ellipticityGraph; QCPGraph *skyGraphIview; QCPGraph *seeingGraphIview; QCPGraph *airmassGraphIview; QCPGraph *rzpGraphIview; QCPGraph *ellipticityGraphIview; QCPDataSelection selection; // data points selected by mouse clicks or key presses QCPDataSelection numSelection; // data points selected by manually entered numeric thresholds QList graphList; QList graphListIview; QStringList filteredImageList; QList numericThresholdList; ImstatsReadme *imstatsReadme; QCPGraph::LineStyle myLineStyle; void clearAll(); void clearData(); void clearSelection(); void makeConnections(); void plot(); void plotSelection(int index); void readStatisticsData(); // void showNoData(QCPGraph *graph, float xpos, float ypos); void makeListOfBadImages(); Data *getData(QList DT_x, QString dirName); void init(); bool isImageSelected(MyImage *myImage, const QString &ra, const QString &dec, const QVector &chipID); void activateImages(); void highlightClickedDataPoint(); }; #endif // IMAGESTATISTICS_H THELI-3.1.3/src/imagestatistics/imagestatistics.ui000066400000000000000000001611751417631501300221170ustar00rootroot00000000000000 ImageStatistics 0 0 1290 832 Image statistics 0 0 0 170 170 171 255 255 255 212 212 213 85 85 85 113 113 114 0 0 0 255 255 255 0 0 0 255 255 255 170 170 171 0 0 0 212 212 213 255 255 220 0 0 0 0 0 0 170 170 171 255 255 255 212 212 213 85 85 85 113 113 114 0 0 0 255 255 255 0 0 0 255 255 255 170 170 171 0 0 0 212 212 213 255 255 220 0 0 0 85 85 85 170 170 171 255 255 255 212 212 213 85 85 85 113 113 114 85 85 85 255 255 255 85 85 85 170 170 171 170 170 171 0 0 0 170 170 171 255 255 220 0 0 0 Qt::StrongFocus Click to select / deselect data points. Right-click to select multiple points. Click-drag to shift plot range. Scroll on plot or axes to zoom. true 0 0 1290 23 File 252 252 252 220 220 221 252 252 252 220 220 221 220 220 221 220 220 221 true QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Configuration 1 75 true Image selection Qt::Horizontal 40 20 0 0 30 0 30 16777215 85 170 255 85 170 255 85 170 255 75 true Qt::ClickFocus Displays a dialog explaining the various mouse and keyboard interactions with the data. ? Qt::Vertical QSizePolicy::Fixed 20 10 Qt::ClickFocus Shows the image associated with a selected data point. Display selected image true 75 true Cut-offs 252 252 252 198 198 199 252 252 252 198 198 199 198 198 199 198 198 199 true QFrame::StyledPanel QFrame::Raised 70 16777215 Qt::StrongFocus Maximum airmass allowed false Seeing 70 16777215 Qt::StrongFocus Minimum seeing allowed (usually unconstrained as lower seeing is better) false 70 16777215 Qt::StrongFocus Maximum seeing allowed false 70 16777215 Qt::StrongFocus Minimum relative zeropoint allowed false 70 16777215 Qt::StrongFocus Minimum airmass allowed (usually unconstrained as lower airmass is better) false 70 16777215 Qt::StrongFocus Minimum sky background allowed false 70 16777215 Qt::StrongFocus Maximum sky background allowed false Airmass 70 16777215 Qt::StrongFocus Minimum PSF ellipticity allowed (usually unconstrained as lower ellipticity is better) false Sky RZP 70 16777215 Qt::StrongFocus Maximum relative zeropoint allowed (usually unconstrained as higher zeropoints mean better transparency) false Ellip. 70 16777215 Qt::StrongFocus Maximum PSF ellipticity allowed false min max Image # 70 16777215 Qt::StrongFocus The lowest image number in the consecutive series (constraint on the x-axis) false 70 16777215 Qt::StrongFocus The highest image number in the consecutive series (constraint on the x-axis) false 75 true Settings 252 252 252 198 198 199 252 252 252 198 198 199 198 198 199 198 198 199 true QFrame::StyledPanel QFrame::Raised FWHM units The units used for the seeing plot arcsec pixel Qt::ClickFocus Invert the selection Invert selection Qt::ClickFocus Clears and resets the plot panels to an empty state. Clear plot Qt::ClickFocus Clears a selection of data points. Clear selection Qt::ClickFocus Restores manually removed data points. Also puts the corresponding bad images back into their original place. Restore data Qt::ClickFocus Exports the graphics to PNG format. Export plot Qt::ClickFocus Connect data points Qt::Vertical 20 254 252 252 252 198 198 199 252 252 252 198 198 199 198 198 199 198 198 199 true QFrame::StyledPanel QFrame::Raised Image shall contain: R.A. DEC Qt::StrongFocus Optional. The DEC coordinate that must be contained in the selection. Decimal or DD:MM:SS format. This might take a while to execute. false Qt::StrongFocus Optional. The R.A. coordinate that must be contained in the selection. Decimal or HH:MM:SS format. This might take a while to execute. false Data: Chips Select for which SCIENCE directory the statistics should be loaded 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::ClickFocus Obtain the statistics measurements Update plots Qt::StrongFocus Blank- or comma-separated list of detector numbers to be shown false Close QCustomPlot QWidget
qcustomplot.h
1
raLineEdit decLineEdit skyMinLineEdit skyMaxLineEdit airmassMinLineEdit airmassMaxLineEdit seeingMinLineEdit seeingMaxLineEdit rzpMinLineEdit rzpMaxLineEdit ellMinLineEdit ellMaxLineEdit imageMinLineEdit imageMaxLineEdit
THELI-3.1.3/src/imagestatistics/imagestatistics_events.cc000066400000000000000000000167641417631501300234560ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagestatistics.h" #include "ui_imagestatistics.h" #include "../functions.h" #include "../qcustomplot.h" #include "../iview/iview.h" #include #include #include // Controls what happens when a key is pressed void ImageStatistics::keyReleaseEvent(QKeyEvent *event) { // 'delete' key: park selected images from one chip in inactive/badStatistics/ // 'a' key: park selected images (including all chips from that exposure) in inactive/badStatistics/ // Left / right key: move selection forward / backward if (!ui->statPlot->hasFocus()) return; if (event->key() != Qt::Key_Delete && event->key() != Qt::Key_A && event->key() != Qt::Key_Left && event->key() != Qt::Key_Right) return; if (selection.isEmpty()) return; if (!scienceDir.exists()) return; QVector badIndexes; if (event->key() == Qt::Key_Delete || event->key() == Qt::Key_A) { // make a "badStatistics" sub-directory QString badStatsDirName = scienceDirName+"/inactive/badStatistics/"; QDir badStatsDir(badStatsDirName); badStatsDir.mkpath(badStatsDirName); // move selected images to inactive/badStatistics/ foreach (QCPDataRange dataRange, selection.dataRanges()) { // QCPGraphDataContainer::const_iterator itBegin = seeingGraph->data()->at(dataRange.begin()); // QCPGraphDataContainer::const_iterator itEnd = seeingGraph->data()->at(dataRange.end()); int begin = dataRange.begin(); int end = dataRange.end(); for (int i=begin; ikey() == Qt::Key_Delete) { // Add selected image to list of bad images if (!badStatsList.contains(imgSelectedName)) { badStatsList << imgSelectedName; } // Deactivate selected image // allMyImages[i]->setActiveState(MyImage::BADSTATS); // deactivate // emit allMyImages[i]->modelUpdateNeeded(allMyImages[i]->chipName); filteredMyImages[i]->setActiveState(MyImage::BADSTATS); // deactivate emit filteredMyImages[i]->modelUpdateNeeded(filteredMyImages[i]->chipName); } // 'A' key pressed // Deactivate selected *exposure* (all chips belonging to that exposure) if (event->key() == Qt::Key_A) { QString base = removeLastWords(imgSelectedName, 1, '_'); QStringList baseFilter(base+"_*.fits"); QStringList baseList = scienceDir.entryList(baseFilter); // List of all images belonging to that exposure for (auto &it : baseList) { if (!badStatsList.contains(it)) { badStatsList << it; } } for (auto &myimg : allMyImages) { // for (auto &myimg : filteredMyImages) { if (imgSelectedName.contains(myimg->rootName)) { myimg->setActiveState(MyImage::BADSTATS); // deactivate emit myimg->modelUpdateNeeded(myimg->chipName); } } } } } dataImageNr = removeVectorItems_T(dataImageNr, badIndexes); dataSky = removeVectorItems_T(dataSky, badIndexes); dataAirmass = removeVectorItems_T(dataAirmass, badIndexes); dataFWHM = removeVectorItems_T(dataFWHM, badIndexes); dataRZP = removeVectorItems_T(dataRZP, badIndexes); dataEllipticity = removeVectorItems_T(dataEllipticity, badIndexes); numObj = dataSky.length(); clearSelection(); readStatisticsData(); plot(); if (iViewOpen) iView->clearAll(); } // Cycle the selection forth or back by one or more data points, // depending on previous click types if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) { if (lastDataPointClicked == -1) return; int currentDataPoint; if (initKeySelection) { clearSelection(); initKeySelection = false; } if (event->key() == Qt::Key_Left) { if (lastDataPointClicked <= 0) return; currentDataPoint = lastDataPointClicked-1; if (lastKeyPressed == Qt::Key_Right) directionSwitched = "RightToLeft"; else directionSwitched = "noSwitch"; lastKeyPressed = Qt::Key_Left; } else if (event->key() == Qt::Key_Right) { if (lastDataPointClicked >= numObj-1) return; currentDataPoint = lastDataPointClicked+1; if (lastKeyPressed == Qt::Key_Left) directionSwitched = "LeftToRight"; else directionSwitched = "noSwitch"; lastKeyPressed = Qt::Key_Right; } else { // middle mouse click etc return; } lastDataPointClicked = currentDataPoint; QCPDataRange rangeSelected; if (directionSwitched == "noSwitch") { rangeSelected.setBegin(currentDataPoint); rangeSelected.setEnd(currentDataPoint+1); } if (directionSwitched == "RightToLeft") { rangeSelected.setBegin(currentDataPoint); rangeSelected.setEnd(currentDataPoint+2); } if (directionSwitched == "LeftToRight") { rangeSelected.setBegin(currentDataPoint-1); rangeSelected.setEnd(currentDataPoint+1); } QCPDataSelection dpClicked; dpClicked.addDataRange(rangeSelected); // Previously right click: add (or remove) previous or next data point to selection if (lastButtonClicked == Qt::RightButton) { if (!selection.contains(dpClicked)) selection.operator +=(rangeSelected); else selection.operator -=(rangeSelected); } // Previously left click: select previous or next data point if (lastButtonClicked == Qt::LeftButton) { clearSelection(); selection = dpClicked; } selection.simplify(); plotSelection(currentDataPoint); highlightClickedDataPoint(); // Reflect the image in iView if (iViewOpen) { imgSelectedName = dataName[currentDataPoint]; if (!selection.isEmpty()) { emit imageSelected(lastDataPointClicked); } else { if (iViewOpen) iView->clearAll(); imgSelected = false; lastDataPointClicked = -1; } } } } THELI-3.1.3/src/imagestatistics/imagestatistics_plotting.cc000066400000000000000000000362061417631501300240030ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagestatistics.h" #include "ui_imagestatistics.h" #include "../instrumentdata.h" #include "../functions.h" #include "../qcustomplot.h" #include "../iview/iview.h" #include "../myimage/myimage.h" #include #include #include #include #include #include #include void ImageStatistics::plot() { if (numObj == 0) { ui->statPlot->replot(); ui->statPlot->update(); } ui->statPlot->clearItems(); ui->statPlot->clearGraphs(); ui->statPlot->plotLayout()->clear(); // create a sub layout that we'll place in first row: QCPLayoutGrid *subLayout = new QCPLayoutGrid(); ui->statPlot->plotLayout()->addElement(0, 0, subLayout); QCPAxisRect *rectSky = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectSeeing = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectRZP = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectAirmass = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectEllipticity = new QCPAxisRect(ui->statPlot); // rectSeeing->axis(QCPAxis::atRight)->setVisible(false); QList< QCPAxisRect* > rectList; rectList << rectSky << rectSeeing << rectRZP << rectAirmass << rectEllipticity; for (auto &it : rectList) { foreach (QCPAxis *axis, it->axes()) { axis->setLayer("axes"); axis->grid()->setLayer("grid"); } it->setupFullAxesBox(true); it->axis(QCPAxis::atBottom)->setLabel("Image #"); } rectSky->axis(QCPAxis::atLeft)->setLabel("Background [ e- ]"); rectAirmass->axis(QCPAxis::atLeft)->setLabel("Airmass"); rectAirmass->axis(QCPAxis::atLeft)->setRangeReversed(true); QString unit = ui->fwhmunitsComboBox->currentText(); if (seeingFromGaia || !seeingData) rectSeeing->axis(QCPAxis::atLeft)->setLabel("Stellar FWHM [ "+unit+" ]"); else rectSeeing->axis(QCPAxis::atLeft)->setLabel("Median FWHM [ "+unit+" ]"); // rectSeeing->addAxis(QCPAxis::atRight)->setLabel("Seeing [ pixel ]"); // QCPAxis *seeingPixelAxis = rectSeeing->axis(QCPAxis::atRight); rectRZP->axis(QCPAxis::atLeft)->setLabel("Relative zeropoint [ mag ]"); if (seeingFromGaia || !ellipticityData) rectEllipticity->axis(QCPAxis::atLeft)->setLabel("Stellar ellipticity [ % ]"); else rectEllipticity->axis(QCPAxis::atLeft)->setLabel("Median ellipticity [ % ]"); subLayout->addElement(0, 0, rectSky); subLayout->addElement(0, 1, rectAirmass); subLayout->addElement(0, 2, rectSeeing); subLayout->addElement(1, 0, rectRZP); subLayout->addElement(1, 1, rectEllipticity); // The graphs graphList.clear(); graphListIview.clear(); skyGraph = ui->statPlot->addGraph(rectSky->axis(QCPAxis::atBottom), rectSky->axis(QCPAxis::atLeft)); seeingGraph = ui->statPlot->addGraph(rectSeeing->axis(QCPAxis::atBottom), rectSeeing->axis(QCPAxis::atLeft)); airmassGraph = ui->statPlot->addGraph(rectAirmass->axis(QCPAxis::atBottom), rectAirmass->axis(QCPAxis::atLeft)); rzpGraph = ui->statPlot->addGraph(rectRZP->axis(QCPAxis::atBottom), rectRZP->axis(QCPAxis::atLeft)); ellipticityGraph = ui->statPlot->addGraph(rectEllipticity->axis(QCPAxis::atBottom), rectEllipticity->axis(QCPAxis::atLeft)); skyGraphIview = ui->statPlot->addGraph(rectSky->axis(QCPAxis::atBottom), rectSky->axis(QCPAxis::atLeft)); seeingGraphIview = ui->statPlot->addGraph(rectSeeing->axis(QCPAxis::atBottom), rectSeeing->axis(QCPAxis::atLeft)); airmassGraphIview = ui->statPlot->addGraph(rectAirmass->axis(QCPAxis::atBottom), rectAirmass->axis(QCPAxis::atLeft)); rzpGraphIview = ui->statPlot->addGraph(rectRZP->axis(QCPAxis::atBottom), rectRZP->axis(QCPAxis::atLeft)); ellipticityGraphIview = ui->statPlot->addGraph(rectEllipticity->axis(QCPAxis::atBottom), rectEllipticity->axis(QCPAxis::atLeft)); graphList << skyGraph << seeingGraph << airmassGraph << rzpGraph << ellipticityGraph; graphListIview << skyGraphIview << seeingGraphIview << airmassGraphIview<< rzpGraphIview << ellipticityGraphIview; // Leave here if we are just initializing the plot panels if (numObj == 0) return; QCPSelectionDecorator *decoratorSky = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorRZP = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorAirmass = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorSeeing = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorEllipticity = new QCPSelectionDecorator(); // change the last argument to a larger number if you want bigger data points QCPScatterStyle scatterstyle(QCPScatterStyle::ScatterShape::ssDisc, QColor("#ff3300"), QColor("#ff3300"), 6); decoratorSky->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorRZP->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorSeeing->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorAirmass->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorEllipticity->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); double xmin = minVec_T(dataImageNr); double xmax = maxVec_T(dataImageNr); double dx = (xmax - xmin) * 0.05; QVector dataPtr; for (auto &it : graphList) { it->setSelectable(QCP::stMultipleDataRanges); it->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(Qt::blue), QBrush(Qt::blue), 6)); it->setLineStyle(myLineStyle); if (it == skyGraph) { dataPtr = dataSky; it->setSelectionDecorator(decoratorSky); it->setData(dataImageNr, dataPtr); } else if (it == seeingGraph) { float unitsRescale = 1.0; if (ui->fwhmunitsComboBox->currentText() == "arcsec") unitsRescale = 1.0; else unitsRescale = instData->pixscale; dataPtr = dataFWHM; for (auto &it : dataPtr) it /= unitsRescale; it->setSelectionDecorator(decoratorSeeing); // if (seeingData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 0.50, 1.80); // } } else if (it == airmassGraph) { dataPtr = dataAirmass; it->setSelectionDecorator(decoratorAirmass); // if (airmassData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 1.80, 0.50); // } } else if (it == rzpGraph) { dataPtr = dataRZP; it->setSelectionDecorator(decoratorRZP); // if (rzpData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 1.8, 1.8); // } } else if (it == ellipticityGraph) { dataPtr = dataEllipticity; it->setSelectionDecorator(decoratorEllipticity); // if (ellipticityData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 2.0, 2.0); // } } double ymin = minVec_T(dataPtr); double ymax = maxVec_T(dataPtr); double dy = (ymax - ymin) * 0.05; it->keyAxis()->setRange(xmin-dx, xmax+dx); it->valueAxis()->setRange(ymin-dy, ymax+dy); } ui->statPlot->replot(); ui->statPlot->update(); if (numObj > 0) statisticsDataDisplayed = true; else statisticsDataDisplayed = false; } void ImageStatistics::highlightClickedDataPoint() { if (lastDataPointClicked == -1) return; for (auto &it : graphListIview) { int ldpc = lastDataPointClicked; QVector x; QVector y; x << dataImageNr[ldpc]; it->setSelectable(QCP::SelectionType::stNone); it->setLineStyle(QCPGraph::lsNone); it->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor("#000000"), 12)); if (it == skyGraphIview) { y << dataSky[ldpc]; it->setData(x,y); } else if (it == seeingGraphIview) { float unitsRescale = 1.0; if (ui->fwhmunitsComboBox->currentText() == "arcsec") unitsRescale = 1.0; else unitsRescale = instData->pixscale; y << dataFWHM[ldpc]; for (auto &it : y) it /= unitsRescale; it->setData(x,y); } else if (it == airmassGraphIview) { y << dataAirmass[ldpc]; it->setData(x,y); } else if (it == rzpGraphIview) { y << dataRZP[ldpc]; it->setData(x,y); } else if (it == ellipticityGraphIview) { y << dataEllipticity[ldpc]; it->setData(x,y); } } ui->statPlot->replot(); ui->statPlot->update(); } /* void ImageStatistics::showNoData(QCPGraph *graph, float xpos, float ypos) { QCPItemText *noData = new QCPItemText(ui->statPlot); noData->position->setType(QCPItemPosition::ptAxisRectRatio); noData->setPositionAlignment(Qt::AlignLeft|Qt::AlignCenter); noData->position->setCoords(xpos, ypos); noData->setClipToAxisRect(false); noData->setSelectable(false); noData->setText("no data"); noData->setTextAlignment(Qt::AlignLeft); noData->setFont(QFont(font().family(), 9)); noData->setPadding(QMargins(4, 0, 4, 0)); noData->setPen(QPen(Qt::black)); } */ void ImageStatistics::plotSelection(int index) { for (auto &it : graphList) { it->setSelection(selection); } ui->statPlot->replot(); ui->statPlot->update(); } void ImageStatistics::dataPointClicked(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) { // Clicking on a data point may select or deselect it imgSelectedName = dataName[dataIndex]; imgSelected = true; lastDataPointClicked = dataIndex; // We build the selection by successively clicking into different graphs. // Last index points to point above data range, hence must be +1 to select single data point; QCPDataRange rangeSelected(dataIndex, dataIndex+1); QCPDataSelection dpClicked; dpClicked.addDataRange(rangeSelected); // Right click: // Include/exclude a data point in the selection. // Multiple data points can be selected (we accumulate them in 'selection') if (event->button() == Qt::RightButton) { initKeySelection = true; if (!selection.contains(dpClicked)) selection.operator +=(rangeSelected); else selection.operator -=(rangeSelected); } // Left click: single selection/deselection only if (event->button() == Qt::LeftButton) { if (!selection.contains(dpClicked)) selection = dpClicked; else clearSelection(); } lastButtonClicked = event->button(); selection.simplify(); plotSelection(dataIndex); highlightClickedDataPoint(); // ui->statPlot->setStatusTip(imgSelectedName); if (!selection.isEmpty()) { emit imageSelected(lastDataPointClicked); } else { if (iViewOpen) iView->clearAll(); imgSelected = false; lastDataPointClicked = -1; } } void ImageStatistics::on_invertSelectionPushButton_clicked() { QCPDataRange outerRange(0, numObj); selection = selection.inverse(outerRange); plotSelection(0); } void ImageStatistics::numericSelection() { if (numObj == 0) return; numSelection.clear(); QVector numericIndexes; QString skyMin = ui->skyMinLineEdit->text(); QString skyMax = ui->skyMaxLineEdit->text(); QString airmassMin = ui->airmassMinLineEdit->text(); QString airmassMax = ui->airmassMaxLineEdit->text(); QString seeingMin = ui->seeingMinLineEdit->text(); QString seeingMax = ui->seeingMaxLineEdit->text(); QString rzpMin = ui->rzpMinLineEdit->text(); QString rzpMax = ui->rzpMaxLineEdit->text(); QString ellMin = ui->ellMinLineEdit->text(); QString ellMax = ui->ellMaxLineEdit->text(); QString imageMin = ui->imageMinLineEdit->text(); QString imageMax = ui->imageMaxLineEdit->text(); for (int i=0; i skyMax.toDouble()) numericIndexes.push_back(i); if (!airmassMin.isEmpty() && dataAirmass[i] < airmassMin.toDouble()) numericIndexes.push_back(i); if (!airmassMax.isEmpty() && dataAirmass[i] > airmassMax.toDouble()) numericIndexes.push_back(i); if (!seeingMin.isEmpty() && dataFWHM[i] < seeingMin.toDouble()) numericIndexes.push_back(i); if (!seeingMax.isEmpty() && dataFWHM[i] > seeingMax.toDouble()) numericIndexes.push_back(i); if (!rzpMin.isEmpty() && dataRZP[i] < rzpMin.toDouble()) numericIndexes.push_back(i); if (!rzpMax.isEmpty() && dataRZP[i] > rzpMax.toDouble()) numericIndexes.push_back(i); if (!ellMin.isEmpty() && dataEllipticity[i] < ellMin.toDouble()) numericIndexes.push_back(i); if (!ellMax.isEmpty() && dataEllipticity[i] > ellMax.toDouble()) numericIndexes.push_back(i); if (!imageMin.isEmpty() && i < imageMin.toInt()) numericIndexes.push_back(i); if (!imageMax.isEmpty() && i > imageMax.toInt()) numericIndexes.push_back(i); } for (auto &it : numericIndexes) { QCPDataRange range(it,it+1); numSelection.addDataRange(range); } numSelection.simplify(); QList rangeList = numSelection.dataRanges(); // operator += automatically simplifies the selection for (auto &it : rangeList) { selection.operator +=(it); } plotSelection(0); // Have the plot widget grab the focus immediately, such that key press events are processed ui->statPlot->setFocus(); } void ImageStatistics::on_connectDataPointsCheckBox_clicked() { if (ui->connectDataPointsCheckBox->isChecked()) myLineStyle = QCPGraph::lsLine; else myLineStyle = QCPGraph::lsNone; plot(); plotSelection(0); } void ImageStatistics::on_clearSelectionPushButton_clicked() { clearSelection(); for (auto &it : graphList) { it->setSelection(selection); } ui->statPlot->replot(); ui->statPlot->update(); } void ImageStatistics::on_restoreDataPushButton_clicked() { clearData(); clearSelection(); badStatsList.clear(); activateImages(); init(); readStatisticsData(); plot(); } void ImageStatistics::activateImages() { for (auto &it : allMyImages) { it->setActiveState(MyImage::ACTIVE); emit it->modelUpdateNeeded(it->chipName); } } THELI-3.1.3/src/instrumentdata.h000066400000000000000000000036661417631501300164010ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef INSTRUMENTDATA_H #define INSTRUMENTDATA_H #include #include #include typedef struct { int numChips; QString name = ""; QString shortName = ""; QString nameFullPath = ""; float obslat = 0.; float obslon = 0.; QString bayer; QString type; QString flip = ""; float pixscale = 1.0; // in arcsec // float gain = 1.0; float radius = 0.1; // exposure coverage radius in degrees float storage = 0; // MB used for a single image float storageExposure = 0.; // MB used for the entire (multi-chip) exposure int numUsedChips; long nGlobal = 1; // Overall focal plane size in x-direction long mGlobal = 1; // Overall focal plane size in x-direction QVector badChips; QVector goodChips; int validChip = -1; QMap chipMap; // in case of bad detectors, we need to map e.g. chip #4 to index #3 (e.g. if data from chip #2 is missing) QVector overscan_xmin; QVector overscan_xmax; QVector overscan_ymin; QVector overscan_ymax; QVector cutx; QVector cuty; QVector sizex; QVector sizey; QVector crpix1; QVector crpix2; } instrumentDataType; #endif // INSTRUMENTDATA_H THELI-3.1.3/src/instrumentdefinition.cc000066400000000000000000000712241417631501300177510ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "instrumentdefinition.h" #include "ui_instrumentdefinition.h" #include "functions.h" #include "libraw/libraw.h" #include #include #include Instrument::Instrument(QWidget *parent) : QMainWindow(parent), ui(new Ui::Instrument) { ui->setupUi(this); geometryList.append(ui->overscanxMinLineEdit); geometryList.append(ui->overscanxMaxLineEdit); geometryList.append(ui->overscanyMinLineEdit); geometryList.append(ui->overscanyMaxLineEdit); geometryList.append(ui->startxLineEdit); geometryList.append(ui->startyLineEdit); geometryList.append(ui->sizexLineEdit); geometryList.append(ui->sizeyLineEdit); geometryList.append(ui->crpix1LineEdit); geometryList.append(ui->crpix2LineEdit); geometryNumList.append(ui->overscanxMinNumLineEdit); geometryNumList.append(ui->overscanxMaxNumLineEdit); geometryNumList.append(ui->overscanyMinNumLineEdit); geometryNumList.append(ui->overscanyMaxNumLineEdit); geometryNumList.append(ui->startxNumLineEdit); geometryNumList.append(ui->startyNumLineEdit); geometryNumList.append(ui->sizexNumLineEdit); geometryNumList.append(ui->sizeyNumLineEdit); geometryNumList.append(ui->crpix1NumLineEdit); geometryNumList.append(ui->crpix2NumLineEdit); for (auto &it: geometryList) { connect(it, &QLineEdit::textChanged, this, &Instrument::validate); connect(it, &QLineEdit::textChanged, this, &Instrument::paintNumLineEdits); } connect(ui->latitudeLineEdit, &QLineEdit::textChanged, this, &Instrument::validate); connect(ui->longitudeLineEdit, &QLineEdit::textChanged, this, &Instrument::validate); connect(ui->plateScaleLineEdit, &QLineEdit::textChanged, this, &Instrument::validate); connect(ui->instrumentNameLineEdit, &QLineEdit::textChanged, this, &Instrument::validate); connect(ui->bayerRGGBToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons); connect(ui->bayerGBRGToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons); connect(ui->bayerBGGRToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons); connect(ui->bayerGRBGToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons); initEnvironment(thelidir, userdir); ui->bayerCheckBox->setChecked(false); bayerButtonGroup->addButton(ui->bayerGBRGToolButton); bayerButtonGroup->addButton(ui->bayerRGGBToolButton); bayerButtonGroup->addButton(ui->bayerBGGRToolButton); bayerButtonGroup->addButton(ui->bayerGRBGToolButton); bayerButtonGroup->setExclusive(true); ui->bayerGBRGToolButton->setIcon(QIcon(":/icons/bayer_gbrg.png")); ui->bayerRGGBToolButton->setIcon(QIcon(":/icons/bayer_rggb.png")); ui->bayerBGGRToolButton->setIcon(QIcon(":/icons/bayer_bggr.png")); ui->bayerGRBGToolButton->setIcon(QIcon(":/icons/bayer_grbg.png")); ui->buttonFrame->hide(); paintNumLineEdits(""); setWindowIcon(QIcon(":/icons/addInst.png")); applyStyleSheets(); QButtonGroup formatButtonGroup; formatButtonGroup.addButton(ui->formatFITSRadioButton); formatButtonGroup.addButton(ui->formatRAWRadioButton); formatButtonGroup.setExclusive(true); connect(ui->formatFITSRadioButton, &QRadioButton::clicked, this, &Instrument::toggleFormatPushButton); connect(ui->formatRAWRadioButton, &QRadioButton::clicked, this, &Instrument::toggleFormatPushButton); toggleFormatPushButton(); } Instrument::~Instrument() { delete ui; } void Instrument::applyStyleSheets() { /* QList titleList; titleList.append(ui->title1Label); for (auto &it : titleList) { it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);"); it->setMargin(8); } */ QList subtitleList; subtitleList.append(ui->subtitle1Label); subtitleList.append(ui->subtitle2Label); for (auto &it : subtitleList) { it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);"); it->setMargin(8); // it->setStyleSheet("background-color: rgb(190,190,210);"); // it->setMargin(4); } QList frameList; frameList.append(ui->inst1Frame); frameList.append(ui->inst2Frame); frameList.append(ui->inst6Frame); /* for (auto &it : frameList) { // it->setStyleSheet("background-color: #ebebee;"); // nothing yet } */ QList buttonList; buttonList.append(ui->bayerBGGRToolButton); buttonList.append(ui->bayerRGGBToolButton); buttonList.append(ui->bayerGBRGToolButton); buttonList.append(ui->bayerGRBGToolButton); /* for (auto &it : buttonList) { // } */ } void Instrument::toggleFormatPushButton() { if (ui->formatFITSRadioButton->isChecked()) { ui->readRAWgeometryPushButton->setDisabled(true); ui->overscanxMinLineEdit->setEnabled(true); ui->overscanxMaxLineEdit->setEnabled(true); ui->overscanyMinLineEdit->setEnabled(true); ui->overscanyMaxLineEdit->setEnabled(true); ui->startxLineEdit->setEnabled(true); ui->startyLineEdit->setEnabled(true); ui->sizexLineEdit->setEnabled(true); ui->sizeyLineEdit->setEnabled(true); ui->crpix1LineEdit->setEnabled(true); ui->crpix2LineEdit->setEnabled(true); } else { ui->readRAWgeometryPushButton->setEnabled(true); ui->overscanxMinLineEdit->setDisabled(true); ui->overscanxMaxLineEdit->setDisabled(true); ui->overscanyMinLineEdit->setDisabled(true); ui->overscanyMaxLineEdit->setDisabled(true); ui->startxLineEdit->setDisabled(true); ui->startyLineEdit->setDisabled(true); ui->sizexLineEdit->setDisabled(true); ui->sizeyLineEdit->setDisabled(true); ui->crpix1LineEdit->setDisabled(true); ui->crpix2LineEdit->setDisabled(true); } } void Instrument::toggle_bayer_ToolButtons() { QToolButton *toolbutton = qobject_cast(sender()); QString sender_name = toolbutton->objectName(); if (toolbutton->isChecked()) this->setStyleSheet("QToolButton#"+sender_name+" { background-color: black }"); else this->setStyleSheet("QToolButton#"+sender_name+" { background-color: #ddddddd }"); } void Instrument::paintNumLineEdits(QString geometry) { QPalette paletteMatch; QPalette paletteNoMatch; paletteMatch.setColor(QPalette::Base,QColor("#a9ffe6")); paletteNoMatch.setColor(QPalette::Base,QColor("#ff99aa")); int numEntries; geometry = geometry.simplified(); // Triggered by LineEdit changed QLineEdit *le = qobject_cast(sender()); if (le != 0) { if (geometry.isEmpty()) numEntries = 0; else numEntries = geometry.split(' ').length(); for (int i=0; iobjectName() == geometryList.at(i)->objectName()) { if (numEntries == ui->numchipSpinBox->value()) geometryNumList.at(i)->setPalette(paletteMatch); else geometryNumList.at(i)->setPalette(paletteNoMatch); geometryNumList.at(i)->setText(QString::number(numEntries)); } } } else { // Triggered by numchipSpinBox value changed for (int i=0; itext().isEmpty()) numEntries = 0; else numEntries = geometryList.at(i)->text().split(' ').length(); if (numEntries == ui->numchipSpinBox->value()) geometryNumList.at(i)->setPalette(paletteMatch); else geometryNumList.at(i)->setPalette(paletteNoMatch); geometryNumList.at(i)->setText(QString::number(numEntries)); } } } void Instrument::on_numchipSpinBox_valueChanged(int arg1) { numChips = arg1; paintNumLineEdits(""); if (arg1 == 1) ui->flipComboBox->setEnabled(true); else ui->flipComboBox->setDisabled(true); } void Instrument::validate(QString arg1) { if (arg1.isEmpty()) return; QRegExp rf1( "[-0-9.]+" ); QValidator* validator_float = new QRegExpValidator(rf1, this ); QRegExp re( "[-0-9e.]+" ); QRegExp rf2( "[0-9.]+" ); QValidator* validator_floatpos = new QRegExpValidator(rf2, this ); QRegExp ri3( "[0-9\\s]+" ); QValidator* validator_intposblank = new QRegExpValidator(ri3, this ); QRegExp ri4( "[-0-9\\s]+" ); QValidator* validator_intblank = new QRegExpValidator(ri4, this ); ui->latitudeLineEdit->setValidator( validator_float ); ui->longitudeLineEdit->setValidator( validator_float ); // ui->gainLineEdit->setValidator( validator_floatpos ); ui->plateScaleLineEdit->setValidator( validator_floatpos ); ui->overscanxMinLineEdit->setValidator( validator_intposblank ); ui->overscanxMaxLineEdit->setValidator( validator_intposblank); ui->overscanyMinLineEdit->setValidator( validator_intposblank ); ui->overscanyMaxLineEdit->setValidator( validator_intposblank); ui->startxLineEdit->setValidator( validator_intposblank ); ui->startyLineEdit->setValidator( validator_intposblank ); ui->sizexLineEdit->setValidator( validator_intposblank ); ui->sizeyLineEdit->setValidator( validator_intposblank ); ui->crpix1LineEdit->setValidator( validator_intblank ); ui->crpix2LineEdit->setValidator( validator_intblank ); // instrument name must not accept blank characters // QRegExp rx2( "^\\S+$" ); QRegExp rx2( "[A-Za-z0-9@_-+]+" ); QValidator* validator_string2 = new QRegExpValidator( rx2, this ); ui->instrumentNameLineEdit->setValidator( validator_string2 ); } QString Instrument::geometryToConfig(QString geometry) { // Transforms the entered blank-separated geometry to a bash array QStringList list = geometry.simplified().split(' '); QString bashArray = ""; int i=1; for (auto &it : list) { bashArray.append("["+QString::number(i)+"]="+it+" "); ++i; } bashArray = bashArray.simplified(); bashArray.prepend("("); bashArray.append(")"); return bashArray; } QString Instrument::configToGeometry(QString config) { // Transforms the bash vector to a blank-separated list config = config.remove("("); config = config.remove(")"); config = config.remove("["); config = config.remove("]"); config = config.replace('=',' '); QStringList list = config.simplified().split(' '); QString geometry = ""; // Keep every second word, only int i=1; for (auto &it : list) { if (! (i%2)) geometry.append(it+" "); ++i; } return geometry.simplified(); } void Instrument::on_saveConfigPushButton_clicked() { QString instrumentName = ui->instrumentNameLineEdit->text(); QString filePath = QDir::homePath()+"/.theli/instruments_user/"+instrumentName+".ini"; QFile configfile(filePath); if (!compareChipNumbers()) { QMessageBox::warning( this, "Mismatch in detector numbers", "Warning:
The number of entries in one or more of the\n" "detector geometries does not match the number of chips declared for the camera.
\n"); return; } if (configfile.exists()) { QMessageBox msgBox; msgBox.setText("A configuration file for "+instrumentName+" already exists."); QAbstractButton* overwrite = msgBox.addButton(tr("Overwrite"), QMessageBox::YesRole); QAbstractButton* cancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole); msgBox.exec(); if (msgBox.clickedButton() == overwrite) { // do nothing } else if (msgBox.clickedButton() == cancel) return; } QString pixscale = ui->plateScaleLineEdit->text(); if (pixscale.isEmpty() || pixscale.toFloat() <= 0.) { QMessageBox msgBox; msgBox.setText("Invalid pixel scale provided: "+pixscale+"\nSet to 1.0 arcsec / pixel."); QAbstractButton* ok = msgBox.addButton(tr("OK"), QMessageBox::YesRole); QAbstractButton* cancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole); msgBox.exec(); if (msgBox.clickedButton() == ok) { ui->plateScaleLineEdit->setText("1.0"); } else if (msgBox.clickedButton() == cancel) return; } if (configfile.open(QIODevice::WriteOnly)) { QTextStream outputStream(&configfile); outputStream << "INSTRUMENT=" << instrumentName << "\n"; outputStream << "NCHIPS=" << ui->numchipSpinBox->value() << "\n"; outputStream << "# Geographic location\n"; outputStream << "OBSLAT=" << ui->latitudeLineEdit->text() << "\n"; outputStream << "OBSLONG=" << ui->longitudeLineEdit->text() << "\n\n"; outputStream << "# Plate scale\n"; outputStream << "PIXSCALE=" << ui->plateScaleLineEdit->text().toFloat() << "\n\n"; outputStream << "# Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image)\n"; outputStream << "# Detector geometries\n"; outputStream << "OVSCANX1=" << geometryToConfig(ui->overscanxMinLineEdit->text()) << "\n"; outputStream << "OVSCANX2=" << geometryToConfig(ui->overscanxMaxLineEdit->text()) << "\n"; outputStream << "OVSCANY1=" << geometryToConfig(ui->overscanyMinLineEdit->text()) << "\n"; outputStream << "OVSCANY2=" << geometryToConfig(ui->overscanyMaxLineEdit->text()) << "\n"; if (!ui->bayerCheckBox->isChecked()) { outputStream << "CUTX=" << geometryToConfig(ui->startxLineEdit->text()) << "\n"; outputStream << "CUTY=" << geometryToConfig(ui->startyLineEdit->text()) << "\n"; outputStream << "SIZEX=" << geometryToConfig(ui->sizexLineEdit->text()) << "\n"; outputStream << "SIZEY=" << geometryToConfig(ui->sizeyLineEdit->text()) << "\n"; } else { // WARNING: foregoing multi-chip support, assuming single chip long cutx = ui->startxLineEdit->text().simplified().toLong(); long cuty = ui->startyLineEdit->text().simplified().toLong(); long sizex = ui->sizexLineEdit->text().simplified().toLong(); long sizey = ui->sizeyLineEdit->text().simplified().toLong(); // enforcing even-numbered geometry if (sizex % 2 != 0) { ui->startxLineEdit->setText(QString::number(cutx+1)); ui->sizexLineEdit->setText(QString::number(sizex-1)); } if (sizey % 2 != 0) { ui->startyLineEdit->setText(QString::number(cuty+1)); ui->sizeyLineEdit->setText(QString::number(sizey-1)); } outputStream << "CUTX=" << geometryToConfig(ui->startxLineEdit->text()) << "\n"; outputStream << "CUTY=" << geometryToConfig(ui->startyLineEdit->text()) << "\n"; outputStream << "SIZEX=" << geometryToConfig(ui->sizexLineEdit->text()) << "\n"; outputStream << "SIZEY=" << geometryToConfig(ui->sizeyLineEdit->text()) << "\n"; } outputStream << "REFPIXX=" << geometryToConfig(ui->crpix1LineEdit->text()) << "\n"; outputStream << "REFPIXY=" << geometryToConfig(ui->crpix2LineEdit->text()) << "\n\n"; outputStream << "# Camera type\n"; QString type; if (ui->instrumentTypeComboBox->currentIndex() == 0) type = "OPT"; else if (ui->instrumentTypeComboBox->currentIndex() == 1) type = "NIR"; else if (ui->instrumentTypeComboBox->currentIndex() == 2) type = "NIRMIR"; else if (ui->instrumentTypeComboBox->currentIndex() == 3) type = "MIR"; else type = "OPT"; outputStream << "TYPE=" << type << "\n"; if (ui->bayerCheckBox->isChecked()) { int checkedId = bayerButtonGroup->checkedId(); if (checkedId == -1) checkedId = 1; QString bayerPattern = bayerButtonGroup->button(checkedId)->objectName().remove("bayer").remove("ToolButton"); outputStream << "BAYER=" << bayerPattern << "\n"; } if (ui->flipComboBox->currentIndex() == 0) outputStream << "FLIP=NOFLIP" << "\n"; else if (ui->flipComboBox->currentIndex() == 1) outputStream << "FLIP=FLIPX" << "\n"; else if (ui->flipComboBox->currentIndex() == 2) outputStream << "FLIP=FLIPY" << "\n"; else if (ui->flipComboBox->currentIndex() == 3) outputStream << "FLIP=ROT180" << "\n"; configfile.close(); // change the text label of the pushbutton for a short while ui->saveConfigPushButton->setText("Done"); QTimer *timer = new QTimer(); connect( timer, SIGNAL(timeout()), SLOT(timerConfigDone()) ); timer->start(1000); } else { QMessageBox msgBox; msgBox.setText(filePath+" could not be opened for writing!"); msgBox.exec(); return; } QMessageBox::information( this, "Restart required", tr("User-defined instrument configurations can be found at the bottom of the instrument selection menu after restarting THELI.\n") + tr("If you edited an existing configuration, you must also restart THELI.")); } void Instrument::on_instrumentTypeComboBox_currentIndexChanged(int index) { if (index == 0) { ui->bayerCheckBox->setEnabled(true); if (ui->bayerCheckBox->isChecked()) ui->buttonFrame->show(); ui->overscanxMinLineEdit->setEnabled(true); ui->overscanxMaxLineEdit->setEnabled(true); ui->overscanyMinLineEdit->setEnabled(true); ui->overscanyMaxLineEdit->setEnabled(true); ui->overscanxMinNumLineEdit->setEnabled(true); ui->overscanxMaxNumLineEdit->setEnabled(true); ui->overscanyMinNumLineEdit->setEnabled(true); ui->overscanyMaxNumLineEdit->setEnabled(true); } else { // Turn off ovserscan for NIR data ui->bayerCheckBox->setDisabled(true); ui->bayerCheckBox->setChecked(false); ui->buttonFrame->hide(); ui->overscanxMinLineEdit->setEnabled(false); ui->overscanxMaxLineEdit->setEnabled(false); ui->overscanyMinLineEdit->setEnabled(false); ui->overscanyMaxLineEdit->setEnabled(false); ui->overscanxMinNumLineEdit->setEnabled(false); ui->overscanxMaxNumLineEdit->setEnabled(false); ui->overscanyMinNumLineEdit->setEnabled(false); ui->overscanyMaxNumLineEdit->setEnabled(false); } } void Instrument::on_loadConfigPushButton_clicked() { QString instrumentDir; QMessageBox msgBox; msgBox.setText("Which instrument type do you want to load?"); QAbstractButton* observatory = msgBox.addButton(tr("Observatory"), QMessageBox::YesRole); QAbstractButton* userdefined = msgBox.addButton(tr("User defined"), QMessageBox::YesRole); QAbstractButton* cancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole); msgBox.exec(); if (msgBox.clickedButton() == observatory) instrumentDir = thelidir+"/config/instruments/"; else if (msgBox.clickedButton() == userdefined) instrumentDir = QDir::homePath()+"/.theli/instruments_user/"; else if (msgBox.clickedButton() == cancel) return; QString instrumentFilename = QFileDialog::getOpenFileName(this, tr("Select instrument configuration file"), instrumentDir, tr("Instrument configuration file (*.ini)")); if ( instrumentFilename.isEmpty()) return; // Parse the configuration file QString line; QStringList list; QString keyword; QString keyvalue; QFile instrumentFile(instrumentFilename); if ( instrumentFile.open(QIODevice::ReadOnly)) { QTextStream stream( &instrumentFile ); // For backwards compatibility (not all config files contain these keywords): ui->bayerCheckBox->setChecked(false); // ui->gainLineEdit->setText("1.0"); ui->longitudeLineEdit->setText("0"); ui->flipComboBox->setCurrentIndex(0); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); // skip comments if (line.contains("#") || line.isEmpty() || !line.contains("=")) continue; if (line.contains("=(")) { list = line.split("=("); keyword = list.at(0); keyvalue = list.at(1); keyvalue = configToGeometry(keyvalue); } else { list = line.split("="); keyword = list.at(0); keyvalue = list.at(1); } if (keyword == "INSTRUMENT") ui->instrumentNameLineEdit->setText(keyvalue); if (keyword == "NCHIPS") { ui->numchipSpinBox->setValue(keyvalue.toInt()); numChips = keyvalue.toInt(); } if (keyword == "OBSLAT") ui->latitudeLineEdit->setText(keyvalue); if (keyword == "OBSLONG") ui->longitudeLineEdit->setText(keyvalue); if (keyword == "PIXSCALE") ui->plateScaleLineEdit->setText(keyvalue); // if (keyword == "GAIN") ui->gainLineEdit->setText(keyvalue); if (keyword == "OVSCANX1") ui->overscanxMinLineEdit->setText(keyvalue); if (keyword == "OVSCANX2") ui->overscanxMaxLineEdit->setText(keyvalue); if (keyword == "OVSCANY1") ui->overscanyMinLineEdit->setText(keyvalue); if (keyword == "OVSCANY2") ui->overscanyMaxLineEdit->setText(keyvalue); if (keyword == "CUTX") ui->startxLineEdit->setText(keyvalue); if (keyword == "CUTY") ui->startyLineEdit->setText(keyvalue); if (keyword == "SIZEX") ui->sizexLineEdit->setText(keyvalue); if (keyword == "SIZEY") ui->sizeyLineEdit->setText(keyvalue); if (keyword == "REFPIXX") ui->crpix1LineEdit->setText(keyvalue); if (keyword == "REFPIXY") ui->crpix2LineEdit->setText(keyvalue); if (keyword == "TYPE") { if (keyvalue == "OPT") ui->instrumentTypeComboBox->setCurrentIndex(0); else if (keyvalue == "NIR") ui->instrumentTypeComboBox->setCurrentIndex(1); else if (keyvalue == "NIRMIR") ui->instrumentTypeComboBox->setCurrentIndex(2); else if (keyvalue == "MIR") ui->instrumentTypeComboBox->setCurrentIndex(3); else ui->instrumentTypeComboBox->setCurrentIndex(0); if (keyvalue == "OPT") ui->bayerCheckBox->setEnabled(true); else ui->bayerCheckBox->setDisabled(true); } if (keyword == "BAYER") { if (keyvalue == "N") ui->bayerCheckBox->setChecked(false); else { ui->bayerCheckBox->setChecked(true); ui->buttonFrame->show(); } } if (keyword == "FLIP") { if (keyvalue == "NOFLIP") ui->flipComboBox->setCurrentIndex(0); else if (keyvalue == "FLIPX") ui->flipComboBox->setCurrentIndex(1); else if (keyvalue == "FLIPY") ui->flipComboBox->setCurrentIndex(2); else if (keyvalue == "ROT180") ui->flipComboBox->setCurrentIndex(3); } } instrumentFile.close(); } } bool Instrument::compareChipNumbers() { bool comparison = true; int count = 0; for (auto &it: geometryNumList) { // skip the first four entries for overscans for NIR detectors if (ui->instrumentTypeComboBox->currentIndex() != 0 && count < 4) continue; if (numChips != it->text().toInt()) comparison = false; ++count; } return comparison; } void Instrument::altStream(QTextStream &stream, QString keyword, QString altValue) { stream << " if [ \"${"+keyword+"}\"_A = \"_A\" ]; then\n"; stream << " "+keyword+"="+altValue+"\n"; stream << " fi\n\n"; } void Instrument::getKey(QTextStream &stream, QString bashkey, QString fitsKey, QString mode) { if (mode.isEmpty()) { stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\"`\n"; } else if (mode == "cleanstring") { stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\" | ${P_CLEANSTRING}`\n"; } else if (mode == "cleancolon") { stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\" cleancolon`\n"; } else if (mode == "equinox") { // Remove first char if not numeric stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\" | sed 's/[^0-9.]//g'`\n"; } } void Instrument::truncateFITSkey(QString &key) { int length = key.length(); if (length == 8) return; if (length > 8) { key = key.left(8); return; } if (length < 8) { while (length < 8) { key = key.append(" "); length = key.length(); } } } void Instrument::timerConfigDone() { ui->saveConfigPushButton->setText("Save instrument config"); } void Instrument::on_clearPushButton_clicked() { QList lineeditList; lineeditList.append(ui->crpix1LineEdit); lineeditList.append(ui->crpix1NumLineEdit); lineeditList.append(ui->crpix2LineEdit); lineeditList.append(ui->crpix2NumLineEdit); // lineeditList.append(ui->gainLineEdit); lineeditList.append(ui->instrumentNameLineEdit); lineeditList.append(ui->latitudeLineEdit); lineeditList.append(ui->longitudeLineEdit); lineeditList.append(ui->optionalKeysLineEdit); lineeditList.append(ui->overscanxMaxLineEdit); lineeditList.append(ui->overscanxMaxNumLineEdit); lineeditList.append(ui->overscanxMinLineEdit); lineeditList.append(ui->overscanxMinNumLineEdit); lineeditList.append(ui->overscanyMaxLineEdit); lineeditList.append(ui->overscanyMaxNumLineEdit); lineeditList.append(ui->overscanyMinLineEdit); lineeditList.append(ui->overscanyMinNumLineEdit); lineeditList.append(ui->plateScaleLineEdit); lineeditList.append(ui->sizexLineEdit); lineeditList.append(ui->sizexNumLineEdit); lineeditList.append(ui->sizeyLineEdit); lineeditList.append(ui->sizeyNumLineEdit); lineeditList.append(ui->startxLineEdit); lineeditList.append(ui->startxNumLineEdit); lineeditList.append(ui->startyLineEdit); lineeditList.append(ui->startyNumLineEdit); // Clear line edits for (auto &it : lineeditList) { it->clear(); } } void Instrument::on_bayerCheckBox_clicked(bool checked) { if (checked) { ui->bayerRGGBToolButton->setDown(true); // not effective? ui->buttonFrame->show(); } else ui->buttonFrame->hide(); } void Instrument::on_actionClose_triggered() { this->close(); } void Instrument::on_readRAWgeometryPushButton_clicked() { QString rawFileName = QFileDialog::getOpenFileName(this, tr("Select a CMOS RAW file"), QDir::homePath(), tr("CMOS RAW files (*.CR2 *.ARW *.DNG *.NEF *.PEF *.cr2 *.arw *.dng *.nef *.pef);; Other (*.*)")); // Try opening as RAW LibRaw rawProcessor; int ret = rawProcessor.open_file((rawFileName).toUtf8().data()); if (ret == LIBRAW_SUCCESS) { // Opened. Try unpacking bool unpack = rawProcessor.unpack(); if (unpack != LIBRAW_SUCCESS) { QMessageBox::warning( this, "Unknown RAW format", "The file chosen does not have a recognized CMOS RAW format."); return; } } #define S rawProcessor.imgdata.sizes // Extract pixels /* long naxis1Raw = S.raw_width; long naxis2Raw = S.raw_height; long naxis1 = S.iwidth; long naxis2 = S.iheight; */ ui->overscanxMinLineEdit->setText("1"); ui->overscanxMaxLineEdit->setText(QString::number(S.left_margin)); ui->overscanyMinLineEdit->setText("1"); ui->overscanyMaxLineEdit->setText(QString::number(S.top_margin)); // enforce even geometry if (S.iwidth % 2 != 0) { S.iwidth -= 1; S.left_margin += 1; } if (S.iheight % 2 != 0) { S.iheight -= 1; S.top_margin += 1; } ui->startxLineEdit->setText(QString::number(S.left_margin+1)); ui->startyLineEdit->setText(QString::number(S.top_margin+1)); ui->sizexLineEdit->setText(QString::number(S.iwidth)); ui->sizeyLineEdit->setText(QString::number(S.iheight)); ui->crpix1LineEdit->setText(QString::number(S.iwidth/2)); ui->crpix2LineEdit->setText(QString::number(S.iheight/2)); } THELI-3.1.3/src/instrumentdefinition.h000066400000000000000000000042601417631501300176070ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef INSTRUMENT_H #define INSTRUMENT_H #include #include #include #include #include #include namespace Ui { class Instrument; } class Instrument : public QMainWindow { Q_OBJECT public: explicit Instrument(QWidget *parent = nullptr); ~Instrument(); private slots: void paintNumLineEdits(QString geometry); void on_numchipSpinBox_valueChanged(int arg1); void validate(QString arg1); void on_saveConfigPushButton_clicked(); void on_instrumentTypeComboBox_currentIndexChanged(int index); void on_loadConfigPushButton_clicked(); void toggle_bayer_ToolButtons(); void timerConfigDone(); void on_clearPushButton_clicked(); void on_bayerCheckBox_clicked(bool checked); void on_actionClose_triggered(); void toggleFormatPushButton(); void on_readRAWgeometryPushButton_clicked(); private: Ui::Instrument *ui; QString thelidir; QString userdir; QList geometryList; QList geometryNumList; int numChips = 1; QString geometryToConfig(QString geometry); QString configToGeometry(QString config); void altStream(QTextStream &stream, QString keyword, QString altValue); QButtonGroup *bayerButtonGroup = new QButtonGroup(this); bool compareChipNumbers(); void getKey(QTextStream &stream, QString bashkey, QString fitsKey, QString mode = ""); void truncateFITSkey(QString &key); void applyStyleSheets(); }; #endif // INSTRUMENT_H THELI-3.1.3/src/instrumentdefinition.ui000066400000000000000000003743711417631501300200120ustar00rootroot00000000000000 Instrument 0 0 759 789 Setup for a new instrument configuration 0 0 0 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 0 0 0 255 255 255 0 0 0 255 255 255 170 170 170 0 0 0 212 212 212 255 255 220 0 0 0 0 0 0 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 0 0 0 255 255 255 0 0 0 255 255 255 170 170 170 0 0 0 212 212 212 255 255 220 0 0 0 85 85 85 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 85 85 85 255 255 255 85 85 85 170 170 170 170 170 170 0 0 0 170 170 170 255 255 220 0 0 0 true QFrame::Panel QFrame::Sunken 1 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame 0 0 0 Instrument name Type Number of chips Qt::Horizontal 186 20 Qt::WheelFocus The number of detectors used in this instrument. 1 999 Geo. latitude Geographic latitude of the observatory Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Scale [ " / pix ] The plate scale in arcsecond per pixel Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Geo. longitude Geographic longitude of the observatory. West counts negative. Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Qt::NoFocus A colored pixel mask commonly found in digital cameras and some amateur CCD cameras. Detector has Bayer matrix QFrame::NoFrame QFrame::Raised 0 0 0 0 0 0 44 44 44 44 Qt::NoFocus 40 40 true true true 44 44 44 44 Qt::NoFocus 40 40 true true 44 44 44 44 Qt::NoFocus 40 40 true true 44 44 44 44 Qt::NoFocus 40 40 true true Suggested name structure: INSTRUMENT@TELESCOPE Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Qt::NoFocus The type determines which elements in the interface will be shown or hidden. Operative wavelength range. THELI will hide and show unrelevant and relevant parts, respectively. Optical Near-IR (1-2.5 micron) Near/mid-IR (1-5 micron) Mid-IR (>5 micron) Flip the WCS matrix to simplify astrometric solutions. ONLY IF CD MATRIX IS ABSENT IN RAW DATA Do not flip WCS Flip WCS horizontally Flip WCS vertically Rotate WCS by 180 deg Qt::Horizontal QSizePolicy::Fixed 18 20 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::NoFrame QFrame::Raised 0 Propagate keywords to new FITS headers A blank- or comma-separated list of keywords that should be propagated to the new FITS header. Qt::Vertical QSizePolicy::Fixed 20 10 Raw data format FITS true Typical data format of a commercial CMOS camera RAW (*.CR2, *.ARW, *.DNG etc) Load a CMOS RAW file and auto-fill the geometry Load RAW geometry from file ... 75 true (1) General properties 0 75 true (2) Detector geometries (FITS only; geometry of RAW formats must be auto-loaded) 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 50 false true QFrame::NoFrame 0 Overscan xmin Blank-separated list, as many entries as detectors The min and max overscan pixels. If the camera has no overscan, enter 0. 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Overscan xmax Blank-separated list, as many entries as detectors The min and max overscan pixels. If the camera has no overscan, enter 0. 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Overscan ymin Blank-separated list, as many entries as detectors The min and max overscan pixels. If the camera has no overscan, enter 0. 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Overscan ymax Blank-separated list, as many entries as detectors The min and max overscan pixels. If the camera has no overscan, enter 0. 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Start x Blank-separated list, as many entries as detectors The first illuminated pixel along the horizontal axis 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Start y Blank-separated list, as many entries as detectors The first illuminated pixel along the vertical axis 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Size x Blank-separated list, as many entries as detectors The number of illuminated pixels along the horizontal axis 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Size y Blank-separated list, as many entries as detectors The number of illuminated pixels along the vertical axis 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true CRPIX1 Blank-separated list, as many entries as detectors 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true CRPIX2 Blank-separated list, as many entries as detectors 60 0 60 16777215 Qt::NoFocus The number of entries made to the left. Must match the number of chips. 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Qt::Vertical QSizePolicy::Fixed 20 10 Qt::Horizontal 188 20 Qt::NoFocus Select any existing instrument configuration as an example. Load config 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 Qt::NoFocus Resets all fields in this dialog. Reset all fields 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Qt::NoFocus Saves the configuration to $HOME/.theli/instrument_user/ Save config Qt::Vertical 20 0 0 0 759 23 File Close instrumentNameLineEdit latitudeLineEdit longitudeLineEdit plateScaleLineEdit overscanxMinLineEdit overscanxMaxLineEdit overscanyMinLineEdit overscanyMaxLineEdit startxLineEdit startyLineEdit sizexLineEdit sizeyLineEdit crpix1LineEdit crpix2LineEdit optionalKeysLineEdit THELI-3.1.3/src/iview/000077500000000000000000000000001417631501300142765ustar00rootroot00000000000000THELI-3.1.3/src/iview/actions.cc000066400000000000000000000260201417631501300162450ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "iview.h" #include "ui_iview.h" #include "ui_ivfinderdockwidget.h" void IView::checkFinder() { if (!finderdw->isVisible()) return; // Both name fields empty if (finderdw->ui->targetNameSiderealLineEdit->text().isEmpty() && finderdw->ui->targetNameNonsiderealLineEdit->text().isEmpty() && !finderdw->ui->targetAlphaLineEdit->text().isEmpty() && !finderdw->ui->targetDeltaLineEdit->text().isEmpty() ) { finderdw->bypassResolver(); } // sidereal field empty, nonsidereal not empty if (!finderdw->ui->targetNameNonsiderealLineEdit->text().isEmpty() && finderdw->ui->targetNameSiderealLineEdit->text().isEmpty()) { finderdw->on_MPCresolverToolButton_clicked(); } // sidereal field not empty, nonsidereal empty, coords empty if (!finderdw->ui->targetNameSiderealLineEdit->text().isEmpty() && finderdw->ui->targetNameNonsiderealLineEdit->text().isEmpty()) { if (finderdw->ui->targetAlphaLineEdit->text().isEmpty() ||finderdw->ui->targetDeltaLineEdit->text().isEmpty()) { finderdw->on_locatePushButton_clicked(); } if (!finderdw->ui->targetAlphaLineEdit->text().isEmpty() && !finderdw->ui->targetDeltaLineEdit->text().isEmpty()) { finderdw->bypassResolver(); } } } void IView::checkFinderBypass() { if (!finderdw->isVisible()) return; finderdw->bypassResolver(); } void IView::previousAction_triggered() { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (currentId > 0) { currentId --; if (displayMode == "FITSmonochrome") loadFITS("", currentId); else if (displayMode == "CLEAR") loadFITS("", currentId); else if (displayMode.contains("SCAMP")) loadPNG("", currentId); else if (displayMode == "MEMview") { // Check if the selected image is active. If not, search for one while (myImageList[currentId]->activeState == MyImage::INACTIVE && currentId > 0) --currentId; loadFromRAM(myImageList[currentId], 0); } ui->actionNext->setEnabled(true); ui->actionEnd->setEnabled(true); ui->actionForward->setEnabled(true); } if (currentId == 0) { ui->actionPrevious->setDisabled(true); ui->actionStart->setDisabled(true); ui->actionBack->setDisabled(true); } showReferenceCat(); showSourceCat(); timer->stop(); ui->actionBack->setChecked(false); ui->actionForward->setChecked(false); emit currentlyDisplayedIndex(currentId); checkFinder(); } void IView::nextAction_triggered() { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (currentId < numImages-1) { currentId ++; if (displayMode == "FITSmonochrome") loadFITS("", currentId); else if (displayMode == "CLEAR") loadFITS("", currentId); else if (displayMode.contains("SCAMP")) loadPNG("", currentId); else if (displayMode == "MEMview") { // Check if the selected image is active. If not, search for one while (currentId < numImages-1 && myImageList[currentId]->activeState == MyImage::INACTIVE) ++currentId; loadFromRAM(myImageList[currentId], 0); } ui->actionPrevious->setEnabled(true); ui->actionStart->setEnabled(true); ui->actionBack->setEnabled(true); } if (currentId == numImages-1) { ui->actionNext->setDisabled(true); ui->actionEnd->setDisabled(true); ui->actionForward->setDisabled(true); } showReferenceCat(); showSourceCat(); timer->stop(); ui->actionBack->setChecked(false); ui->actionForward->setChecked(false); emit currentlyDisplayedIndex(currentId); checkFinder(); } void IView::forwardAction_triggered() { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (ui->actionForward->isChecked()) timer->start(1000/speedSpinBox->value()); else return; if (currentId < numImages - 1 && ui->actionForward->isChecked()) { ui->actionBack->setChecked(false); currentId ++; if (displayMode == "FITSmonochrome") loadFITS("", currentId); else if (displayMode == "CLEAR") loadFITS("", currentId); else if (displayMode.contains("SCAMP")) loadPNG("", currentId); else if (displayMode == "MEMview") { // Check if the selected image is active. If not, search for one while (currentId < numImages-1 && myImageList[currentId]->activeState == MyImage::INACTIVE) ++currentId; loadFromRAM(myImageList[currentId], 0); } ui->actionPrevious->setEnabled(true); ui->actionStart->setEnabled(true); } if (currentId == numImages-1) { timer->stop(); ui->actionBack->setChecked(false); ui->actionBack->setEnabled(true); ui->actionForward->setChecked(false); ui->actionForward->setDisabled(true); ui->actionNext->setDisabled(true); ui->actionEnd->setDisabled(true); } showReferenceCat(); showSourceCat(); emit currentlyDisplayedIndex(currentId); checkFinder(); } void IView::backAction_triggered() { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (ui->actionBack->isChecked()) timer->start(1000/speedSpinBox->value()); else return; if (currentId > 0 && ui->actionBack->isChecked()) { ui->actionForward->setChecked(false); currentId --; if (displayMode == "FITSmonochrome") loadFITS("", currentId); else if (displayMode == "CLEAR") loadFITS("", currentId); else if (displayMode.contains("SCAMP")) loadPNG("", currentId); else if (displayMode == "MEMview") { // Check if the selected image is active. If not, search for one while (currentId > 0 && myImageList[currentId]->activeState == MyImage::INACTIVE) --currentId; loadFromRAM(myImageList[currentId], 0); } ui->actionNext->setEnabled(true); ui->actionEnd->setEnabled(true); } if (currentId == 0) { timer->stop(); ui->actionBack->setChecked(false); ui->actionBack->setDisabled(true); ui->actionForward->setChecked(false); ui->actionForward->setEnabled(true); ui->actionPrevious->setDisabled(true); ui->actionStart->setDisabled(true); } showReferenceCat(); showSourceCat(); emit currentlyDisplayedIndex(currentId); checkFinder(); } void IView::startAction_triggered() { // Leave if no image is displayed if (scene->items().isEmpty()) return; currentId = 0; if (displayMode == "FITSmonochrome") loadFITS("", currentId); else if (displayMode == "CLEAR") loadFITS("", currentId); else if (displayMode.contains("SCAMP")) loadPNG("", currentId); else if (displayMode == "MEMview") { // Check if the selected image is active. If not, search for one while (myImageList[currentId]->activeState == MyImage::INACTIVE && currentId < numImages-1) ++currentId; loadFromRAM(myImageList[currentId], 0); } ui->actionNext->setEnabled(true); ui->actionForward->setEnabled(true); ui->actionEnd->setEnabled(true); ui->actionStart->setDisabled(true); ui->actionPrevious->setDisabled(true); ui->actionBack->setDisabled(true); showReferenceCat(); showSourceCat(); timer->stop(); ui->actionBack->setChecked(false); ui->actionForward->setChecked(false); emit currentlyDisplayedIndex(currentId); checkFinder(); } void IView::endAction_triggered() { // Leave if no image is displayed if (scene->items().isEmpty()) return; currentId = numImages - 1; if (displayMode == "FITSmonochrome") loadFITS("", currentId); else if (displayMode == "CLEAR") loadFITS("", currentId); else if (displayMode.contains("SCAMP")) loadPNG("", currentId); else if (displayMode == "MEMview") { // Check if the selected image is active. If not, search for one while (myImageList[currentId]->activeState == MyImage::INACTIVE && currentId > 0) --currentId; loadFromRAM(myImageList[currentId], 0); } ui->actionNext->setDisabled(true); ui->actionForward->setDisabled(true); ui->actionEnd->setDisabled(true); ui->actionStart->setEnabled(true); ui->actionPrevious->setEnabled(true); ui->actionBack->setEnabled(true); showReferenceCat(); showSourceCat(); timer->stop(); ui->actionBack->setChecked(false); ui->actionForward->setChecked(false); emit currentlyDisplayedIndex(currentId); checkFinder(); } void IView::on_actionDragMode_triggered() { setMiddleMouseMode("DragMode"); // exclusive button group in c'tor does not work! emit middleMouseModeChanged("DragMode"); } void IView::on_actionSkyMode_triggered() { setMiddleMouseMode("SkyMode"); // exclusive button group in c'tor does not work! emit middleMouseModeChanged("SkyMode"); } void IView::on_actionWCSMode_triggered() { setMiddleMouseMode("WCSMode"); // exclusive button group in c'tor does not work! emit middleMouseModeChanged("WCSMode"); } void IView::on_actionMaskingMode_triggered() { setMiddleMouseMode("MaskingMode"); // exclusive button group in c'tor does not work! emit middleMouseModeChanged("MaskingMode"); } void IView::on_actionImage_statistics_triggered() { if (statdw->isVisible()) { removeDockWidget(statdw); statdw->hide(); } else { statdw->init(); statdw->setFloating(false); statdw->raise(); statdw->show(); } } void IView::on_actionFinder_triggered() { if (finderdw->isVisible()) { removeDockWidget(finderdw); finderdw->hide(); } else { finderdw->setFloating(false); finderdw->raise(); finderdw->show(); finderdw->ui->targetNameSiderealLineEdit->setFocus(); } } void IView::on_actionRedshift_triggered() { if (zdw->isVisible()) { clearAxes(); removeDockWidget(zdw); zdw->hide(); } else { // Do not display the dialog if no image is loaded if (!currentMyImage) { ui->actionRedshift->setChecked(false); return; } zdw->setFloating(false); zdw->raise(); zdw->show(); zdw->init(); updateAxes(); } } THELI-3.1.3/src/iview/constructors.cc000066400000000000000000000730631417631501300173660ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "iview.h" #include "ui_iview.h" #include "../functions.h" #include "mygraphicsview.h" #include "mygraphicsellipseitem.h" #include "mygraphicsscene.h" #include "ui_ivconfdockwidget.h" #include "ui_ivcolordockwidget.h" #include "ui_ivredshiftdockwidget.h" #include "dockwidgets/ivscampdockwidget.h" #include "dockwidgets/ivcolordockwidget.h" #include "dockwidgets/ivredshiftdockwidget.h" #include "../tools/tools.h" #include "fitsio2.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Various constructors // Open the window without loading an image // Not sure I'm using that anywhere // mode = CLEAR IView::IView(QWidget *parent) : QMainWindow(parent), displayMode("CLEAR"), ui(new Ui::IView) { // qDebug() << "mode 1"; ui->setupUi(this); initGUI(); icdw->zoom2scale(zoomLevel); // get a list of all FITS files in the current directory QDir dir = dir.current(); dirName = dir.absolutePath(); filterName = "*.fits"; setImageList(filterName); makeConnections(); switchMode(); initGUIstep2(); } // MEMview, single MyImage IView::IView(QString mode, QWidget *parent) : QMainWindow(parent), displayMode(mode), // "MEMview", set externally ui(new Ui::IView) { ui->setupUi(this); initGUI(); // Hide redshift action ui->actionRedshift->setVisible(false); // qDebug() << "mode memview single image:" << mode; icdw->zoom2scale(zoomLevel); /* // get a list of all FITS files in the current directory QDir dir = dir.current(); dirName = dir.absolutePath(); filterName = "*.fits"; setImageList(filterName); */ makeConnections(); switchMode(); initGUIstep2(); fromMemory = true; // Can't use these in memory mode (ensuring internal consistency, and avoiding very complex code) // filterLabel->hide(); // filterLineEdit->hide(); } // MEMview, list of MyImages IView::IView(QString mode, QList &list, QString dirname, QWidget *parent) : QMainWindow(parent), displayMode(mode), ui(new Ui::IView) { ui->setupUi(this); initGUI(); // Hide redshift action ui->actionRedshift->setVisible(false); // qDebug() << "mode memview list of images:" << mode; icdw->zoom2scale(zoomLevel); myImageList = list; numImages = myImageList.length(); setImageListFromMemory(); dirName = dirname; fromMemory = true; // 'currentId' is initialised externally in memoryViewer /* // get a list of all FITS files in the current directory QDir dir = dir.current(); dirName = dir.absolutePath(); filterName = "*.fits"; setImageList(filterName); */ makeConnections(); switchMode(); initGUIstep2(); // Can't use these in memory mode (ensuring internal consistency, and avoiding very complex code) // filterLabel->hide(); // filterLineEdit->hide(); } // FITS viewer, commandline invocation, with or without an argument // mode == FITSmonochrome IView::IView(QString mode, QString name, QWidget *parent) : QMainWindow(parent), displayMode(mode), ui(new Ui::IView) { ui->setupUi(this); initGUI(); if (displayMode == "FITSmonochrome") { icdw->zoom2scale(zoomLevel); QFileInfo fileInfo(name); QString suffix = fileInfo.suffix(); QDir dir; if (suffix == "") dir = dir.current(); else dir = fileInfo.absoluteDir(); dirName = dir.absolutePath(); filterName = "*.fits"; setImageList(filterName); makeConnections(); switchMode(); currentFileName = name; if (!name.isEmpty()) loadFITS(name); } else if (displayMode == "SCAMP") { dirName = name; scampInteractiveMode = true; filterName = "*.png"; setImageList(filterName); makeConnections(); switchMode(); currentId = 0; loadPNG("", currentId); } else if (displayMode == "SCAMP_VIEWONLY") { // just to display the plots, whenever dirName = name; scampInteractiveMode = false; filterName = "*.png"; setImageList(filterName); makeConnections(); switchMode(); currentId = 0; loadPNG("", currentId); } // TODO: if no refcat subdir found then hide the sourcecat / refcat buttons initGUIstep2(); } /* // FITS viewer, commandline invocation, with or without an argument // mode == FITSmonochrome IView::IView(QString mode, QString fileName, QWidget *parent) : QMainWindow(parent), displayMode(mode), ui(new Ui::IView) { ui->setupUi(this); initGUI(); QFileInfo fileInfo(fileName); QString suffix = fileInfo.suffix(); QDir dir; if (suffix == "") dir = dir.current(); else dir = fileInfo.absoluteDir(); dirName = dir.absolutePath(); filterName = "*.fits"; setImageList(filterName); makeConnections(); switchMode(); if (!fileName.isEmpty()) loadFITS(fileName); // TODO: if no refcat subdir found then hide the sourcecat / refcat buttons initGUIstep2(); } */ /* // Scamp checkplot viewer // mode == "SCAMP" IView::IView(QString mode, QString dirname, QWidget *parent) : QMainWindow(parent), dirName(dirname), displayMode(mode), scampInteractiveMode(true), ui(new Ui::IView) { ui->setupUi(this); initGUI(); // get a list of all PNG files in this directory filterName = "*.png"; setImageList(filterName); makeConnections(); currentId = 0; switchMode(); loadPNG("", currentId); initGUIstep2(); } */ // Used by imstatistics (opening iview without data point selection) // mode = FITSmonochrome IView::IView(QString mode, QString dirname, QString filter, QWidget *parent) : QMainWindow(parent), dirName(dirname), filterName(filter), displayMode(mode), ui(new Ui::IView) { ui->setupUi(this); initGUI(); filterLineEdit->setText(filterName); // Hide redshift action ui->actionRedshift->setVisible(false); icdw->zoom2scale(zoomLevel); // get a list of all FITS files in this directory setImageList(filterName); pageLabel->setText("? / "+QString::number(numImages)); makeConnections(); switchMode(); if (numImages > 0) { currentFileName = imageList[0]; loadFITS(dirName+'/'+imageList[0]); } initGUIstep2(); } // Used by imstatistics (opening iview with a data point selected) // mode = FITSmonochrome IView::IView(QString mode, QString dirname, QString fileName, QString filter, QWidget *parent) : QMainWindow(parent), dirName(dirname), filterName(filter), currentFileName(fileName), displayMode(mode), ui(new Ui::IView) { ui->setupUi(this); initGUI(); // Hide redshift action ui->actionRedshift->setVisible(false); // qDebug() << "mode imstatistics 2:" << mode << filterName; filterLineEdit->setText(filterName); icdw->zoom2scale(zoomLevel); // get a list of all FITS files in this directory setImageList(filterName); pageLabel->setText("? / "+QString::number(numImages)); makeConnections(); switchMode(); loadFITS(dirName+'/'+fileName); initGUIstep2(); } // Displaying color images // mode = FITScolor IView::IView(QString mode, QString dirname, QString rChannel, QString gChannel, QString bChannel, float factorR, float factorB, QWidget *parent) : QMainWindow(parent), dirName(dirname), filterName("*.fits"), displayMode(mode), ui(new Ui::IView), ChannelR(rChannel), ChannelG(gChannel), ChannelB(bChannel) { ui->setupUi(this); initGUI(); // Hide redshift action ui->actionRedshift->setVisible(false); // The list of the three FITS images imageList << ChannelR << ChannelG << ChannelB; numImages = imageList.length(); // Update the dockwidget colordw->colorFactorZeropoint[0] = factorR; colordw->colorFactorZeropoint[1] = 1.0; colordw->colorFactorZeropoint[2] = factorB; colordw->colorFactorApplied[0] = factorR; colordw->colorFactorApplied[1] = 1.0; colordw->colorFactorApplied[2] = factorB; colordw->ui->redFactorLineEdit->setText(QString::number(factorR, 'f', 3)); colordw->ui->blueFactorLineEdit->setText(QString::number(factorB, 'f', 3)); makeConnections(); switchMode(); loadColorFITS(icdw->zoom2scale(zoomLevel)); initGUIstep2(); /* ui->toolBar->addWidget(redResetPushButton); ui->toolBar->addWidget(redFactorLineEdit); ui->toolBar->addWidget(redSlider); ui->toolBar->addSeparator(); ui->toolBar->addWidget(blueResetPushButton); ui->toolBar->addWidget(blueFactorLineEdit); ui->toolBar->addWidget(blueSlider); redSlider->setMinimum(0); redSlider->setMaximum(sliderSteps); redSlider->setValue(sliderSteps/2); redSlider->setMinimumWidth(150); redSlider->setMaximumWidth(250); redFactorLineEdit->setText(QString::number(factorR, 'f', 3)); redFactorLineEdit->setMinimumWidth(120); redFactorLineEdit->setMaximumWidth(120); redResetPushButton->setText("Reset red factor"); blueSlider->setMinimum(0); blueSlider->setMaximum(sliderSteps); blueSlider->setValue(sliderSteps/2); blueSlider->setMinimumWidth(150); blueSlider->setMaximumWidth(250); blueFactorLineEdit->setText(QString::number(factorB, 'f', 3)); blueFactorLineEdit->setMinimumWidth(120); blueFactorLineEdit->setMaximumWidth(120); blueResetPushButton->setText("Reset blue factor"); */ } // Force the user to make a decision in case we are in interactive mode // viewing the scamp checkplots, and the user wants to close the dialog // by closing the window directly, not by accepting or rejecting a solution void IView::closeEvent(QCloseEvent *event) { // qDebug() << fitsData.capacity(); // fitsData.clear(); // fitsData.squeeze(); timer->stop(); if (scampInteractiveMode && !scampCorrectlyClosed) { QMessageBox msgBox; msgBox.setText("Accept or reject the astrometric solution."); msgBox.setInformativeText("THELI needs to know whether to update the FITS headers with " "the astrometric solution or not. If in doubt, click reject. " "You can re-run the astrometric solution at any time. \n\n"); QAbstractButton *pButtonAccept = msgBox.addButton(tr("Accept"), QMessageBox::YesRole); QAbstractButton *pButtonReject = msgBox.addButton(tr("Reject"), QMessageBox::YesRole); QAbstractButton *pButtonAgain = msgBox.addButton(tr("Show me again"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton()==pButtonAccept) emit solutionAcceptanceState(true); else if (msgBox.clickedButton()==pButtonReject) emit solutionAcceptanceState(false); else if (msgBox.clickedButton()==pButtonAgain) { event->ignore(); return; } } writePreferenceSettings(); emit closed(); event->accept(); } IView::~IView() { if (dataIntSet) { delete [] dataInt; dataInt = nullptr; } if (dataIntRSet) { delete [] dataIntR; dataIntR = nullptr; } if (dataIntGSet) { delete [] dataIntG; dataIntG = nullptr; } if (dataIntBSet) { delete [] dataIntB; dataIntB = nullptr; } if (dataBinnedIntSet) { delete [] dataBinnedInt; dataBinnedInt = nullptr; } if (dataBinnedIntRSet) { delete [] dataBinnedIntR; dataBinnedIntR = nullptr; } if (dataBinnedIntGSet) { delete [] dataBinnedIntG; dataBinnedIntG = nullptr; } if (dataBinnedIntBSet) { delete [] dataBinnedIntB; dataBinnedIntB = nullptr; } // It appears that 'scene' does not take ownership of the pixmapitem. // nullptr if e.g. closing the GUI without saving the images. Don't know how that can be related, but here we go ... if (pixmapItem != nullptr) { delete pixmapItem; pixmapItem = nullptr; } // if (binnedPixmapItem != nullptr) { // delete binnedPixmapItem; // binnedPixmapItem = nullptr; // } if (magnifiedPixmapItem != nullptr) { // delete magnifiedPixmapItem; // magnifiedPixmapItem = nullptr; } delete ui; // if (icdwDefined) delete icdw; // if (scampdwDefined) delete scampdw; if (!fromMemory) { if (wcsInit) wcsfree(wcs); // wcs is a pointer to MyImage if loaded from memory, hence we must not delete it here! } // delete wcs; delete myGraphicsView; delete scene; myGraphicsView = nullptr; scene = nullptr; } void IView::makeConnections() { connect(ui->actionClose, &QAction::triggered, this, &IView::close); connect(ui->actionLoadImageFromDrive, &QAction::triggered, this, &IView::loadImage); connect(ui->actionStart, &QAction::triggered, this, &IView::startAction_triggered); connect(ui->actionEnd, &QAction::triggered, this, &IView::endAction_triggered); connect(ui->actionPrevious, &QAction::triggered, this, &IView::previousAction_triggered); connect(ui->actionNext, &QAction::triggered, this, &IView::nextAction_triggered); connect(ui->actionForward, &QAction::triggered, this, &IView::forwardAction_triggered); connect(ui->actionBack, &QAction::triggered, this, &IView::backAction_triggered); connect(ui->actionSourceCat, &QAction::triggered, this, &IView::showSourceCat); connect(ui->actionRefCat, &QAction::triggered, this, &IView::showReferenceCat); // myGraphicsView = new MyGraphicsView(this); myGraphicsView = new MyGraphicsView(); QPalette backgroundPalette; backgroundPalette.setColor(QPalette::Base, QColor("#000000")); myGraphicsView->setPalette(backgroundPalette); myGraphicsView->setMouseTracking(true); ui->graphicsLayout->addWidget(myGraphicsView); connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::showCurrentMousePos); connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::collectLocalStatisticsSample); connect(myGraphicsView, &MyGraphicsView::rightDragTravelled, this, &IView::adjustBrightnessContrast); connect(myGraphicsView, &MyGraphicsView::leftDragTravelled, this, &IView::drawSeparationVector); connect(myGraphicsView, &MyGraphicsView::middleSkyDragTravelled, this, &IView::drawSkyCircle); connect(myGraphicsView, &MyGraphicsView::middleMaskingDragTravelled, this, &IView::drawMaskingPolygon); connect(myGraphicsView, &MyGraphicsView::middleWCSTravelled, this, &IView::updateCRPIX); connect(myGraphicsView, &MyGraphicsView::middleWCSreleased, this, &IView::updateCRPIXFITS); connect(myGraphicsView, &MyGraphicsView::middlePressResetCRPIX, this, &IView::middlePressResetCRPIXreceived); connect(myGraphicsView, &MyGraphicsView::rightPress, this, &IView::initDynrangeDrag); connect(myGraphicsView, &MyGraphicsView::leftPress, this, &IView::initSeparationVector); connect(myGraphicsView, &MyGraphicsView::leftPress, this, &IView::sendStatisticsCenter); connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, this, &IView::clearSeparationVector); connect(myGraphicsView, &MyGraphicsView::middleButtonReleased, this, &IView::appendSkyCircle); connect(myGraphicsView, &MyGraphicsView::rightButtonReleased, this, &IView::redrawSkyCirclesAndCats); connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, this, &IView::updateSkyCircles); connect(myGraphicsView, &MyGraphicsView::mouseEnteredView, icdw, &IvConfDockWidget::mouseEnteredViewReceived); connect(myGraphicsView, &MyGraphicsView::mouseLeftView, icdw, &IvConfDockWidget::mouseLeftViewReceived); connect(myGraphicsView, &MyGraphicsView::viewportChanged, this, &IView::viewportChangedReceived); connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::updateNavigatorMagnifiedReceived); connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::showWavelength); connect(myGraphicsView, &MyGraphicsView::leftDragTravelled, &restframeAxis, &MyAxis::redshiftSpectrum); connect(myGraphicsView, &MyGraphicsView::leftDragTravelled, &spectrumAxis, &MyAxis::redshiftSpectrum); connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, &restframeAxis, &MyAxis::closeRedshift); connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, &spectrumAxis, &MyAxis::closeRedshift); connect(scene, &MyGraphicsScene::itemDeleted, this, &IView::updateSkyCircles); connect(scene, &MyGraphicsScene::mouseLeftScene, icdw, &IvConfDockWidget::mouseLeftViewReceived); connect(wcsdw, &IvWCSDockWidget::CDmatrixChanged, this, &IView::updateCDmatrix); connect(wcsdw, &IvWCSDockWidget::CDmatrixChangedFITS, this, &IView::updateCDmatrixFITS); connect(wcsdw, &IvWCSDockWidget::CDmatrixChanged, icdw, &IvConfDockWidget::drawCompass); connect(statdw, &IvStatisticsDockWidget::visibilityChanged, this, &IView::updateStatisticsButton); connect(zdw, &IvRedshiftDockWidget::visibilityChanged, this, &IView::updateRedshiftButton); connect(finderdw, &IvFinderDockWidget::visibilityChanged, this, &IView::updateFinderButton); connect(finderdw, &IvFinderDockWidget::targetResolved, this, &IView::targetResolvedReceived); connect(finderdw, &IvFinderDockWidget::clearTargetResolved, scene, &MyGraphicsScene::removeCrosshair); connect(timer, &QTimer::timeout, this, &IView::forwardAction_triggered); connect(timer, &QTimer::timeout, this, &IView::backAction_triggered); connect(this, &IView::middleMouseModeChanged, myGraphicsView, &MyGraphicsView::updateMiddleMouseMode); connect(this, &IView::updateNavigatorMagnified, icdw, &IvConfDockWidget::updateNavigatorMagnifiedReceived); connect(this, &IView::updateNavigatorBinned, icdw, &IvConfDockWidget::updateNavigatorBinnedReceived); connect(this, &IView::updateNavigatorBinnedViewport, icdw, &IvConfDockWidget::updateNavigatorBinnedViewportReceived); connect(this, &IView::statisticsSampleAvailable, statdw, &IvStatisticsDockWidget::statisticsSampleReceiver); connect(this, &IView::statisticsSampleColorAvailable, statdw, &IvStatisticsDockWidget::statisticsSampleColorReceiver); connect(filterLineEdit, &QLineEdit::textChanged, this, &IView::filterLineEdit_textChanged); connect(icdw->binnedGraphicsView, &MyBinnedGraphicsView::fovRectCenterChanged, this, &IView::fovCenterChangedReceiver); connect(this, &IView::updateNavigatorBinnedWCS, icdw, &IvConfDockWidget::receiveWCS); connect(this, &IView::clearMagnifiedScene, icdw, &IvConfDockWidget::clearMagnifiedSceneReceiver); connect(this, &IView::newImageLoaded, this, &IView::updateAxes); connect(this, &IView::newImageLoaded, this, &IView::resetRedshift); connect(this, &IView::wavelengthUpdated, zdw, &IvRedshiftDockWidget::showWavelength); connect(&restframeAxis, &MyAxis::redshiftRecomputed, this, &IView::updateAxes); connect(&spectrumAxis, &MyAxis::redshiftRecomputed, this, &IView::updateAxes); connect(&spectrumAxis, &MyAxis::redshiftUpdated, zdw, &IvRedshiftDockWidget::redshiftUpdatedReceiver); } void IView::switchMode(QString mode) { if (!mode.isEmpty()) displayMode = mode; ui->actionClose->setVisible(true); if (displayMode.contains("SCAMP")) { this->setWindowTitle("iView --- Scamp check plots"); // Disable file menu. Must stay within interactive mode. Also, 'close' will cause segfault. ui->menuFile->setVisible(false); middleMouseActionGroup->setVisible(false); // many of the settings below are handled by the modeStackedWidget already! ui->actionSourceCat->setVisible(false); ui->actionRefCat->setVisible(false); ui->actionBack->setVisible(false); ui->actionForward->setVisible(false); pageLabel->show(); speedLabel->hide(); speedSpinBox->hide(); ui->actionBack->setEnabled(true); ui->actionForward->setEnabled(true); ui->actionPrevious->setEnabled(true); ui->actionNext->setEnabled(true); ui->actionStart->setEnabled(true); ui->actionEnd->setEnabled(true); } else if (displayMode == "FITSmonochrome") { this->setWindowTitle("iView --- FITS file viewer"); middleMouseActionGroup->setVisible(true); ui->actionSourceCat->setVisible(true); ui->actionRefCat->setVisible(true); pageLabel->show(); speedLabel->show(); speedSpinBox->show(); ui->actionBack->setEnabled(true); ui->actionForward->setEnabled(true); ui->actionPrevious->setEnabled(true); ui->actionNext->setEnabled(true); ui->actionStart->setEnabled(true); ui->actionEnd->setEnabled(true); } else if (displayMode == "MEMview") { this->setWindowTitle("iView --- Memory viewer"); middleMouseActionGroup->setVisible(true); ui->actionSourceCat->setVisible(true); ui->actionRefCat->setVisible(true); pageLabel->show(); speedLabel->show(); speedSpinBox->show(); ui->actionLoadImageFromDrive->setDisabled(true); ui->actionBack->setEnabled(true); ui->actionForward->setEnabled(true); ui->actionPrevious->setEnabled(true); ui->actionNext->setEnabled(true); ui->actionStart->setEnabled(true); ui->actionEnd->setEnabled(true); } else if (displayMode == "FITScolor") { this->setWindowTitle("iView --- FITS file viewer"); middleMouseActionGroup->setVisible(false); ui->actionSourceCat->setVisible(false); ui->actionRefCat->setVisible(false); pageLabel->hide(); speedLabel->hide(); speedSpinBox->hide(); ui->actionBack->setVisible(false); ui->actionForward->setVisible(false); ui->actionPrevious->setVisible(false); ui->actionNext->setVisible(false); ui->actionStart->setVisible(false); ui->actionEnd->setVisible(false); } else if (displayMode == "CLEAR") { this->setWindowTitle("iView --- FITS file viewer"); middleMouseActionGroup->setVisible(true); ui->actionBack->setDisabled(true); ui->actionForward->setDisabled(true); ui->actionPrevious->setDisabled(true); ui->actionNext->setDisabled(true); ui->actionStart->setDisabled(true); ui->actionEnd->setDisabled(true); ui->actionSourceCat->setDisabled(true); ui->actionRefCat->setDisabled(true); } // Also adjust the dockwidgets // NOT in SCAMP mode, because there it is not initialized! if (!displayMode.contains("SCAMP")) icdw->switchMode(displayMode); } void IView::initGUI() { addDockWidgets(); // Widgets must be alive early on // QRect rec = QApplication::desktop()->screenGeometry(); // deprecated in Qt5.14 QScreen *screen = QGuiApplication::screens().at(0); QRect rec = screen->geometry(); screenHeight = rec.height(); screenWidth = rec.width(); middleMouseActionGroup->setExclusive(true); middleMouseActionGroup->addAction(ui->actionDragMode); middleMouseActionGroup->addAction(ui->actionSkyMode); middleMouseActionGroup->addAction(ui->actionMaskingMode); middleMouseActionGroup->addAction(ui->actionWCSMode); ui->actionDragMode->setChecked(true); wcsdw->hide(); if (displayMode.contains("SCAMP")) { middleMouseActionGroup->setVisible(false); // NOTE: must add actions above before we can "hide" them simply by hiding the group } else { middleMouseActionGroup->setVisible(true); } readPreferenceSettings(); setWindowIcon(QIcon(":/icons/iview.png")); // QFile file(":/qss/default.qss"); // file.open(QFile::ReadOnly); // QString styleSheet = QString::fromLatin1(file.readAll()); // qApp->setStyleSheet(styleSheet); this->setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); } void IView::initGUIstep2() { // update the startDirName if (!startDirNameSet) { startDirName = dirName; startDirNameSet = true; } if (!displayMode.contains("SCAMP")) { // ui->toolBar->addWidget(speedLabel); // speedLabel->setText(" Frame rate"); ui->toolBar->addWidget(speedSpinBox); speedSpinBox->setValue(2); speedSpinBox->setMinimum(1); speedSpinBox->setMaximum(10); speedSpinBox->setSuffix(" Hz"); speedSpinBox->setToolTip("Frame rate for forward / backward playing"); ui->toolBar->addWidget(filterLabel); filterLabel->setText(" Filter"); ui->toolBar->addWidget(filterLineEdit); filterLineEdit->setStatusTip("Only these images will be selected when using the yellow navigation buttons at the top."); } pageLabel->setMaximumWidth(200); pageLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); ui->toolBar->addWidget(pageLabel); ui->toolBar->addSeparator(); QWidget* empty = new QWidget(); empty->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Preferred); ui->toolBar->addWidget(empty); } void IView::addDockWidgets() { setDockOptions(DockOption::AllowNestedDocks); if (displayMode == "FITSmonochrome" || displayMode == "MEMview") { icdw = new IvConfDockWidget(this); addDockWidget(Qt::LeftDockWidgetArea, icdw); icdw->setFloating(false); icdw->raise(); } else if (displayMode == "FITScolor") { icdw = new IvConfDockWidget(this); addDockWidget(Qt::LeftDockWidgetArea, icdw); icdw->setFloating(false); icdw->raise(); colordw = new IvColorDockWidget(this); addDockWidget(Qt::LeftDockWidgetArea, colordw); colordw->setFloating(false); colordw->raise(); } else if (displayMode == "CLEAR") { icdw = new IvConfDockWidget(this); addDockWidget(Qt::LeftDockWidgetArea, icdw); icdw->setFloating(false); icdw->raise(); } else if (displayMode == "SCAMP") { scampdw = new IvScampDockWidget(this); icdw = new IvConfDockWidget(this); addDockWidget(Qt::LeftDockWidgetArea, scampdw); scampdw->setFloating(false); icdw->hide(); scampdw->raise(); finderdw->hide(); statdw->hide(); zdw->hide(); } else if (displayMode == "SCAMP_VIEWONLY") { icdw = new IvConfDockWidget(this); icdw->hide(); finderdw->hide(); statdw->hide(); zdw->hide(); } // Connections if (displayMode == "SCAMP") { scampdwDefined = true; connect(scampdw, &IvScampDockWidget::solutionAcceptanceState, this, &IView::solutionAcceptanceStateReceived); } else if (displayMode == "SCAMP_VIEWONLY") { scampdwDefined = false; } else { icdwDefined = true; connect(icdw, &IvConfDockWidget::autoContrastPushButton_toggled, this, &IView::autoContrastPushButton_toggled_receiver); connect(icdw, &IvConfDockWidget::minmaxLineEdit_returnPressed, this, &IView::minmaxLineEdit_returnPressed_receiver); connect(icdw, &IvConfDockWidget::minmaxLineEdit_returnPressed, this, &IView::minmaxLineEdit_returnPressed_receiver); connect(icdw, &IvConfDockWidget::zoomFitPushButton_clicked, this, &IView::zoomFitPushButton_clicked_receiver); connect(icdw, &IvConfDockWidget::zoomInPushButton_clicked, this, &IView::zoomInPushButton_clicked_receiver); connect(icdw, &IvConfDockWidget::zoomOutPushButton_clicked, this, &IView::zoomOutPushButton_clicked_receiver); connect(icdw, &IvConfDockWidget::zoomZeroPushButton_clicked, this, &IView::zoomZeroPushButton_clicked_receiver); connect(icdw, &IvConfDockWidget::zoomFitPushButton_clicked, this, &IView::updateAxes); connect(icdw, &IvConfDockWidget::zoomInPushButton_clicked, this, &IView::updateAxes); connect(icdw, &IvConfDockWidget::zoomOutPushButton_clicked, this, &IView::updateAxes); connect(icdw, &IvConfDockWidget::zoomZeroPushButton_clicked, this, &IView::updateAxes); connect(icdw, &IvConfDockWidget::closeIview, this, &IView::close); } if (!displayMode.contains("SCAMP")) { addDockWidget(Qt::LeftDockWidgetArea, statdw); statdw->hide(); addDockWidget(Qt::LeftDockWidgetArea, finderdw); finderdw->hide(); addDockWidget(Qt::LeftDockWidgetArea, zdw); zdw->hide(); } } void IView::updateStatisticsButton() { if (statdw->isVisible()) ui->actionImage_statistics->setChecked(true); else ui->actionImage_statistics->setChecked(false); } void IView::updateRedshiftButton() { if (zdw->isVisible()) ui->actionRedshift->setChecked(true); else ui->actionRedshift->setChecked(false); } void IView::updateFinderButton() { if (finderdw->isVisible()) { ui->actionFinder->setChecked(true); } else { ui->actionFinder->setChecked(false); scene->removeCrosshair(); } } THELI-3.1.3/src/iview/dockwidgets/000077500000000000000000000000001417631501300166055ustar00rootroot00000000000000THELI-3.1.3/src/iview/dockwidgets/ivcolordockwidget.cc000066400000000000000000000124441417631501300226430ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivcolordockwidget.h" #include "ui_ivcolordockwidget.h" #include "../iview.h" #include #include #include IvColorDockWidget::IvColorDockWidget(IView *parent) : QDockWidget(parent), ui(new Ui::IvColorDockWidget) { ui->setupUi(this); iview = parent; ui->redSlider->setMinimum(0); ui->redSlider->setMaximum(sliderSteps); ui->redSlider->setValue(sliderSteps/2); // ui->redSlider->setMinimumWidth(150); // ui->redSlider->setMaximumWidth(250); // ui->redFactorLineEdit->setMinimumWidth(120); // ui->redFactorLineEdit->setMaximumWidth(120); // ui->redResetPushButton->setText("Reset"); ui->blueSlider->setMinimum(0); ui->blueSlider->setMaximum(sliderSteps); ui->blueSlider->setValue(sliderSteps/2); // ui->blueSlider->setMinimumWidth(150); // ui->blueSlider->setMaximumWidth(250); // ui->blueFactorLineEdit->setMinimumWidth(120); // ui->blueFactorLineEdit->setMaximumWidth(120); // ui->blueResetPushButton->setText("Reset"); connect(ui->blueFactorLineEdit, &QLineEdit::textChanged, this, &IvColorDockWidget::validate); connect(ui->redFactorLineEdit, &QLineEdit::textChanged, this, &IvColorDockWidget::validate); connect(ui->redFactorLineEdit, &QLineEdit::textEdited, this, &IvColorDockWidget::redFactorEdited); connect(ui->blueFactorLineEdit, &QLineEdit::textEdited, this, &IvColorDockWidget::blueFactorEdited); connect(ui->redSlider, &QSlider::sliderMoved, this, &IvColorDockWidget::redSliderMoved); connect(ui->blueSlider, &QSlider::sliderMoved, this, &IvColorDockWidget::blueSliderMoved); connect(this, &IvColorDockWidget::colorFactorChanged, iview, &IView::colorFactorChanged_receiver); connect(ui->G2referencesPushButton, &QPushButton::toggled, iview, &IView::showG2References); } IvColorDockWidget::~IvColorDockWidget() { delete ui; } void IvColorDockWidget::validate() { // Floating point validator QRegExp rf( "^[0-9]+[.]{0,1}[0-9]+" ); QValidator *validator = new QRegExpValidator( rf, this ); ui->blueFactorLineEdit->setValidator( validator ); ui->redFactorLineEdit->setValidator( validator ); } void IvColorDockWidget::sliderToText(int sliderValue, QString channel) { float sh = sliderSteps / 2.0; if (channel == "red") { colorFactorApplied[0] = colorFactorZeropoint[0] * pow(2., float(sliderValue-sh) / sh); ui->redFactorLineEdit->setText(QString::number(colorFactorApplied[0], 'f', 3)); } if (channel == "blue") { colorFactorApplied[2] = colorFactorZeropoint[2] * pow(2., float(sliderValue-sh) / sh); ui->blueFactorLineEdit->setText(QString::number(colorFactorApplied[2], 'f', 3)); } } void IvColorDockWidget::textToSlider(QString value, QString channel) { float sh = sliderSteps / 2.0; if (channel == "red") { int sliderValue = sh * ( log(value.toFloat() / colorFactorZeropoint[0]) / log(2.) + 1.); ui->redSlider->setValue(sliderValue); } if (channel == "blue") { int sliderValue = sh * ( log(value.toFloat() / colorFactorZeropoint[2]) / log(2.) + 1.); ui->blueSlider->setValue(sliderValue); } } void IvColorDockWidget::redSliderMoved(const int &sliderValue) { sliderToText(sliderValue, "red"); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::blueSliderMoved(const int &sliderValue) { sliderToText(sliderValue, "blue"); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::redFactorEdited(const QString &value) { textToSlider(value, "red"); colorFactorApplied[0] = value.toFloat(); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::blueFactorEdited(const QString &value) { textToSlider(value, "blue"); colorFactorApplied[2] = value.toFloat(); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::on_redResetPushButton_clicked() { ui->redSlider->setValue(sliderSteps/2.); ui->redFactorLineEdit->setText(QString::number(colorFactorZeropoint[0], 'f', 3)); colorFactorApplied[0] = colorFactorZeropoint[0]; emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::on_blueResetPushButton_clicked() { ui->blueSlider->setValue(sliderSteps/2.); ui->blueFactorLineEdit->setText(QString::number(colorFactorZeropoint[2], 'f', 3)); colorFactorApplied[2] = colorFactorZeropoint[2]; emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } THELI-3.1.3/src/iview/dockwidgets/ivcolordockwidget.h000066400000000000000000000036661417631501300225130ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVCOLORDOCKWIDGET_H #define IVCOLORDOCKWIDGET_H #include #include #include #include #include namespace Ui { class IvColorDockWidget; } class IView; // Forward declaration to access members class IvColorDockWidget : public QDockWidget { Q_OBJECT public: explicit IvColorDockWidget(IView *parent = 0); ~IvColorDockWidget(); Ui::IvColorDockWidget *ui; void textToSlider(QString value, QString channel); QVector colorFactorApplied = QVector(3, 1.0); // stores current RGB factors QVector colorFactorZeropoint = QVector(3, 1.0); // stores fixed RGB factors as determined by calibration IView *iview; private: void sliderToText(int sliderValue, QString channel); int sliderSteps = 100; signals: void colorFactorChanged(QString redFactor, QString blueFactor); void showG2references(bool checked); private slots: void blueSliderMoved(const int &sliderValue); void blueFactorEdited(const QString &value); void redSliderMoved(const int &sliderValue); void redFactorEdited(const QString &value); void validate(); void on_blueResetPushButton_clicked(); void on_redResetPushButton_clicked(); }; #endif // IVCOLORDOCKWIDGET_H THELI-3.1.3/src/iview/dockwidgets/ivcolordockwidget.ui000066400000000000000000000234561417631501300227000ustar00rootroot00000000000000 IvColorDockWidget 0 0 168 176 0 0 168 524287 QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Color calibration Qt::NoFocus Qt::Horizontal 0 0 252 252 252 241 37 64 252 252 252 241 37 64 241 37 64 241 37 64 true QFrame::Box QFrame::Plain 1 3 3 3 3 Qt::NoFocus Resets the blue factor to the determined value Reset Qt::Vertical 20 40 The reference sources used for color calibration (SDSS: red, PanSTARRS: cyan, ATLAS-REFCAT2: green, SKYMAPPER: yellow) Show G2 Sources true Qt::NoFocus Resets the red factor to the determined value Reset 0 0 252 252 252 25 25 255 252 252 252 25 25 255 25 25 255 25 25 255 true QFrame::Box QFrame::Plain 1 3 3 3 3 0 0 Blue color balance factor Qt::NoFocus Qt::Horizontal 0 0 Red color balance factor redFactorLineEdit blueFactorLineEdit G2referencesPushButton redResetPushButton blueResetPushButton redSlider blueSlider THELI-3.1.3/src/iview/dockwidgets/ivconfdockwidget.cc000066400000000000000000000346641417631501300224620ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivconfdockwidget.h" #include "ui_ivconfdockwidget.h" #include "../iview.h" #include #include IvConfDockWidget::IvConfDockWidget(IView *parent) : QDockWidget(parent), ui(new Ui::IvConfDockWidget) { ui->setupUi(this); iview = parent; // Populate the navigator widget QPalette backgroundPalette; backgroundPalette.setColor(QPalette::Base, QColor("#000000")); magnifiedGraphicsView = new MyMagnifiedGraphicsView(); magnifiedGraphicsView->setPalette(backgroundPalette); magnifiedGraphicsView->setMouseTracking(true); magnifiedGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); magnifiedGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); binnedGraphicsView = new MyBinnedGraphicsView(); binnedGraphicsView->setPalette(backgroundPalette); binnedGraphicsView->setMouseTracking(true); binnedGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); binnedGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // binnedGraphicsView->setRenderHint(QPainter::Antialiasing); // ui->navigatorStackedWidget->setContentsMargins(0,0,0,0); ui->binnedGraphicsLayout->insertWidget(0, binnedGraphicsView); ui->magnifiedGraphicsLayout->insertWidget(1, magnifiedGraphicsView); navigator_binned_nx = ui->binnedFrame->width(); navigator_binned_ny = ui->binnedFrame->height(); navigator_magnified_nx = ui->magnifiedFrame->width(); navigator_magnified_ny = ui->magnifiedFrame->height(); binnedGraphicsView->nx = navigator_binned_nx; binnedGraphicsView->ny = navigator_binned_ny; ui->quitPushButton->hide(); connect(binnedGraphicsView, &MyBinnedGraphicsView::currentMousePos, this, &IvConfDockWidget::showCurrentMousePosBinned); // connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftDragTravelled, this, &IView::drawSeparationVector); // connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftPress, this, &IView::initSeparationVector); // connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftPress, this, &IView::sendStatisticsCenter); // connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftButtonReleased, this, &IView::clearSeparationVector); // connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftButtonReleased, this, &IView::updateSkyCircles); } IvConfDockWidget::~IvConfDockWidget() { delete ui; } void IvConfDockWidget::switchMode(QString mode) { if (mode == "FITSmonochrome" || mode == "MEMview") { ui->valueGreenLabel->hide(); ui->valueBlueLabel->hide(); ui->valueGreenLeftLabel->hide(); ui->valueBlueLeftLabel->hide(); } else if (mode == "FITScolor") { ui->valueGreenLabel->show(); ui->valueBlueLabel->show(); ui->valueGreenLeftLabel->show(); ui->valueBlueLeftLabel->show(); ui->valueLeftLabel->setText("R = "); } else if (mode == "CLEAR") { ui->xposLabel->setText(""); ui->yposLabel->setText(""); ui->alphaDecLabel->setText(""); ui->alphaHexLabel->setText(""); ui->deltaDecLabel->setText(""); ui->deltaHexLabel->setText(""); ui->valueLabel->setText(""); // ui->zoomValueLabel->setText(""); ui->valueGreenLabel->hide(); ui->valueBlueLabel->hide(); ui->valueGreenLeftLabel->hide(); ui->valueBlueLeftLabel->hide(); } } double IvConfDockWidget::zoom2scale(int zoomlevel) { // Translates the integer zoom level to a scaling factor. // Update the zoom label if (zoomlevel > 0) { // ui->zoomValueLabel->setText(QString::number(zoomlevel+1)+":1"); iview->scene->zoomScale = zoomlevel+1.; return zoomlevel+1.; } else if (zoomlevel == 0) { // ui->zoomValueLabel->setText("1:1"); iview->scene->zoomScale = 1.; return 1.; } else { // ui->zoomValueLabel->setText("1:"+QString::number(-zoomlevel+1)); iview->scene->zoomScale = 1./(-zoomlevel+1.); return 1./(-zoomlevel+1.); } } void IvConfDockWidget::on_zoomInPushButton_clicked() { ui->zoomFitPushButton->setChecked(false); emit zoomInPushButton_clicked(); } void IvConfDockWidget::on_zoomOutPushButton_clicked() { ui->zoomFitPushButton->setChecked(false); emit zoomOutPushButton_clicked(); } void IvConfDockWidget::on_zoomZeroPushButton_clicked() { ui->zoomFitPushButton->setChecked(false); emit zoomZeroPushButton_clicked(); } void IvConfDockWidget::on_zoomFitPushButton_clicked() { emit zoomFitPushButton_clicked(ui->zoomFitPushButton->isChecked()); } void IvConfDockWidget::on_minLineEdit_returnPressed() { ui->autocontrastPushButton->setChecked(false); emit minmaxLineEdit_returnPressed(ui->minLineEdit->text(), ui->maxLineEdit->text()); } void IvConfDockWidget::on_maxLineEdit_returnPressed() { //QPixmap magnifiedPixmap = QPixmap("/home/mischa/euclid_logo.png"); //icdw->magnifiedGraphicsView->resetMatrix(); //QGraphicsPixmapItem *newItem = new QGraphicsPixmapItem(magnifiedPixmap); ui->autocontrastPushButton->setChecked(false); emit minmaxLineEdit_returnPressed(ui->minLineEdit->text(), ui->maxLineEdit->text()); } void IvConfDockWidget::on_autocontrastPushButton_toggled(bool checked) { emit autoContrastPushButton_toggled(checked); } void IvConfDockWidget::on_quitPushButton_clicked() { emit closeIview(); } // receiver from mouse pos hovering in binned vew void IvConfDockWidget::showCurrentMousePosBinned(QPointF currentMousePos) { QPointF qpoint = iview->binnedToQimage(currentMousePos); long i = qpoint.x(); long j = iview->naxis2 - qpoint.y(); ui->xposLabel->setText(QString::number(i)); ui->yposLabel->setText(QString::number(j)); // display sky coords iview->xy2sky(qpoint.x(), iview->naxis2 - qpoint.y()); // Display pixel values: respect image boundaries if (i<0 || j<0 || i>= iview->naxis1 || j>= iview->naxis2) { if (iview->displayMode == "FITSmonochrome" || iview->displayMode == "MEMview") { ui->valueLeftLabel->setText("Value = "); ui->valueLabel->setText(""); } else if (iview->displayMode == "FITScolor") { ui->valueLeftLabel->setText("R = "); ui->valueLabel->setText(""); ui->valueGreenLabel->setText(""); ui->valueBlueLabel->setText(""); } } else { if (iview->displayMode == "FITSmonochrome" || iview->displayMode == "MEMview") { ui->valueLabel->setText(QString::number(iview->fitsData[i+iview->naxis1*j])); } else if (iview->displayMode == "FITScolor") { ui->valueLeftLabel->setText("R = "+QString::number(iview->fitsDataR[i+iview->naxis1*j])); ui->valueLabel->setText(QString::number(iview->fitsDataR[i+iview->naxis1*j])); ui->valueGreenLabel->setText(QString::number(iview->fitsDataG[i+iview->naxis1*j])); ui->valueBlueLabel->setText(QString::number(iview->fitsDataB[i+iview->naxis1*j])); } } } void IvConfDockWidget::updateNavigatorMagnifiedReceived(QGraphicsPixmapItem *magnifiedPixmapItem, qreal magnification, float dx, float dy) { magnifiedGraphicsView->resetMatrix(); magnifiedScene->clear(); magnifiedScene->addItem(magnifiedPixmapItem); magnifiedGraphicsView->setScene(magnifiedScene); magnifiedGraphicsView->scale(magnification, magnification); magnifiedGraphicsView->centerOn(magnifiedPixmapItem); QPen pen(QColor("#00ffff")); pen.setCosmetic(true); float x1 = navigator_magnified_nx / magnification / 2.; float y1 = navigator_magnified_ny / magnification / 2.; QPoint p1 = QPoint(x1, y1); QPoint p2 = QPoint(x1, y1); // dx and dy intended to realign pixmap when cursor moves out of image boundary, but it is not working. // magnifiedGraphicsView->centerOn(x1+dx, y1+dy); magnifiedScene->addRect(QRect(p1,p2), pen); magnifiedGraphicsView->show(); // ui->navigatorStackedWidget->setCurrentIndex(1); } void IvConfDockWidget::clearMagnifiedSceneReceiver() { magnifiedScene->clear(); magnifiedGraphicsView->show(); } void IvConfDockWidget::clearBinnedSceneReceiver() { binnedScene->clear(); binnedGraphicsView->show(); } void IvConfDockWidget::updateNavigatorBinnedReceived(QGraphicsPixmapItem *binnedPixmapItem) { // binnedGraphicsView->resetMatrix(); binnedScene->clear(); binnedScene->addItem(binnedPixmapItem); // needed to prevent binnedView from scrolling binnedScene->setSceneRect(binnedPixmapItem->boundingRect()); // panning movement restricted to fov, half offset, if the following line is commented. Unclear why binnedGraphicsView->binnedSceneRect = binnedScene->sceneRect(); binnedGraphicsView->setScene(binnedScene); binnedGraphicsView->show(); } // Receiver for the event when the mouse enters the main graphics view void IvConfDockWidget::mouseEnteredViewReceived() { // ui->navigatorStackedWidget->setCurrentIndex(1); } // Receiver for the event when the mouse leaves the main graphics view void IvConfDockWidget::mouseLeftViewReceived() { // when the mouse cursor leaves the scene magnifiedScene->clear(); magnifiedGraphicsView->show(); // ui->navigatorStackedWidget->setCurrentIndex(0); } // whenever the user scrolls or zooms in the main window , this slot is invoked void IvConfDockWidget::updateNavigatorBinnedViewportReceived(QRect rect) { // leave if the user scrolls by dragging the fov rectangle in the binned window if (binnedGraphicsView->fovBeingDragged) return; // delete the old display of the rect QList items = binnedScene->items(); for (auto &it : items) { QGraphicsRectItem *rect = qgraphicsitem_cast(it); if (rect) binnedScene->removeItem(it); } // draw the new rect QPen pen(QColor("#00ffff")); pen.setCosmetic(true); pen.setWidth(0); binnedGraphicsView->fovRectItem = new MyQGraphicsRectItem(rect, nullptr); binnedGraphicsView->fovRectItem->setPen(pen); binnedGraphicsView->fovRectItem->setFlags(QGraphicsEllipseItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges); binnedScene->addItem(binnedGraphicsView->fovRectItem); // binnedGraphicsView->fovRectItem->setFlags(QGraphicsEllipseItem::ItemIsMovable | QGraphicsRectItem::ItemSendsGeometryChanges); // binnedGraphicsView->fovRectItem->setFlags(QGraphicsRectItem::ItemSendsGeometryChanges); binnedGraphicsView->setScene(binnedScene); binnedGraphicsView->show(); } void IvConfDockWidget::updateNavigatorMagnifiedViewportReceived() { return; // remove old rects QList items = magnifiedScene->items(); for (auto &it : items) { QGraphicsRectItem *rectcast = qgraphicsitem_cast(it); if (rectcast) magnifiedScene->removeItem(it); } QPen pen(QColor("#aaffff")); pen.setCosmetic(true); pen.setWidth(0); int x1 = navigator_magnified_nx/2-0.5; int x2 = navigator_magnified_nx/2+0.5; int y1 = navigator_magnified_ny/2-0.5; int y2 = navigator_magnified_ny/2+0.5; QPoint p1 = magnifiedGraphicsView->mapFromScene(QPoint(x1, y1)); QPoint p2 = magnifiedGraphicsView->mapFromScene(QPoint(x2, y2)); magnifiedScene->addRect(QRect(p1, p2), pen); magnifiedGraphicsView->setScene(magnifiedScene); magnifiedGraphicsView->show(); } void IvConfDockWidget::receiveWCS(wcsprm *WCS, bool wcsinit) { if (!wcsinit) return; wcs = WCS; // Catching spectroscopic exposures or others with invalid "imaging" WCS if (!wcs) return; cd11 = wcs->cd[0]; cd12 = wcs->cd[1]; cd21 = wcs->cd[2]; cd22 = wcs->cd[3]; if (cd11 == 0. && cd12 == 0. && cd21 == 0. && cd22 == 0.) return; drawCompass(); } void IvConfDockWidget::drawCompass() { // delete old compass elements QList items = binnedScene->items(); for (auto &it : items) { QGraphicsLineItem *line = qgraphicsitem_cast(it); if (line) binnedScene->removeItem(it); QGraphicsTextItem *text = qgraphicsitem_cast(it); if (text) binnedScene->removeItem(it); } double norm = sqrt(cd11*cd11+cd12*cd12); double length = navigator_binned_nx / 5.; QPointF start = iview->qimageToBinned(QPointF(iview->naxis1/2, iview->naxis2/2)); QPen pen(QColor("#ffff00")); pen.setCosmetic(true); pen.setWidth(0); // Arrows QPointF eastEnd; QPointF northEnd; eastEnd.setX(start.x() + cd11/norm * length); eastEnd.setY(start.y() - cd12/norm * length); // y axis is inverted in QImage wrt FITS, hence -cd12 northEnd.setX(start.x() + cd21/norm * length); northEnd.setY(start.y() - cd22/norm * length); // y axis is inverted in QImage wrt FITS, hence -cd22 QLineF eastArrow = QLineF(start, eastEnd); QLineF northArrow = QLineF(start, northEnd); binnedScene->addLine(eastArrow, pen); binnedScene->addLine(northArrow, pen); // Labels QGraphicsTextItem *labelEast = binnedScene->addText("E"); QGraphicsTextItem *labelNorth = binnedScene->addText("N"); labelEast->setDefaultTextColor(QColor("#ffff00")); labelNorth->setDefaultTextColor(QColor("#ffff00")); int exoffset = labelEast->boundingRect().width()/2; int eyoffset = labelEast->boundingRect().height()/2; int nxoffset = labelNorth->boundingRect().width()/2; int nyoffset = labelNorth->boundingRect().height()/2; int exspace = 0.3*(eastEnd.x() - start.x()); int eyspace = 0.3*(eastEnd.y() - start.y()); int nxspace = 0.3*(northEnd.x() - start.x()); int nyspace = 0.3*(northEnd.y() - start.y()); labelEast->setPos(eastEnd.x()-exoffset+exspace, eastEnd.y()-eyoffset+eyspace); labelNorth->setPos(northEnd.x()-nxoffset+nxspace, northEnd.y()-nyoffset+nyspace); binnedGraphicsView->show(); } THELI-3.1.3/src/iview/dockwidgets/ivconfdockwidget.h000066400000000000000000000063321417631501300223130ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVCONFDOCKWIDGET_H #define IVCONFDOCKWIDGET_H #include "../mybinnedgraphicsview.h" #include "../mymagnifiedgraphicsview.h" #include "../mygraphicsscene.h" #include #include "wcs.h" #include "wcshdr.h" namespace Ui { class IvConfDockWidget; } class IView; // Forward declaration to access members class IvConfDockWidget : public QDockWidget { Q_OBJECT public: explicit IvConfDockWidget(IView *parent = 0); ~IvConfDockWidget(); Ui::IvConfDockWidget *ui; IView *iview; MyMagnifiedGraphicsView *magnifiedGraphicsView; MyBinnedGraphicsView *binnedGraphicsView; MyGraphicsScene *magnifiedScene = new MyGraphicsScene(); MyGraphicsScene *binnedScene = new MyGraphicsScene(); int navigator_binned_nx = 0; // the width and height of the binned window; int navigator_binned_ny = 0; int navigator_magnified_nx = 0; // the width and height of the magnifyer window; int navigator_magnified_ny = 0; double cd11 = 0.; double cd12 = 0.; double cd21 = 0.; double cd22 = 0.; wcsprm *wcs = nullptr; QRect currentFov; // the currently displayed field of view QList currentFovList; void switchMode(QString mode); double zoom2scale(int zoomlevel); void drawCompass(); private slots: void on_zoomOutPushButton_clicked(); void on_zoomInPushButton_clicked(); void on_minLineEdit_returnPressed(); void on_maxLineEdit_returnPressed(); void on_autocontrastPushButton_toggled(bool checked); void on_quitPushButton_clicked(); void showCurrentMousePosBinned(QPointF currentMousePos); public slots: void on_zoomFitPushButton_clicked(); void on_zoomZeroPushButton_clicked(); void updateNavigatorMagnifiedReceived(QGraphicsPixmapItem *magnifiedPixmapItem, qreal magnification, float dx, float dy); void updateNavigatorBinnedReceived(QGraphicsPixmapItem *binnedPixmapItem); void mouseEnteredViewReceived(); void mouseLeftViewReceived(); void updateNavigatorBinnedViewportReceived(QRect rect); void updateNavigatorMagnifiedViewportReceived(); void receiveWCS(wcsprm *WCS, bool wcsinit); void clearMagnifiedSceneReceiver(); void clearBinnedSceneReceiver(); signals: void autoContrastPushButton_toggled(bool checked); void minmaxLineEdit_returnPressed(QString rangeMin, QString rangeMax); void zoomFitPushButton_clicked(bool checked); void zoomInPushButton_clicked(); void zoomOutPushButton_clicked(); void zoomZeroPushButton_clicked(); void closeIview(); }; #endif // IVCONFDOCKWIDGET_H THELI-3.1.3/src/iview/dockwidgets/ivconfdockwidget.ui000066400000000000000000003045121417631501300225020ustar00rootroot00000000000000 IvConfDockWidget 0 0 168 719 0 0 168 524287 QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Navigation 150 150 150 150 QFrame::Box QFrame::Plain 0 0 0 0 0 0 0 150 150 150 150 QFrame::Box QFrame::Plain 0 0 0 0 0 0 0 0 0 150 0 150 16777215 252 252 252 198 198 199 252 252 252 198 198 199 198 198 199 198 198 199 10 50 false false true QFrame::StyledPanel QFrame::Raised 4 4 4 4 4 0 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 10 50 false x = 10 50 false y = 10 50 false Value = 0 0 10 50 false G = 10 50 false B = 10 50 false R.A. = 10 50 false R.A. = 10 50 false Dec = 10 50 false Dec = 0 0 150 0 150 16777215 252 252 252 198 198 199 252 252 252 198 198 199 198 198 199 198 198 199 10 50 false false true QFrame::StyledPanel QFrame::Raised 4 4 4 4 2 35 0 35 16777215 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 81 127 114 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 81 127 114 255 255 255 81 127 114 162 255 229 162 255 229 0 0 0 162 255 229 255 255 220 0 0 0 Qt::NoFocus 1:1 zoom 1:1 Qt::Vertical QSizePolicy::Fixed 20 10 35 0 35 16777215 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 81 127 114 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 81 127 114 255 255 255 81 127 114 162 255 229 162 255 229 0 0 0 162 255 229 255 255 220 0 0 0 Qt::NoFocus Zoom in + 35 0 35 16777215 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 81 127 114 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 81 127 114 255 255 255 81 127 114 162 255 229 162 255 229 0 0 0 162 255 229 255 255 220 0 0 0 Qt::NoFocus Zoom to fit image into the window Fit true 35 0 35 16777215 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 81 127 114 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 81 127 114 255 255 255 81 127 114 162 255 229 162 255 229 0 0 0 162 255 229 255 255 220 0 0 0 Qt::NoFocus Zoom out - 70 0 Qt::StrongFocus Pixels brighter than this value will be shown white Min Max 70 0 Qt::StrongFocus Pixels fainter than this value will be shown black 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 0 0 0 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 0 0 0 255 255 255 0 0 0 255 255 255 162 255 229 0 0 0 208 255 242 255 255 220 0 0 0 81 127 114 162 255 229 255 255 255 208 255 242 81 127 114 108 170 153 81 127 114 255 255 255 81 127 114 162 255 229 162 255 229 0 0 0 162 255 229 255 255 220 0 0 0 50 false Qt::NoFocus Automatically determine the dynamic range for display true Auto contrast true Qt::Vertical QSizePolicy::Fixed 20 13 0 0 0 192 216 255 255 255 255 223 235 255 96 108 127 128 144 170 0 0 0 255 255 255 0 0 0 255 255 255 192 216 255 0 0 0 223 235 255 255 255 220 0 0 0 0 0 0 192 216 255 255 255 255 223 235 255 96 108 127 128 144 170 0 0 0 255 255 255 0 0 0 255 255 255 192 216 255 0 0 0 223 235 255 255 255 220 0 0 0 96 108 127 192 216 255 255 255 255 223 235 255 96 108 127 128 144 170 96 108 127 255 255 255 96 108 127 192 216 255 192 216 255 0 0 0 192 216 255 255 255 220 0 0 0 Cloes iView, all changes to images will be saved. Accept sky locations Qt::Vertical 20 137 minLineEdit maxLineEdit quitPushButton THELI-3.1.3/src/iview/dockwidgets/ivfinderdockwidget.cc000066400000000000000000000126631417631501300227770ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivfinderdockwidget.h" #include "ui_ivfinderdockwidget.h" #include "../iview.h" #include "../../query/query.h" #include // To implement MPC cone search using 'skybot' // https://astroquery.readthedocs.io/en/latest/imcce/imcce.html IvFinderDockWidget::IvFinderDockWidget(QWidget *parent) : QDockWidget(parent), ui(new Ui::IvFinderDockWidget) { ui->setupUi(this); QIcon star(":/icons/star_icon.png"); ui->targetresolverToolButton->setIcon(star); QIcon asteroid(":/icons/asteroid_icon.png"); ui->MPCresolverToolButton->setIcon(asteroid); connect(this, &IvFinderDockWidget::targetResolved, this, &IvFinderDockWidget::targetResolvedReceived); connect(ui->targetAlphaLineEdit, &QLineEdit::textChanged, this, &IvFinderDockWidget::validate); connect(ui->targetDeltaLineEdit, &QLineEdit::textChanged, this, &IvFinderDockWidget::validate); } IvFinderDockWidget::~IvFinderDockWidget() { delete ui; } void IvFinderDockWidget::on_targetresolverToolButton_clicked() { ui->targetAlphaLineEdit->clear(); ui->targetDeltaLineEdit->clear(); QString targetName = ui->targetNameSiderealLineEdit->text(); if (targetName.isEmpty()) return; targetName = targetName.simplified().replace(" ", "_"); int verbosity = 0; Query *query = new Query(&verbosity); QString check = query->resolveTargetSidereal(targetName); if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta); else if (check == "Unresolved") { QMessageBox::information(this, "THELI: Target unresolved", "The target " + targetName + " could not be resolved."); } else { // nothing yet. } delete query; query = nullptr; } // Query updates RA/DEC fields if successful void IvFinderDockWidget::targetResolvedReceived(QString alpha, QString delta) { ui->targetAlphaLineEdit->setText(alpha); ui->targetDeltaLineEdit->setText(delta); } // Coords were entered manually, then user clicks the "locate" button void IvFinderDockWidget::on_locatePushButton_clicked() { QString alpha = ui->targetAlphaLineEdit->text(); QString delta = ui->targetDeltaLineEdit->text(); if (alpha.isEmpty() || delta.isEmpty()) return; emit targetResolved(alpha, delta); } void IvFinderDockWidget::validate() { QRegExp RA( "[0-9.:]+" ); QRegExp DEC( "^[-]{0,1}[0-9.:]+" ); QValidator* validator_ra = new QRegExpValidator( RA, this ); QValidator* validator_dec = new QRegExpValidator( DEC, this ); ui->targetAlphaLineEdit->setValidator( validator_ra ); ui->targetDeltaLineEdit->setValidator( validator_dec ); } void IvFinderDockWidget::on_clearPushButton_clicked() { ui->targetNameSiderealLineEdit->clear(); ui->targetNameNonsiderealLineEdit->clear(); ui->targetAlphaLineEdit->clear(); ui->targetDeltaLineEdit->clear(); emit clearTargetResolved(); } void IvFinderDockWidget::on_MPCresolverToolButton_clicked() { ui->targetAlphaLineEdit->clear(); ui->targetDeltaLineEdit->clear(); QString targetName = ui->targetNameNonsiderealLineEdit->text(); if (targetName.isEmpty()) return; // targetName = targetName.simplified().replace(" ", "_"); targetName = targetName.simplified(); int verbosity = 0; Query *query = new Query(&verbosity); QString check = query->resolveTargetNonsidereal(targetName, dateObs, geoLon, geoLat); if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta); else if (check == "Unresolved") { // Test if there is a blank in the string, and try without the blank: if (targetName.contains(' ')) { QString targetOrig = targetName; targetName.remove(QChar(' ')); QString check = query->resolveTargetNonsidereal(targetName, dateObs, geoLon, geoLat); if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta); else { QMessageBox::information(this, "THELI: Target unresolved", "The target names \"" + targetOrig + "\" and " +"\"" + targetName + "\"" + " could not be resolved."); } } else { QMessageBox::information(this, "THELI: Target unresolved", "The target name \"" + targetName + "\" could not be resolved."); } } else { // nothing yet. } delete query; query = nullptr; } void IvFinderDockWidget::updateDateObsAndGeo(QString dateobs, float geolon, float geolat) { dateObs = dateobs; geoLon = geolon; geoLat = geolat; } // just show a crosshair at the coordinates, don't resolve anything void IvFinderDockWidget::bypassResolver() { emit targetResolved(ui->targetAlphaLineEdit->text(), ui->targetDeltaLineEdit->text()); } THELI-3.1.3/src/iview/dockwidgets/ivfinderdockwidget.h000066400000000000000000000031161417631501300226320ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVFINDERDOCKWIDGET_H #define IVFINDERDOCKWIDGET_H #include namespace Ui { class IvFinderDockWidget; } class IvFinderDockWidget : public QDockWidget { Q_OBJECT public: explicit IvFinderDockWidget(QWidget *parent = 0); ~IvFinderDockWidget(); Ui::IvFinderDockWidget *ui; QString dateObs = "2020-01-01T00:00:00"; float geoLon = 0.0; float geoLat = 0.0; void bypassResolver(); public slots: void updateDateObsAndGeo(QString dateobs, float geolon, float geolat); void on_targetresolverToolButton_clicked(); void on_MPCresolverToolButton_clicked(); void on_locatePushButton_clicked(); private slots: void targetResolvedReceived(QString alpha, QString delta); void validate(); void on_clearPushButton_clicked(); signals: void targetResolved(QString alpha, QString delta); void clearTargetResolved(); private: }; #endif // IVFINDERDOCKWIDGET_H THELI-3.1.3/src/iview/dockwidgets/ivfinderdockwidget.ui000066400000000000000000000146431417631501300230270ustar00rootroot00000000000000 IvFinderDockWidget 0 0 168 217 168 524287 Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Locate target Official MPC name of a nonsidereal target Target declination (decimal or sexagesimal) Target right ascension (decimal or sexagesimal) Dec 30 30 30 30 Qt::ClickFocus Nonsidereal target: Lookup the coordinates for the DATE-OBS in this image true ... ../../dockwidgets/icons/magnifyer.png../../dockwidgets/icons/magnifyer.png 49 49 false true true 30 30 30 30 Qt::ClickFocus Sidereal target: Lookup the coordinates true ... ../../dockwidgets/icons/magnifyer.png../../dockwidgets/icons/magnifyer.png 49 49 false true true Name of a sidereal target Qt::NoFocus Shows manually entered coordinates. The target resolver buttons do this automatically. Locate Qt::NoFocus Clears all input fields and removes the target marker Clear R.A. Qt::Vertical 20 40 Qt::Horizontal targetNameSiderealLineEdit targetNameNonsiderealLineEdit targetAlphaLineEdit targetDeltaLineEdit locatePushButton clearPushButton THELI-3.1.3/src/iview/dockwidgets/ivredshiftdockwidget.cc000066400000000000000000000165271417631501300233430ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivredshiftdockwidget.h" #include "ui_ivredshiftdockwidget.h" #include "../iview.h" #include "../../functions.h" #include #include #include #include #include IvRedshiftDockWidget::IvRedshiftDockWidget(IView *parent) : QDockWidget(parent), ui(new Ui::IvRedshiftDockWidget) { ui->setupUi(this); iview = parent; populateWavelengthMaps(); init(); QString lambda = QString(QChar(0xbb, 0x03)); QString angstrom = QString(QChar(0x2b, 0x21)); ui->lambdaObsLabel->setText(lambda+"observed"+" ["+angstrom+"]"); ui->lambdaRestLabel->setText(lambda+"restframe"+" ["+angstrom+"]"); } IvRedshiftDockWidget::~IvRedshiftDockWidget() { delete ui; } void IvRedshiftDockWidget::populateWavelengthMaps() { HList.append(qMakePair(QString("Lya"), 1215)); HList.append(qMakePair(QString("Lyb"), 1025)); HList.append(qMakePair(QString("Lyg"), 972)); HList.append(qMakePair(QString("Hd"), 4103)); HList.append(qMakePair(QString("Hg"), 4343)); HList.append(qMakePair(QString("Hb"), 4864)); HList.append(qMakePair(QString("Ha"), 6565)); HList.append(qMakePair(QString("Paa"), 18746)); HList.append(qMakePair(QString("Pab"), 12815)); HList.append(qMakePair(QString("Pag"), 10935)); HList.append(qMakePair(QString("Brg"), 21650)); HList.append(qMakePair(QString("H2_1-0"), 21220)); HList.append(qMakePair(QString("H2_2-1"), 22480)); HeList.append(qMakePair(QString("HeII"), 1640)); HeList.append(qMakePair(QString("HeII"), 2733)); HeList.append(qMakePair(QString("HeI"), 2945)); HeList.append(qMakePair(QString("HeII"), 3204)); HeList.append(qMakePair(QString("HeI"), 3889)); HeList.append(qMakePair(QString("HeI"), 4471)); HeList.append(qMakePair(QString("HeII"), 4687)); HeList.append(qMakePair(QString("HeII"), 5413)); HeList.append(qMakePair(QString("HeI"), 5877)); HeList.append(qMakePair(QString("HeI"), 6680)); HeList.append(qMakePair(QString("HeI"), 10830)); HeList.append(qMakePair(QString("HeI"), 20581)); OList.append(qMakePair(QString("OVI"), 1032)); OList.append(qMakePair(QString("OVI"), 1038)); OList.append(qMakePair(QString("OVI]"), 1402)); OList.append(qMakePair(QString("OIII]"), 1666)); OList.append(qMakePair(QString("OIII"), 3133)); OList.append(qMakePair(QString("[OII]"), 3727)); OList.append(qMakePair(QString("[OIII]"), 4363)); OList.append(qMakePair(QString("[OIII]"), 4960)); OList.append(qMakePair(QString("[OIII]"), 5008)); OList.append(qMakePair(QString("[OI]"), 6302)); OList.append(qMakePair(QString("[OI]"), 6366)); OList.append(qMakePair(QString("[OII]"), 7321)); NList.append(qMakePair(QString("NV"), 1240)); NList.append(qMakePair(QString("[NII]"), 6550)); NList.append(qMakePair(QString("[NII]"), 6586)); CList.append(qMakePair(QString("CIII"), 977)); CList.append(qMakePair(QString("CIII]"), 1909)); CList.append(qMakePair(QString("CIV"), 1549)); CList.append(qMakePair(QString("CII"), 2326)); ArList.append(qMakePair(QString("[ArIII]"), 7138)); SList.append(qMakePair(QString("[SII]"), 1812)); SList.append(qMakePair(QString("[SII]"), 1822)); SList.append(qMakePair(QString("[SII]"), 4069)); SList.append(qMakePair(QString("[SII]"), 4076)); SList.append(qMakePair(QString("SII"), 5203)); SList.append(qMakePair(QString("[SII]"), 6718)); SList.append(qMakePair(QString("[SII]"), 6733)); SList.append(qMakePair(QString("[SIII]"), 9071)); SList.append(qMakePair(QString("[SIII]"), 9533)); NaList.append(qMakePair(QString("NaD2"), 5890)); NaList.append(qMakePair(QString("NaD1"), 5896)); NeList.append(qMakePair(QString("[NeIV]"), 2424)); NeList.append(qMakePair(QString("[NeV]"), 3347)); NeList.append(qMakePair(QString("[NeV]"), 3427)); NeList.append(qMakePair(QString("[NeIII]"), 3869)); NeList.append(qMakePair(QString("[NeIII]"), 3968)); CaList.append(qMakePair(QString("CaH"), 3934)); CaList.append(qMakePair(QString("CaK"), 3969)); CaList.append(qMakePair(QString("CaT1"), 8499)); CaList.append(qMakePair(QString("CaT2"), 8542)); CaList.append(qMakePair(QString("CaT3"), 8662)); MgList.append(qMakePair(QString("Mg"), 2799)); MgList.append(qMakePair(QString("Mg"), 5167)); MgList.append(qMakePair(QString("Mg"), 5173)); MgList.append(qMakePair(QString("Mg"), 5184)); FeList.append(qMakePair(QString("FeI"), 2745)); FeList.append(qMakePair(QString("FeI"), 2807)); FeList.append(qMakePair(QString("FeI"), 2950)); FeList.append(qMakePair(QString("FeI"), 5725)); FeList.append(qMakePair(QString("[FeVII]"), 6089)); FeList.append(qMakePair(QString("FeI"), 11887)); } void IvRedshiftDockWidget::init() { connect(ui->HCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->HeCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->NCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->CCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->OCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->SCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->NeCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->NaCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->CaCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->MgCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->ArCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->FeCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes); connect(ui->finesseSpinBox, static_cast(&QSpinBox::valueChanged), iview, &IView::updateFinesse); // QSpinBox has two valueChanged(), signals with int and string arguments; we need int connect(ui->zLineEdit, &QLineEdit::textEdited, iview, &IView::redshiftChanged); connect(ui->zLineEdit, &QLineEdit::textChanged, this, &IvRedshiftDockWidget::validate); } void IvRedshiftDockWidget::showWavelength(QString lobs, QString lrest) { // Display the wavelengths ui->lambdaObsLineEdit->setText(lobs); ui->lambdaRestLineEdit->setText(lrest); } void IvRedshiftDockWidget::on_zLineEdit_textChanged(const QString &arg1) { emit redshiftEdited(ui->zLineEdit->text()); } void IvRedshiftDockWidget::redshiftUpdatedReceiver(float z_0) { ui->zLineEdit->setText(QString::number(z_0, 'f', 4)); } void IvRedshiftDockWidget::validate() { QRegExp rf( "^[0-9]*[.]{0,1}[0-9]+" ); QValidator* validator_float_pos = new QRegExpValidator(rf, this ); ui->zLineEdit->setValidator(validator_float_pos); } THELI-3.1.3/src/iview/dockwidgets/ivredshiftdockwidget.h000066400000000000000000000037071417631501300232010ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVREDSHIFTDOCKWIDGET_H #define IVREDSHIFTDOCKWIDGET_H #include #include #include #include "../myaxis.h" namespace Ui { class IvRedshiftDockWidget; } class IView; // Forward declaration to access members class IvRedshiftDockWidget : public QDockWidget { Q_OBJECT public: explicit IvRedshiftDockWidget(IView *parent = 0); ~IvRedshiftDockWidget(); Ui::IvRedshiftDockWidget *ui; IView *iview; QList> HList; QList> HeList; QList> NeList; QList> NList; QList> CList; QList> OList; QList> ArList; QList> FeList; QList> MgList; QList> NaList; QList> CaList; QList> SList; void init(); public slots: void showWavelength(QString lobs, QString lrest); void redshiftUpdatedReceiver(float z_0); private slots: void on_zLineEdit_textChanged(const QString &arg1); void validate(); private: void populateWavelengthMaps(); void showAxes(); signals: void redshiftEdited(QString text); }; #endif // IVREDSHIFTDOCKWIDGET_H THELI-3.1.3/src/iview/dockwidgets/ivredshiftdockwidget.ui000066400000000000000000000174601417631501300233700ustar00rootroot00000000000000 IvRedshiftDockWidget 0 0 161 313 Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Redshift estimator Hydrogen H true Sodium Na Sulfur S true Calcium Ca true Carbon C Oxygen O true Magnesium Mg true Nitrogen N true Iron Fe Argon Ar Neon Ne true Helium He true Spectral features The currently applied redshift Redshift The currently applied redshift 0.0 Finesse The higher the number, the finer you can adjust the redshift by left-click dragging in the image. false 10 5 lobs Observed wavelength true lrest Restframe wavelength true Qt::Vertical 20 40 HCheckBox HeCheckBox NeCheckBox OCheckBox SCheckBox NCheckBox CaCheckBox MgCheckBox CCheckBox NaCheckBox ArCheckBox FeCheckBox zLineEdit finesseSpinBox lambdaObsLineEdit lambdaRestLineEdit THELI-3.1.3/src/iview/dockwidgets/ivscampdockwidget.cc000066400000000000000000000022621417631501300226250ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivscampdockwidget.h" #include "ui_ivscampdockwidget.h" #include "../iview.h" #include IvScampDockWidget::IvScampDockWidget(IView *parent) : QDockWidget(parent), ui(new Ui::IvScampDockWidget) { ui->setupUi(this); iview = parent; } IvScampDockWidget::~IvScampDockWidget() { delete ui; } void IvScampDockWidget::on_acceptSolution_clicked() { emit solutionAcceptanceState(true); } void IvScampDockWidget::on_rejectSolution_clicked() { emit solutionAcceptanceState(false); } THELI-3.1.3/src/iview/dockwidgets/ivscampdockwidget.h000066400000000000000000000023371417631501300224720ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVSCAMPDOCKWIDGET_H #define IVSCAMPDOCKWIDGET_H #include namespace Ui { class IvScampDockWidget; } class IView; // Forward declaration to access members class IvScampDockWidget : public QDockWidget { Q_OBJECT public: explicit IvScampDockWidget(IView *parent = 0); ~IvScampDockWidget(); IView *iview; private: Ui::IvScampDockWidget *ui; private slots: void on_acceptSolution_clicked(); void on_rejectSolution_clicked(); signals: void solutionAcceptanceState(bool state); }; #endif // IVSCAMPDOCKWIDGET_H THELI-3.1.3/src/iview/dockwidgets/ivscampdockwidget.ui000066400000000000000000000617421417631501300226650ustar00rootroot00000000000000 IvScampDockWidget 0 0 171 222 QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Scamp solution 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 Will continue processing, including updating the zero order WCS solution in the FITS headers. Accept solution, update FITS headers, run IQ analysis, and close 0 0 0 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 0 0 0 255 255 255 0 0 0 255 255 255 223 77 123 0 0 0 239 166 189 255 255 220 0 0 0 0 0 0 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 0 0 0 255 255 255 0 0 0 255 255 255 223 77 123 0 0 0 239 166 189 255 255 220 0 0 0 111 38 61 223 77 123 255 168 195 239 122 159 111 38 61 149 51 82 111 38 61 255 255 255 111 38 61 223 77 123 223 77 123 0 0 0 223 77 123 255 255 220 0 0 0 Will abort processing. Zero order solution in FITS headers will not be updated. Reject solution, don't update headers, no IQ analysis, and close Qt::Vertical QSizePolicy::Expanding 20 0 THELI-3.1.3/src/iview/dockwidgets/ivstatisticsdockwidget.cc000066400000000000000000000111451417631501300237140ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivstatisticsdockwidget.h" #include "ui_ivstatisticsdockwidget.h" #include "../iview.h" #include "../../functions.h" #include IvStatisticsDockWidget::IvStatisticsDockWidget(IView *parent) : QDockWidget(parent), ui(new Ui::IvStatisticsDockWidget) { ui->setupUi(this); iview = parent; } IvStatisticsDockWidget::~IvStatisticsDockWidget() { delete ui; } void IvStatisticsDockWidget::init() { QString sigma = QChar(0xc3, 0x03); int validDigits = 4 - log( fabs(iview->globalMedian)) / log(10.); if (validDigits < 0) validDigits = 0; if (iview->displayMode == "FITSmonochrome" || iview->displayMode == "MEMview") { ui->globalSigmaLeftLabel->setText(sigma + " = "); ui->localSigmaLeftLabel->setText(sigma + " = "); ui->globalMedianLabel->setText(QString::number(iview->globalMedian, 'f', validDigits)); ui->globalMeanLabel->setText(QString::number(iview->globalMean, 'f', validDigits)); ui->globalSigmaLabel->setText(QString::number(iview->globalRMS, 'f', validDigits)); ui->localMedianLabel->clear(); ui->localMeanLabel->clear(); ui->localSigmaLabel->clear(); } if (iview->displayMode == "FITScolor") { ui->globalMedianLeftLabel->setText("Median R = "); ui->globalMeanLeftLabel->setText("Median G = "); ui->globalSigmaLeftLabel->setText("Median B = "); ui->globalMedianLabel->setText(QString::number(iview->globalMedianR, 'f', validDigits)); ui->globalMeanLabel->setText(QString::number(iview->globalMedianG, 'f', validDigits)); ui->globalSigmaLabel->setText(QString::number(iview->globalMedianB, 'f', validDigits)); ui->localMedianLeftLabel->setText("Median R = "); ui->localMeanLeftLabel->setText("Median G = "); ui->localSigmaLeftLabel->setText("Median B = "); ui->localMedianLabel->clear(); ui->localMeanLabel->clear(); ui->localSigmaLabel->clear(); } ui->localWindowComboBox->setCurrentText("9x9"); } void IvStatisticsDockWidget::statisticsSampleReceiver(const QVector &sample) { if (!this->isVisible()) return; localMedian = straightMedian_T(sample); localMean = meanMask_T(sample, QVector()); localSigma = 1.486*madMask_T(sample, QVector(), "ignoreZeroes"); int validDigits = 4 - log( fabs(localMedian)) / log(10.); if (validDigits < 0) validDigits = 0; ui->localMedianLabel->setText(QString::number(localMedian, 'f', validDigits)); ui->localMeanLabel->setText(QString::number(localMean, 'f', validDigits)); ui->localSigmaLabel->setText(QString::number(localSigma, 'f', validDigits)); } void IvStatisticsDockWidget::statisticsSampleColorReceiver(const QVector &sampleR, const QVector &sampleG, const QVector &sampleB) { if (!this->isVisible()) return; localMedianR = straightMedian_T(sampleR); localMedianG = straightMedian_T(sampleG); localMedianB = straightMedian_T(sampleB); /* float localMeanR = meanMask_T(sampleR, QVector()); float localMeanG = meanMask_T(sampleG, QVector()); float localMeanB = meanMask_T(sampleB, QVector()); float localSigmaR = 1.486*madMask_T(sampleR, QVector(), "ignoreZeroes"); float localSigmaG = 1.486*madMask_T(sampleG, QVector(), "ignoreZeroes"); float localSigmaB = 1.486*madMask_T(sampleB, QVector(), "ignoreZeroes"); */ int validDigits = 4 - log( fabs(localMedianG)) / log(10.); if (validDigits < 0) validDigits = 0; // re-purposing default labels: ui->localMedianLabel->setText(QString::number(localMedianR, 'f', validDigits)); ui->localMeanLabel->setText(QString::number(localMedianG, 'f', validDigits)); ui->localSigmaLabel->setText(QString::number(localMedianB, 'f', validDigits)); } void IvStatisticsDockWidget::on_localWindowComboBox_currentIndexChanged(const QString &arg1) { statWidth = ui->localWindowComboBox->currentText().split('x').at(0).toInt(); } THELI-3.1.3/src/iview/dockwidgets/ivstatisticsdockwidget.h000066400000000000000000000031651417631501300235610ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVSTATISTICSDOCKWIDGET_H #define IVSTATISTICSDOCKWIDGET_H #include namespace Ui { class IvStatisticsDockWidget; } class IView; // Forward declaration to access members class IvStatisticsDockWidget : public QDockWidget { Q_OBJECT public: explicit IvStatisticsDockWidget(IView *parent = 0); ~IvStatisticsDockWidget(); Ui::IvStatisticsDockWidget *ui; IView *iview; int statWidth = 3; void init(); public slots: void statisticsSampleReceiver(const QVector &sample); void statisticsSampleColorReceiver(const QVector &sampleR, const QVector &sampleG, const QVector &sampleB); private slots: void on_localWindowComboBox_currentIndexChanged(const QString &arg1); private: float localMedian = 0.; float localSigma = 0.; float localMean = 0.; float localMedianR = 0.; float localMedianG = 0.; float localMedianB = 0.; }; #endif // IVSTATISTICSDOCKWIDGET_H THELI-3.1.3/src/iview/dockwidgets/ivstatisticsdockwidget.ui000066400000000000000000000207531417631501300237510ustar00rootroot00000000000000 IvStatisticsDockWidget 0 0 138 218 138 218 168 524287 Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Pixel statistics 70 0 70 16777215 The squared aperture [pixel] at the cursor position in which local statistics are measured 3x3 5x5 9x9 15x15 25x25 10 75 true Local: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 10 50 false Median = Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter TextLabel 10 50 false Mean = Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter TextLabel 0 0 10 50 false SD = Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter TextLabel 10 75 true Global: Qt::Horizontal 0 20 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 10 50 false Median = Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter TextLabel 10 50 false Mean = Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter TextLabel 10 50 false SD = Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter TextLabel Qt::Vertical 20 40 THELI-3.1.3/src/iview/dockwidgets/ivwcsdockwidget.cc000066400000000000000000000147551417631501300223300ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivwcsdockwidget.h" #include "ui_ivwcsdockwidget.h" #include "../../functions.h" IvWCSDockWidget::IvWCSDockWidget(QWidget *parent) : QDockWidget(parent), ui(new Ui::IvWCSDockWidget) { ui->setupUi(this); } IvWCSDockWidget::~IvWCSDockWidget() { delete ui; } void IvWCSDockWidget::init() { cd11 = cd11_orig; cd12 = cd12_orig; cd21 = cd21_orig; cd22 = cd22_orig; updateLineEdits(); } void IvWCSDockWidget::on_cd11Slider_sliderMoved(int position) { QSlider *slider = qobject_cast(sender()); float weight = calcCDweight(); if (weight > 1.) weight = 1.; cd11 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd11_orig; emit CDmatrixChanged(cd11, cd12, cd21, cd22); ui->cd11LineEdit->setText(QString::number(cd11, 'e', 6)); } void IvWCSDockWidget::on_cd12Slider_sliderMoved(int position) { QSlider *slider = qobject_cast(sender()); float weight = calcCDweight(); if (weight < 1.) weight = 1.; weight = 5.; cd12 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd12_orig; emit CDmatrixChanged(cd11, cd12, cd21, cd22); ui->cd12LineEdit->setText(QString::number(cd12, 'e', 6)); } void IvWCSDockWidget::on_cd21Slider_sliderMoved(int position) { QSlider *slider = qobject_cast(sender()); float weight = calcCDweight(); if (weight < 1.) weight = 1.; weight = 5.; cd21 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd21_orig; emit CDmatrixChanged(cd11, cd12, cd21, cd22); ui->cd21LineEdit->setText(QString::number(cd21, 'e', 6)); } void IvWCSDockWidget::on_cd22Slider_sliderMoved(int position) { QSlider *slider = qobject_cast(sender()); float weight = calcCDweight(); if (weight > 1.) weight = 1.; cd22 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd22_orig; emit CDmatrixChanged(cd11, cd12, cd21, cd22); ui->cd22LineEdit->setText(QString::number(cd22, 'e', 6)); } // Calculate a weight that makes the WCS slider more sensitive to smaller CD values float IvWCSDockWidget::calcCDweight() { float ratio = 1.0; if (cd12_orig != 0. && cd11_orig != 0) ratio = fabs(cd11_orig / cd12_orig); else if (cd11_orig == 0. && cd12_orig != 0.) ratio = 0.001; // effective else if (cd12_orig == 0. && cd11_orig != 0.) ratio = 1000.; // effective else ratio = 1.; float weight = sqrt(ratio); // return 1.; // deactivated return weight; } // Translates the integer slider position to a relative change, non-linearly double IvWCSDockWidget::translateCDmatrixSlider(int position, int maxRange) { double pos = position; double range = maxRange; return pow(2., 0.5*pos/range); // from 0.7 to 1.4 } // Translates the integer slider position to a relative change, non-linearly using a cosh dependence double IvWCSDockWidget::translatePlateScaleSlider(int position, int maxRange) { double pos = position; double range = maxRange; return pow(2., 0.5*pos/range); // from 0.7 to 1.4 } // Translates the integer slider position to a relative change, non-linearly using a cosh dependence double IvWCSDockWidget::translatePosAngleSlider(int position, int maxRange) { double pos = position; double range = maxRange; return 10.*(pos/range); // from -10 to 10 } void IvWCSDockWidget::on_plateScaleSlider_sliderMoved(int position) { QSlider *slider = qobject_cast(sender()); double rescaleFactor = translatePlateScaleSlider(position, slider->maximum()); cd11 = cd11_orig * rescaleFactor; cd12 = cd12_orig * rescaleFactor; cd21 = cd21_orig * rescaleFactor; cd22 = cd22_orig * rescaleFactor; emit CDmatrixChanged(cd11, cd12, cd21, cd22); updateLineEdits(); } void IvWCSDockWidget::on_posAngleSlider_sliderMoved(int position) { QSlider *slider = qobject_cast(sender()); double oldPA = getPosAnglefromCD(cd11_orig, cd12_orig, cd21_orig, cd22_orig, true); // in [deg] double newPA = oldPA + translatePosAngleSlider(position, slider->maximum()); // in [deg] cd11 = cd11_orig; cd12 = cd12_orig; cd21 = cd21_orig; cd22 = cd22_orig; rotateCDmatrix(cd11, cd12, cd21, cd22, newPA); emit CDmatrixChanged(cd11, cd12, cd21, cd22); updateLineEdits(); } void IvWCSDockWidget::on_resetPushButton_clicked() { cd11 = cd11_orig; cd12 = cd12_orig; cd21 = cd21_orig; cd22 = cd22_orig; updateLineEdits(); restoreSliders(); emit CDmatrixChanged(cd11, cd12, cd21, cd22); } void IvWCSDockWidget::updateLineEdits() { ui->cd11LineEdit->setText(QString::number(cd11, 'e', 6)); ui->cd12LineEdit->setText(QString::number(cd12, 'e', 6)); ui->cd21LineEdit->setText(QString::number(cd21, 'e', 6)); ui->cd22LineEdit->setText(QString::number(cd22, 'e', 6)); double pscale1 = sqrt(cd11 * cd11 + cd21 * cd21); double pscale2 = sqrt(cd12 * cd12 + cd22 * cd22); QString pscale = QString::number(0.5*(pscale1+pscale2)*3600., 'f', 6); ui->plateScaleLineEdit->setText(pscale); QString PA = QString::number(getPosAnglefromCD(cd11, cd12, cd21, cd22), 'f', 2); // in [deg] ui->posAngleLineEdit->setText(PA); } void IvWCSDockWidget::restoreSliders() { ui->cd11Slider->setValue(0); ui->cd12Slider->setValue(0); ui->cd21Slider->setValue(0); ui->cd22Slider->setValue(0); ui->plateScaleSlider->setValue(0); ui->posAngleSlider->setValue(0); } void IvWCSDockWidget::on_cd11Slider_sliderReleased() { emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22); } void IvWCSDockWidget::on_cd12Slider_sliderReleased() { emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22); } void IvWCSDockWidget::on_cd21Slider_sliderReleased() { emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22); } void IvWCSDockWidget::on_cd22Slider_sliderReleased() { emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22); } THELI-3.1.3/src/iview/dockwidgets/ivwcsdockwidget.h000066400000000000000000000046211417631501300221610ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVWCSDOCKWIDGET_H #define IVWCSDOCKWIDGET_H #include namespace Ui { class IvWCSDockWidget; } class IvWCSDockWidget : public QDockWidget { Q_OBJECT public: explicit IvWCSDockWidget(QWidget *parent = 0); ~IvWCSDockWidget(); double cd11_orig = 0.; double cd12_orig = 0.; double cd21_orig = 0.; double cd22_orig = 0.; double crpix1_orig = 0.; double crpix2_orig = 0.; double crval1_orig = 0.; double crval2_orig = 0.; void init(); private slots: void on_cd11Slider_sliderMoved(int position); void on_cd12Slider_sliderMoved(int position); void on_cd21Slider_sliderMoved(int position); void on_cd22Slider_sliderMoved(int position); void on_plateScaleSlider_sliderMoved(int position); void on_posAngleSlider_sliderMoved(int position); void on_resetPushButton_clicked(); void on_cd11Slider_sliderReleased(); void on_cd12Slider_sliderReleased(); void on_cd21Slider_sliderReleased(); void on_cd22Slider_sliderReleased(); private: Ui::IvWCSDockWidget *ui; double cd11 = 0.; double cd12 = 0.; double cd21 = 0.; double cd22 = 0.; double crpix1 = 0.; double crpix2 = 0.; double crval1 = 0.; double crval2 = 0.; double translateCDmatrixSlider(int position, int maxRange); double translatePlateScaleSlider(int position, int maxRange); double translatePosAngleSlider(int position, int maxRange); void updateLineEdits(); void restoreSliders(); float calcCDweight(); signals: void CDmatrixChanged(double cd11, double cd12, double cd21, double cd22); void CDmatrixChangedFITS(double cd11, double cd12, double cd21, double cd22); void CRPIXchanged(double crpix); }; #endif // IVWCSDOCKWIDGET_H THELI-3.1.3/src/iview/dockwidgets/ivwcsdockwidget.ui000066400000000000000000000160251417631501300223500ustar00rootroot00000000000000 IvWCSDockWidget 0 0 168 324 168 324 168 524287 Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea CD matrix 0 CD1_1 Qt::NoFocus -100 100 Qt::Horizontal CD1_2 Qt::NoFocus -100 100 Qt::Horizontal CD2_1 Qt::NoFocus -100 100 Qt::Horizontal CD2_2 Qt::NoFocus -100 100 Qt::Horizontal Plate scale The plate scale in arcsec / pixel Qt::NoFocus -100 100 Qt::Horizontal Pos. angle Position angle, counting North over East Qt::NoFocus -100 100 Qt::Horizontal Restore original WCS Qt::Vertical QSizePolicy::Expanding 20 0 cd11LineEdit cd12LineEdit cd21LineEdit cd22LineEdit plateScaleLineEdit posAngleLineEdit cd12Slider cd22Slider cd11Slider plateScaleSlider cd21Slider posAngleSlider resetPushButton THELI-3.1.3/src/iview/events.cc000066400000000000000000000734041417631501300161210ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "iview.h" #include "ui_iview.h" #include "../functions.h" #include "mygraphicsview.h" #include "mygraphicsellipseitem.h" #include "mygraphicsscene.h" #include "ui_ivconfdockwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include void IView::initSeparationVector(QPointF pointStart) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; startLeftClickInsideItem = false; QList listStart = scene->items(pointStart, Qt::IntersectsItemShape); for (auto & it : listStart) { if (it->type() == QGraphicsEllipseItem::Type) startLeftClickInsideItem = true; } } void IView::initDynrangeDrag() { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; dynRangeMinDragStart = dynRangeMin; dynRangeMaxDragStart = dynRangeMax; // Must clear all items on the scene, then redraw afterwards if (!skyCircleItems.isEmpty()) skyCircleItems.clear(); if (!sourceCatItems.isEmpty()) sourceCatItems.clear(); if (!refCatItems.isEmpty()) refCatItems.clear(); if (!acceptedSkyCircleItems.isEmpty()) { for (auto &it : acceptedSkyCircleItems) { scene->removeItem(it); } } if (scene->crosshairShown) scene->removeCrosshair(); clearAxes(); } void IView::showCurrentMousePos(QPointF point) { // This function receives the image coords from a mouseMoveEvent // and translates them // Cursor coordinates: // Still have to mirror in y, and add a half pixel correction // to be conform with the FITS standard if (displayMode == "CLEAR" || displayMode.contains("SCAMP") || !currentMyImage) return; float x_cursor; float y_cursor; // constant offsets required to show same coordinates as in skycat / ds9 x_cursor = point.x() + 0.5; y_cursor = naxis2 - point.y() + 0.5; // Display the information QString xpos = QString::number(x_cursor); QString ypos = QString::number(y_cursor); icdw->ui->xposLabel->setText(xpos); icdw->ui->yposLabel->setText(ypos); // Pixel index in the 2D image long i = x_cursor - 0.5; long j = y_cursor - 0.5; if (i=0 && j=0) { if (displayMode == "FITSmonochrome" || displayMode == "MEMview") { QString value = QString::number(fitsData[i+naxis1*j]); icdw->ui->valueLabel->setText(value); } else { // Color FITS QString rval = QString::number(fitsDataR[i+naxis1*j]); QString gval = QString::number(fitsDataG[i+naxis1*j]); QString bval = QString::number(fitsDataB[i+naxis1*j]); icdw->ui->valueLabel->setText(rval); icdw->ui->valueGreenLabel->setText(gval); icdw->ui->valueBlueLabel->setText(bval); } } else { if (displayMode == "FITSmonochrome" || displayMode == "MEMview") { icdw->ui->valueLabel->setText(""); } else { icdw->ui->valueLabel->setText(""); icdw->ui->valueGreenLabel->setText(""); icdw->ui->valueBlueLabel->setText(""); } } xy2sky(x_cursor, y_cursor); // Show the magnified area in the magnify window // Translate FITS pixel position in the large window to the magnify window icdw->magnifiedGraphicsView->mapFromScene(point.x(),point.y()); icdw->magnifiedGraphicsView->setScene(icdw->magnifiedScene); icdw->magnifiedGraphicsView->show(); } void IView::collectLocalStatisticsSample(QPointF point) { if (!statdw->isVisible()) return; // Pixel index in the 2D image long x = point.x(); long y = naxis2 - point.y(); int s = statdw->statWidth; int imin = x-s; int imax = x+s; int jmin = y-s; int jmax = y+s; if (imin < 0) imin = 0; if (imax >= naxis1) imax = naxis1-1; if (jmin < 0) jmin = 0; if (jmax >= naxis2) jmax = naxis2-1; if (displayMode == "FITSmonochrome" || displayMode == "MEMview") { QVector sample; for (int j = jmin; j<=jmax; ++j) { for (int i = imin; i<=imax; ++i) { sample.append(fitsData[i+naxis1*j]); } } emit statisticsSampleAvailable(sample); } else if (displayMode == "FITScolor") { QVector sampleR; QVector sampleG; QVector sampleB; for (int j = jmin; j<=jmax; ++j) { for (int i = imin; i<=imax; ++i) { sampleR.append(fitsDataR[i+naxis1*j]); sampleG.append(fitsDataG[i+naxis1*j]); sampleB.append(fitsDataB[i+naxis1*j]); } } emit statisticsSampleColorAvailable(sampleR, sampleG, sampleB); } } void IView::adjustBrightnessContrast(QPointF point) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR" || !currentMyImage) return; // Also leave if actively cycling through images // (will crash because the scene items become unavailable while dragging) // Or (NOT IMPLEMENTED): stop cycling through images if (ui->actionForward->isChecked()) return; if (ui->actionBack->isChecked()) return; icdw->ui->autocontrastPushButton->setChecked(false); // This slot receives the right-click drag vector int dx = point.x(); int dy = point.y(); // Adjust brightness level (shift lower bound of dynamic range) // Adjust contrast symmetrically around float range = dynRangeMaxDragStart - dynRangeMinDragStart; // dynRangeMin = dynRangeMinDragStart * (1.1*(100.+dy)/100.+0.01) - 7*dx; // dynRangeMax = dynRangeMaxDragStart / (1.1*(100.+dy)/100.+0.01); float cutoff = 0.95; float scaling = dy/100.*cutoff; if (scaling > cutoff) scaling = cutoff; if (scaling < -cutoff) scaling = -cutoff; float deltaRange = - 0.5 * range * scaling; dynRangeMax = dynRangeMaxDragStart - deltaRange; // dynRangeMin = dynRangeMinDragStart + deltaRange + 7*dx; dynRangeMin = dynRangeMinDragStart + deltaRange + range*0.4*dx/100; // qDebug() << dynRangeMinDragStart << deltaRange << 7*dx << scaling << dy; // if (dynRangeMin <= 1.01*dynRangeMin) dynRangeMax = 1.01*dynRangeMin; int validDigits = 3-log(fabs(dynRangeMax))/log(10); if (validDigits<0) validDigits = 0; icdw->ui->minLineEdit->setText(QString::number(dynRangeMin,'f',validDigits)); icdw->ui->maxLineEdit->setText(QString::number(dynRangeMax,'f',validDigits)); mapFITS(); myGraphicsView->setScene(scene); myGraphicsView->show(); // Show the magnified area in the magnify window icdw->magnifiedGraphicsView->setScene(icdw->magnifiedScene); icdw->magnifiedGraphicsView->show(); emit updateNavigatorBinned(binnedPixmapItem); if (wcs != nullptr && wcsInit != false) { emit updateNavigatorBinnedWCS(wcs, wcsInit); } } double IView::haversine(double x1, double y1, double x2, double y2) { if (!wcsInit) return 0.; double world1[2]; double world2[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; int stat[1]; // zero-indexing of C++ vectors can be ignored when measuring distances. pixcrd[0] = x1; pixcrd[1] = y1; wcsp2s(wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world1, stat); double alpha1 = world1[0] * rad; double delta1 = world1[1] * rad; // Get alpha / delta for the 2nd point pixcrd[0] = x2; pixcrd[1] = y2; wcsp2s(wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world2, stat); double alpha2 = world2[0] * rad; double delta2 = world2[1] * rad; double dDelta = delta2 - delta1; double dAlpha = alpha2 - alpha1; // Haversine formula to calculate angular distance between two points on a sphere in degrees, also works for very small separations return 2.*asin( sqrt( pow(sin(dDelta/2.),2) + cos(delta1)*cos(delta2)*pow(sin(dAlpha/2.),2))) / rad; } void IView::measureAngularSeparations(QPointF pointStart, QPointF pointEnd, double &sepX, double &sepY, double &sepD) { qreal x1 = pointStart.x(); qreal y1 = pointStart.y(); qreal x2 = pointEnd.x(); qreal y2 = pointEnd.y(); // The "diagonal" sepD = haversine(x1, y1, x2, y2) * 3600.; // The "horizontal" sepX = haversine(x1, y1, x2, y1) * 3600.; // The "vertical" sepY = haversine(x1, y1, x1, y2) * 3600.; } void IView::drawSeparationVector(QPointF pointStart, QPointF pointEnd) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR" || !currentMyImage) return; if (zdw->isVisible()) return; // (will crash because the scene items become unavailable while dragging) if (ui->actionForward->isChecked()) return; if (ui->actionBack->isChecked()) return; // don't draw the vector if there is an ellipse underneath if (startLeftClickInsideItem) return; // QPen pen(QColor("#ffaa00")); QPen pen(QColor("#35ffff")); pen.setWidth(0); // QPen penDashed(QColor("#ffaa00")); QPen penDashed(QColor("#35ffff")); penDashed.setWidth(0); QVector dashes; dashes << 5 << 5; penDashed.setDashPattern(dashes); qreal x1 = pointStart.x(); qreal y1 = pointStart.y(); qreal x2 = pointEnd.x(); qreal y2 = pointEnd.y(); qreal dy = y2-y1; qreal dx = x2-x1; double sepX = 0.; double sepY = 0.; double sepD = 0.; measureAngularSeparations(pointStart, pointEnd, sepX, sepY, sepD); QString sepXString = getVectorLabel(sepX); QString sepYString = getVectorLabel(sepY); QString sepDString = getVectorLabel(sepD); clearVectorItems(); QGraphicsTextItem *labelX = scene->addText(sepXString); QGraphicsTextItem *labelY = scene->addText(sepYString); QGraphicsTextItem *labelD = scene->addText(sepDString); QFont currentFont = this->font(); qreal rescale; if (!icdw->ui->zoomFitPushButton->isChecked()) rescale = icdw->zoom2scale(zoomLevel); else rescale = myGraphicsView->transform().m11(); currentFont.setPointSize(int(float(currentFont.pointSize())/rescale)); labelX->setFont(currentFont); labelY->setFont(currentFont); labelD->setFont(currentFont); //labelX->setDefaultTextColor(QColor("#ffff00")); //labelY->setDefaultTextColor(QColor("#ffff00")); //labelD->setDefaultTextColor(QColor("#ffff00")); // use an orange background (same as #ffaa00) for the angular distances labelX->setHtml(QString("
" + QString(" ") + sepXString + QString(" ") + QString("
") )); labelY->setHtml(QString("
" + QString(" ") + sepYString + QString(" ") + QString("
") )); labelD->setHtml(QString("
" + QString(" ") + sepDString + QString(" ") + QString("
") )); // labelX->setHtml(QString("
" + QString(" ") + sepXString + QString(" ") + QString("
") )); // labelY->setHtml(QString("
" + QString(" ") + sepYString + QString(" ") + QString("
") )); // labelD->setHtml(QString("
" + QString(" ") + sepDString + QString(" ") + QString("
") )); labelX->setDefaultTextColor(QColor("#000000")); labelY->setDefaultTextColor(QColor("#000000")); labelD->setDefaultTextColor(QColor("#000000")); qreal xpos = 0.5*(x1+x2); qreal ypos = 0.5*(y1+y2); qreal x_yoffset = 0.; qreal y_xoffset = 0.; qreal d_xoffset = 0; qreal d_yoffset = 0; getVectorOffsets(dx, dy, x_yoffset, y_xoffset, d_xoffset, d_yoffset); labelX->setPos(xpos-20/icdw->zoom2scale(zoomLevel), y1+x_yoffset); labelY->setPos(x2+y_xoffset, ypos-10/icdw->zoom2scale(zoomLevel)); labelD->setPos(xpos+d_xoffset, ypos+d_yoffset); vectorLineItems.append(scene->addLine(x1, y1, x2, y2, pen)); // diagonal vectorLineItems.append(scene->addLine(x1, y1, x2, y1, penDashed)); // horizontal vectorLineItems.append(scene->addLine(x2, y1, x2, y2, penDashed)); // vertical vectorTextItems.append(labelX); vectorTextItems.append(labelY); vectorTextItems.append(labelD); myGraphicsView->setScene(scene); myGraphicsView->show(); } // Used to draw separation vectors void IView::getVectorOffsets(const qreal dx, const qreal dy, qreal &x_yoffset, qreal &y_xoffset, qreal &d_xoffset, qreal &d_yoffset) { qreal s; if (!icdw->ui->zoomFitPushButton->isChecked()) { s = icdw->zoom2scale(zoomLevel); } else { s = myGraphicsView->transform().m11(); } if (dy < 0) x_yoffset = 10/s; else x_yoffset = -30/s; if (dx < 0) y_xoffset = -70/s; else y_xoffset = 10/s; if (dx>=0 && dy>=0) { d_xoffset = -50/s; d_yoffset = 10/s; } else if (dx<0 && dy>=0) { d_xoffset = 10/s; d_yoffset = 10/s; } else if (dx<0 && dy<0) { d_xoffset = 10/s; d_yoffset = -25/s; } else { // (dx>=0 && dy<0) d_xoffset = -50/s; d_yoffset = -50/s; } } void IView::clearVectorItems() { if (!vectorLineItems.isEmpty()) { for (auto &it : vectorLineItems ) scene->removeItem(it); vectorLineItems.clear(); } if (!vectorTextItems.isEmpty()) { for (auto &it : vectorTextItems ) scene->removeItem(it); vectorTextItems.clear(); } } void IView::clearSkyRectItems() { if (!skyRectItems.isEmpty()) { for (auto &it : skyRectItems ) scene->removeItem(it); skyRectItems.clear(); } if (!skyTextItems.isEmpty()) { for (auto &it : skyTextItems ) scene->removeItem(it); skyTextItems.clear(); } } void IView::clearMaskPolygonItems() { if (!maskPolygonItems.isEmpty()) { for (auto &it : maskPolygonItems ) scene->removeItem(it); maskPolygonItems.clear(); } } void IView::clearMaskRectItems() { if (!maskRectItems.isEmpty()) { for (auto &it : maskRectItems ) scene->removeItem(it); maskRectItems.clear(); } } void IView::clearSkyCircleItems() { if (!skyCircleItems.isEmpty()) { for (auto &it : skyCircleItems ) scene->removeItem(it); skyCircleItems.clear(); } } // currently unused void IView::drawSkyRectangle(QPointF pointStart, QPointF pointEnd) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR" || !currentMyImage) return; if (displayMode == "FITScolor") return; // (will crash because the scene items become unavailable while dragging) if (ui->actionForward->isChecked()) return; if (ui->actionBack->isChecked()) return; QPen pen(QColor("#00ff00")); pen.setWidth(0); qreal x1 = pointStart.x(); qreal y1 = pointStart.y(); qreal x2 = pointEnd.x(); qreal y2 = pointEnd.y(); qreal dx = fabs(x2-x1); qreal dy = fabs(y2-y1); // Collect alpha and delta of the four vertices QVector alphaValues; QVector deltaValues; // TODO if routine is activated: must translate x/y to FITS coordinate system before computing sky coordinates! xy2sky(x1,y1,"middleButton"); alphaValues.append(skyRa); deltaValues.append(skyDec); xy2sky(x2,y1,"middleButton"); alphaValues.append(skyRa); deltaValues.append(skyDec); xy2sky(x2,y2,"middleButton"); alphaValues.append(skyRa); deltaValues.append(skyDec); xy2sky(x1,y2,"middleButton"); alphaValues.append(skyRa); deltaValues.append(skyDec); double alphaMin = minVec_T(alphaValues); double alphaMax = maxVec_T(alphaValues); double deltaMin = minVec_T(deltaValues); double deltaMax = maxVec_T(deltaValues); QString raMin = QString::number(alphaMin,'f',6); QString raMax = QString::number(alphaMax,'f',6); QString decMin = QString::number(deltaMin,'f',6); QString decMax = QString::number(deltaMax,'f',6); QString skyBox = "R.A. min = "+raMin+"\n"; skyBox.append("R.A. max = "+raMax+"\n"); skyBox.append("DEC min = "+decMin+"\n"); skyBox.append("DEC max = "+decMax); QGraphicsTextItem *labelSkyBox = scene->addText(skyBox); QFont currentFont = this->font(); qreal rescale; if (!icdw->ui->zoomFitPushButton->isChecked()) rescale = icdw->zoom2scale(zoomLevel); else rescale = myGraphicsView->transform().m11(); currentFont.setPointSize(int(float(currentFont.pointSize())/rescale)); labelSkyBox->setFont(currentFont); labelSkyBox->setDefaultTextColor(QColor("#00ff00")); labelSkyBox->setPos(x1, y1-100/rescale); clearSkyRectItems(); qreal xmin = pointStart.x(); qreal ymin = pointStart.y(); if (pointEnd.x() < xmin) xmin = pointEnd.x(); if (pointEnd.y() < ymin) ymin = pointEnd.y(); skyRectItems.append(scene->addRect(xmin, ymin, dx, dy, pen)); skyTextItems.append(labelSkyBox); myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::middlePressResetCRPIXreceived() { if (!wcsInit) return; crpix1_start = wcs->crpix[0]; crpix2_start = wcs->crpix[1]; } /* // Receiver for the event when the mouse enters the main graphics view void IView::mouseEnteredViewReceived() { // icdw->ui->navigatorStackedWidget->setCurrentIndex(1); emit updateNavigatorBinned(binnedPixmapItem); } // Receiver for the event when the mouse leaves the main graphics view void IView::mouseLeftViewReceived() { // icdw->ui->navigatorStackedWidget->setCurrentIndex(0); emit updateNavigatorBinned(binnedPixmapItem); } */ void IView::viewportChangedReceived(QRect viewport_rect) { // the currently shown image area, in QImage coordinates QRectF rect = myGraphicsView->mapToScene(viewport_rect).boundingRect(); // the matching area, in QImage coordinates of the binned overview image QRect rectBinned = qimageToBinned(rect); // send the binned rect to the binned navigator window emit updateNavigatorBinnedViewport(rectBinned); } void IView::updateCRPIX(QPointF pointStart, QPointF pointEnd) { if (!wcsInit) return; // Do nothing if no refcat items are displayed. if (refCatItems.isEmpty()) return; // Remove items from display for (auto &it: refCatItems) scene->removeItem(it); refCatItems.clear(); scene->removeCrosshair(); myGraphicsView->setScene(scene); myGraphicsView->show(); scene->removeCrosshair(); // Recalculate CRPIX offset qreal dx = pointEnd.x() - pointStart.x(); qreal dy = -(pointEnd.y() - pointStart.y()); // Image y-axis flipped in graphics view wcs->crpix[0] = crpix1_start + dx; wcs->crpix[1] = crpix2_start + dy; wcs->flag = 0; // force an update of internal wcs params. showReferenceCat(); checkFinder(); } void IView::updateCDmatrix(double cd11, double cd12, double cd21, double cd22) { if (!wcsInit) return; // Do nothing if no refcat items are displayed. if (refCatItems.isEmpty()) return; // Remove items from display for (auto &it: refCatItems) scene->removeItem(it); refCatItems.clear(); scene->removeCrosshair(); myGraphicsView->setScene(scene); myGraphicsView->show(); // Update CD matrix wcs->cd[0] = cd11; wcs->cd[1] = cd12; wcs->cd[2] = cd21; wcs->cd[3] = cd22; wcs->flag = 0; // force an update of internal wcs params. icdw->cd11 = cd11; icdw->cd12 = cd12; icdw->cd21 = cd21; icdw->cd22 = cd22; showReferenceCat(); checkFinder(); } // Called when middle mouse button is released in wcs mode void IView::updateCRPIXFITS() { if (!wcsInit) return; if (!currentMyImage) return; // Do nothing if no refcat items are displayed. if (refCatItems.isEmpty()) return; int status = 0; if (currentFileName.isEmpty()) currentFileName = currentMyImage->baseName+".fits"; // force drive dump if FITS file does not exist yet if (!currentMyImage->imageOnDrive) currentMyImage->writeImage(); // Identical way to reconstruct filenames // TODO: uniformize // qDebug() << currentFileName; // qDebug() << currentMyImage->path+"/"+currentMyImage->chipName+currentMyImage->processingStatus->statusString+".fits"; fitsfile *fptr = nullptr; fits_open_file(&fptr, (dirName+"/"+currentMyImage->pathExtension+"/"+currentFileName).toUtf8().data(), READWRITE, &status); fits_update_key_flt(fptr, "CRPIX1", wcs->crpix[0], -5, nullptr, &status); fits_update_key_flt(fptr, "CRPIX2", wcs->crpix[1], -5, nullptr, &status); fits_close_file(fptr, &status); if (status > 0) qDebug() << "IView::updateCRPIXFITS(): cfitsio error code = " << status << dirName+"/"+currentFileName; } // Called when slider is released in wcs mode void IView::updateCDmatrixFITS() { if (!wcsInit) return; if (!currentMyImage) return; // Do nothing if no refcat items are displayed. if (refCatItems.isEmpty()) return; int status = 0; if (currentFileName.isEmpty()) currentFileName = currentMyImage->baseName+".fits"; fitsfile *fptr = nullptr; fits_open_file(&fptr, (dirName+"/"+currentMyImage->pathExtension+"/"+currentFileName).toUtf8().data(), READWRITE, &status); fits_update_key_dbl(fptr, "CD1_1", wcs->cd[0], 8, nullptr, &status); fits_update_key_dbl(fptr, "CD1_2", wcs->cd[1], 8, nullptr, &status); fits_update_key_dbl(fptr, "CD2_1", wcs->cd[2], 8, nullptr, &status); fits_update_key_dbl(fptr, "CD2_2", wcs->cd[3], 8, nullptr, &status); fits_close_file(fptr, &status); if (status > 0) qDebug() << "IView::updateCDmatrixFITS(): cfitsio error code = " << status << dirName+"/"+currentFileName; } void IView::drawSkyCircle(QPointF pointStart, QPointF pointEnd) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; if (displayMode == "FITScolor") return; QPen pen(QColor("#00ff00")); pen.setWidth(0); QVector dashes; dashes << 3 << 3; pen.setDashPattern(dashes); qreal x1 = pointStart.x(); qreal y1 = pointStart.y(); qreal x2 = pointEnd.x(); qreal y2 = pointEnd.y(); qreal xcen = 0.5*(x1+x2); qreal ycen = 0.5*(y1+y2); qreal dx = fabs(x2-x1); qreal dy = fabs(y2-y1); qreal radius = sqrt(dx*dx+dy*dy); // Collect alpha and delta of the first click // Set 'skyRa' and 'skyDec' xy2sky(xcen,ycen,"middleButton"); clearSkyCircleItems(); QGraphicsEllipseItem *ellipse = scene->addEllipse(x1-radius, y1-radius, 2.*radius, 2.*radius, pen); ellipse->setFlags(QGraphicsEllipseItem::ItemIsSelectable | QGraphicsEllipseItem::ItemIsMovable); skyCircleItems.append(ellipse); myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::drawMaskingPolygon(QPointF pointStart, QPointF pointEnd) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; if (displayMode == "FITScolor") return; QPen pen(QColor("#00ff00")); pen.setWidth(0); qreal x1 = pointStart.x(); qreal y1 = pointStart.y(); qreal x2 = pointEnd.x(); qreal y2 = pointEnd.y(); clearMaskRectItems(); QRectF rect; QGraphicsRectItem *rectItem = scene->addRect(QRectF(QPoint(x1,y1), QPoint(x2,y2))); rectItem->setPen(pen); rectItem->setFlags(QGraphicsRectItem::ItemIsSelectable | QGraphicsRectItem::ItemIsMovable); maskRectItems.append(rectItem); myGraphicsView->setScene(scene); myGraphicsView->show(); } /* void IView::drawMaskingPolygon(QPointF pointStart, QPointF pointEnd) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; if (displayMode == "FITScolor") return; QPen pen(QColor("#00ff00")); pen.setWidth(0); qreal x1 = pointStart.x(); qreal y1 = pointStart.y(); qreal x2 = pointEnd.x(); qreal y2 = pointEnd.y(); clearMaskPolygonItems(); QPolygonF polygon; polygon << QPoint(x1,y1) << QPoint(x2,y2); QGraphicsPolygonItem *polygonItem = scene->addPolygon(polygon); polygonItem->setPen(pen); polygonItem->setFlags(QGraphicsPolygonItem::ItemIsSelectable | QGraphicsPolygonItem::ItemIsMovable); maskPolygonItems.append(polygonItem); myGraphicsView->setScene(scene); myGraphicsView->show(); } */ void IView::appendSkyCircle() { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; if (displayMode == "FITScolor") return; // Fetch the last item drawn and add it to the permanent list QGraphicsItem *lastItem = scene->items(Qt::AscendingOrder).last(); QPen pen(QColor("#00ff00")); pen.setWidth(0); if (lastItem->type() == QGraphicsEllipseItem::Type) { QGraphicsEllipseItem *ellipse = qgraphicsitem_cast(lastItem); ellipse->setPen(pen); acceptedSkyCircleItems.append(ellipse); } // Clear the temporary display (ellipses shown while dragging) clearSkyCircleItems(); // Add the last state of the drawn ellipse item to the scene if (!acceptedSkyCircleItems.isEmpty()) { scene->addItem(acceptedSkyCircleItems.last()); } // Update the data record in the external file dumpSkyCircleCoordinates(); } void IView::updateSkyCircles() { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; if (displayMode == "FITScolor") return; // A selected sky circle has been removed by a key press event, or moved by mouse drag // Update the underlying QList by fetching all visible sky circles acceptedSkyCircleItems.clear(); QList list = scene->items(); for (auto &it : list) { if (it->type() == QGraphicsEllipseItem::Type) { acceptedSkyCircleItems.append(qgraphicsitem_cast(it)); } } // Update the data record in the external file dumpSkyCircleCoordinates(); } // invoked e.g. when dynamic range is changed void IView::redrawSkyCirclesAndCats() { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; if (displayMode == "FITScolor") return; if (!acceptedSkyCircleItems.isEmpty()) { for (auto &it: acceptedSkyCircleItems) { scene->addItem(it); } } showSourceCat(); showReferenceCat(); checkFinderBypass(); redrawUpdateAxes(); } void IView::dumpSkyCircleCoordinates() { // Dump the centers and radii of the sky circles to an external file QFile skysamples(startDirName+"/skysamples.dat"); if (skysamples.open(QIODevice::WriteOnly)) { QTextStream outputStream(&skysamples); for (auto &it : acceptedSkyCircleItems) { // Store the coordinates in decimal Ra Dec radius [arcsec] QRectF bound = it->sceneBoundingRect(); double xcen = bound.center().x(); double ycen = naxis2-bound.center().y(); xy2sky(xcen, ycen, "middleButton"); double radius = bound.height()/2.*plateScale; outputStream.setRealNumberPrecision(9); outputStream << skyRa << " " << skyDec << " " << radius << "\n"; } skysamples.close(); } // Create a copy in the parent folder (if we have several science directories of the same target) QFile copy(startDirName+"/../skysamples.dat"); if (copy.exists()) copy.remove(); skysamples.copy(startDirName+"/../skysamples.dat"); } void IView::clearSeparationVector() { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; clearVectorItems(); myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::xy2sky(double x, double y, QString button) { if (!wcsInit) return; double world[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; pixcrd[0] = x; pixcrd[1] = y; int stat[1]; wcsp2s(wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world, stat); // not used by all calls to this function if (button == "middleButton") { skyRa = world[0]; skyDec = world[1]; return; } QString alphaDec = QString::number(world[0],'f',6); QString deltaDec = QString::number(world[1],'f',6); QString alphaHex = dec2hex(world[0]/15.).remove("+"); QString deltaHex = dec2hex(world[1]); icdw->ui->alphaDecLabel->setText(alphaDec); icdw->ui->alphaHexLabel->setText(alphaHex); icdw->ui->deltaDecLabel->setText(deltaDec); icdw->ui->deltaHexLabel->setText(deltaHex); } // Unused /* void IView::xy2sky_linear(double x, double y, QString button) { double pi = 3.14159265; double dx = x - crpix1; double dy = y - crpix2; double xt = cd1_1*dx + cd2_1*dy; double yt = cd1_2*dx + cd2_2*dy; double delta = crval2 + yt; double alpha = crval1 + xt / cos(delta * pi/180.); // not used by all calls to this function if (button == "middleButton") { skyRa = alpha; skyDec = delta; return; } QString alphaDec = QString::number(alpha,'f',6); QString deltaDec = QString::number(delta,'f',6); QString alphaHex = dec2hex(alpha/15.).remove("+"); QString deltaHex = dec2hex(delta); icdw->ui->alphaDecLabel->setText("R.A. = "+alphaDec); icdw->ui->alphaHexLabel->setText("R.A. = "+alphaHex); icdw->ui->deltaDecLabel->setText("Dec = "+deltaDec); icdw->ui->deltaHexLabel->setText("Dec = "+deltaHex); } */ THELI-3.1.3/src/iview/iview.cc000066400000000000000000001515201417631501300157340ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "iview.h" #include "ui_iview.h" #include "../functions.h" #include "mygraphicsview.h" #include "mygraphicsellipseitem.h" #include "mygraphicsscene.h" #include "dockwidgets/ivconfdockwidget.h" #include "dockwidgets/ivscampdockwidget.h" #include "dockwidgets/ivcolordockwidget.h" #include "dockwidgets/ivwcsdockwidget.h" #include "dockwidgets/ivstatisticsdockwidget.h" #include "dockwidgets/ivfinderdockwidget.h" #include "ui_ivconfdockwidget.h" #include "ui_ivcolordockwidget.h" #include "ui_ivstatisticsdockwidget.h" #include "ui_ivfinderdockwidget.h" #include "../tools/tools.h" #include "../myimage/myimage.h" #include "fitsio2.h" #include "wcs.h" #include "wcshdr.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void IView::setMiddleMouseMode(QString mode) { if (mode == "SkyMode") { ui->actionSkyMode->setChecked(true); ui->actionDragMode->setChecked(false); ui->actionWCSMode->setChecked(false); ui->actionMaskingMode->setChecked(false); myGraphicsView->middleMouseMode = "SkyMode"; hideWCSdockWidget(); icdw->ui->quitPushButton->show(); } else if (mode == "DragMode") { ui->actionDragMode->setChecked(true); ui->actionSkyMode->setChecked(false); ui->actionWCSMode->setChecked(false); ui->actionMaskingMode->setChecked(false); middleMouseMode = "DragMode"; hideWCSdockWidget(); icdw->ui->quitPushButton->hide(); } else if (mode == "WCSMode") { ui->actionWCSMode->setChecked(true); ui->actionSkyMode->setChecked(false); ui->actionDragMode->setChecked(false); ui->actionMaskingMode->setChecked(false); middleMouseMode = "WCSMode"; showWCSdockWidget(); icdw->ui->quitPushButton->hide(); } else if (mode == "MaskingMode") { ui->actionMaskingMode->setChecked(true); ui->actionSkyMode->setChecked(false); ui->actionDragMode->setChecked(false); ui->actionWCSMode->setChecked(false); middleMouseMode = "MaskingMode"; hideWCSdockWidget(); icdw->ui->quitPushButton->hide(); } } void IView::sendWCStoWCSdockWidget() { if (!wcsInit) return; // Catching spectroscopic exposures or other exposures with invalid "imaging" WCS if (!wcs) { wcsdw->init(); return; } // Copy the CD matrix to the WCS dock widget and init() wcsdw->cd11_orig = wcs->cd[0]; wcsdw->cd12_orig = wcs->cd[1]; wcsdw->cd21_orig = wcs->cd[2]; wcsdw->cd22_orig = wcs->cd[3]; wcsdw->crpix1_orig = wcs->crpix[0]; wcsdw->crpix2_orig = wcs->crpix[1]; wcsdw->crval1_orig = wcs->crval[0]; wcsdw->crval2_orig = wcs->crval[1]; wcsdw->init(); } void IView::showWCSdockWidget() { if (!wcs || ! wcsInit) { QMessageBox msgBox; msgBox.setText("WCS not found"); msgBox.setInformativeText("This image does not contain any WCS information. The WCS dialog will not be shown.\n\n"); msgBox.addButton(tr("Ok"), QMessageBox::YesRole); msgBox.exec(); wcsdw->setDisabled(true); ui->actionWCSMode->setChecked(false); return; } if (wcsdw->isVisible()) return; sendWCStoWCSdockWidget(); addDockWidget(Qt::LeftDockWidgetArea, wcsdw); wcsdw->setFloating(false); wcsdw->raise(); wcsdw->show(); if (!ui->actionRefCat->isChecked()) { // otherwise showReferenceCat() exits ui->actionRefCat->setChecked(true); } showReferenceCat(); if (refCatItems.isEmpty()) { QMessageBox msgBox; msgBox.setText("No reference sources available"); msgBox.setInformativeText("You must retrieve a reference catalog first before using the WCS module.\n\n"); msgBox.addButton(tr("Ok"), QMessageBox::YesRole); msgBox.exec(); wcsdw->setDisabled(true); ui->actionRefCat->setChecked(false); return; } } void IView::hideWCSdockWidget() { removeDockWidget(wcsdw); wcsdw->hide(); } void IView::resizeEvent(QResizeEvent * event) { event->accept(); if (icdw->ui->zoomFitPushButton->isChecked()) icdw->on_zoomFitPushButton_clicked(); } void IView::sendStatisticsCenter(QPointF point) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return; long x = point.x(); long y = naxis2 - point.y(); emit statisticsRequested(x, y); } QString IView::getVectorLabel(double separation) { QString units; if (separation < 60) { units = "\""; } else if (separation>=60. && separation < 3600.) { separation /= 60.; units = "\'"; } else if (separation > 3600.) { separation /= 3600.; units = "°"; } return QString::number(separation,'f',2)+" "+units; } QRect IView::adjustGeometry() { QRect geometry = myGraphicsView->geometry(); // if the graphics is larger than what the screen can accomodate: int minMargin = 150; myGraphicsView->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); if (naxis2 > screenHeight-minMargin) { myGraphicsView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); geometry.setHeight(screenHeight-minMargin); } else { // myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } if (naxis1 > screenWidth-minMargin) { myGraphicsView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); geometry.setWidth(screenWidth-minMargin); } else { // myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } return geometry; } void IView::setImageList(QString filter) { QDir dir(dirName); QStringList filterList = filter.split(" "); if (dir.exists()) { // filterList << filter; dir.setNameFilters(filterList); imageList = dir.entryList(); } numImages = imageList.length(); // we also need a list of chip names (without the status string) imageListToChipName(); } void IView::setImageListFromMemory() { imageList.clear(); imageListChipName.clear(); for (auto &it : myImageList) { QString imageName = it->chipName + it->processingStatus->statusString + ".fits"; imageList.append(imageName); imageListChipName.append(it->chipName); } } void IView::imageListToChipName() { imageListChipName.clear(); for (auto &it : imageList) { QString rootName = it; rootName.truncate(rootName.lastIndexOf('_')); QStringList list = it.split('_'); QString chipnr = list.last().remove(".fits"); chipnr.remove(QRegExp("[A-Z]")); rootName.append("_"+chipnr); imageListChipName.append(rootName); } } void IView::setCurrentId(QString filename) { // The number of the file in the list of all images (PNG or FITS) in this directory if (filterName.isEmpty() || filterLineEdit->text().isEmpty()) { if (!displayMode.contains("SCAMP")) filterName = "*.fits"; else filterName = "*.png"; filterLineEdit->setText(filterName); } setImageList(filterName); currentId = imageList.indexOf(QFileInfo(filename).fileName()); if (currentId == -1) { qDebug() << "IView::getCurrentId(): Image not found in list." << filterName << numImages << filename; } } void IView::loadImage() { QString filter = filterLineEdit->text(); if (filter.isEmpty() || !filter.contains(".fit") || !filter.contains("*")) { filter = "*.fits"; filterLineEdit->setText(filter); } if (!QDir(dirName).exists()) dirName = QDir::homePath(); if (displayMode.contains("SCAMP")) { currentFileName = QFileDialog::getOpenFileName(this, tr("Select image"), dirName, tr("Images and Scamp checkplots (")+filter+" *.png)"); } else { filter = "*.fits *.fit"; currentFileName = QFileDialog::getOpenFileName(this, tr("Select image"), dirName, tr("Images ")+filter); } if (currentFileName.isEmpty()) return; // Identify file type by suffix QFileInfo fi(currentFileName); QString suffix = fi.suffix(); // update the dirname dirName = fi.absolutePath(); // Update the filter string filterName = "*."+suffix; filterLineEdit->setText(filter); if (suffix == "fits") { switchMode("FITSmonochrome"); // Delete catalog displays, if any clearItems(); // reset the startDirname if in PNG or CLEAR mode previously if (displayMode.contains("SCAMP") || displayMode == "CLEAR") startDirNameSet = false; loadFITS(currentFileName); } else if (suffix == "png") { switchMode("SCAMP"); loadPNG(currentFileName); myGraphicsView->fitInView(scene->items(Qt::AscendingOrder).at(0), Qt::KeepAspectRatio); icdw->on_zoomZeroPushButton_clicked(); } else { switchMode("CLEAR"); } // update the startDirName if (!startDirNameSet) { startDirName = dirName; startDirNameSet = true; } } void IView::clearItems() { // Delete any catalog displays if (!sourceCatItems.isEmpty()) { for (auto &it: sourceCatItems) scene->removeItem(it); sourceCatItems.clear(); sourcecatSourcesShown = false; ui->actionSourceCat->setChecked(false); } if (!refCatItems.isEmpty()) { for (auto &it: refCatItems) scene->removeItem(it); refCatItems.clear(); refcatSourcesShown = false; ui->actionRefCat->setChecked(false); } if (!acceptedSkyCircleItems.isEmpty()) { for (auto &it: acceptedSkyCircleItems) scene->removeItem(it); acceptedSkyCircleItems.clear(); } scene->removeCrosshair(); } void IView::setCatalogOverlaysExternally(bool sourcecatShown, bool refcatShown) { ui->actionSourceCat->setChecked(sourcecatShown); ui->actionRefCat->setChecked(refcatShown); sourcecatSourcesShown = sourcecatShown; refcatSourcesShown = refcatShown; } // Used by imagestatistics void IView::clearAll() { clearItems(); scene->clear(); myGraphicsView->setScene(scene); myGraphicsView->show(); this->setWindowTitle("iView"); pageLabel->clear(); switchMode("CLEAR"); icdw->clearBinnedSceneReceiver(); icdw->clearMagnifiedSceneReceiver(); } void IView::loadFITSexternal(QString fileName, QString filter) { if (!fileName.isEmpty()) { switchMode("FITSmonochrome"); filterName = filter; filterLineEdit->setText(filterName); loadFITS(fileName); } else { switchMode("CLEAR"); filterName = filter; filterLineEdit->setText(filterName); } } // invoked when clicking a data point in image statistics void IView::loadFITSexternalRAM(int index) { switchMode("MEMview"); bool sourcecatShown = sourcecatSourcesShown; bool refcatShown = refcatSourcesShown; clearItems(); loadFromRAM(myImageList[index], 0); currentId = index; setCatalogOverlaysExternally(sourcecatShown, refcatShown); redrawSkyCirclesAndCats(); } void IView::loadPNG(QString filename, int currentId) { if (imageList.isEmpty() || dirName.isEmpty()) { qDebug() << __func__ << " No scamp checkplots found!"; return; } if (filename.isEmpty()) filename = dirName+"/"+imageList.at(currentId); else { setCurrentId(filename); if (currentId == -1) return; } QFileInfo fi(filename); QString showName = fi.fileName(); QPixmap pixmap = QPixmap(filename); naxis1 = pixmap.width(); naxis2 = pixmap.height(); zoomLevel = 0; // icdw->zoom2scale(zoomLevel); // uninitialized myGraphicsView->resetMatrix(); // QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap); pixmapItem = new QGraphicsPixmapItem(pixmap); // Update the view // QRect geometry = adjustGeometry(); scene->clear(); scene->addItem(pixmapItem); myGraphicsView->setScene(scene); myGraphicsView->scale(1.0,1.0); // myGraphicsView->setGeometry(geometry); myGraphicsView->show(); QString prependPath = dirName; removeLastCharIf(prependPath, '/'); QString path = get2ndLastWord(prependPath,'/')+"/"+getLastWord(prependPath,'/'); this->setWindowTitle("iView --- "+path+"/ --- "+showName); pageLabel->setText(QString::number(currentId+1)+" / "+QString::number(numImages)); // icdw->zoom2scale(zoomLevel); myGraphicsView->resetMatrix(); myGraphicsView->setMinimumSize(naxis1,naxis2); myGraphicsView->setMaximumSize(naxis1,naxis2); myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); myGraphicsView->resize(naxis1,naxis2); } void IView::loadFITS(QString filename, int currentId, qreal scaleFactor) { if (filename.isEmpty()) { filename = dirName+"/"+imageList.at(currentId); currentFileName = imageList.at(currentId); } else { setCurrentId(filename); if (currentId == -1) return; } QFileInfo fi(filename); QString showName = fi.fileName(); if (loadFITSdata(filename, fitsData)) { // Map dynamic range to INT, update the scene mapFITS(); // Update the view QRect geometry = adjustGeometry(); myGraphicsView->setScene(scene); myGraphicsView->scale(scaleFactor, scaleFactor); myGraphicsView->setGeometry(geometry); // myGraphicsView->centerOn(pixmapItem); myGraphicsView->show(); myGraphicsView->setMinimumSize(200,200); myGraphicsView->setMaximumSize(10000,10000); QString prependPath = dirName; removeLastCharIf(prependPath, '/'); QString path = getLastWord(prependPath,'/'); this->setWindowTitle("iView --- "+path+"/ --- "+showName); pageLabel->setText(QString::number(currentId+1)+" / "+QString::number(numImages)); // Load the binned image to the navigator emit updateNavigatorBinned(binnedPixmapItem); // binnedPixmapItem created in mapFITS() emit updateNavigatorBinnedWCS(wcs, wcsInit); emit newImageLoaded(); } else { // At end of file list, or file does not exist anymore. // Update file list filterLineEdit_textChanged("dummy"); return; } } /* void IView::loadFromRAMlist(const QModelIndex &index) { loadFromRAM(myImageList[index.row()], index.column()); // Get the center image poststamp; copy() refers to the top left corner, and then width and height QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(naxis1/2.-icdw->navigator_magnified_nx/2., naxis2/2.-icdw->navigator_magnified_ny/2., icdw->navigator_magnified_nx, icdw->navigator_magnified_ny); magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap); // Update the navigator magnified window with the center image poststamp emit updateNavigatorMagnified(magnifiedPixmapItem, icdw->zoom2scale(zoomLevel)*magnify, 0., 0.); } */ // Receiver of Navigator currentMousePos Eevent void IView::updateNavigatorMagnifiedReceived(QPointF point) { // Cap the magnification qreal magnification = icdw->zoom2scale(zoomLevel)*magnify; if (magnification > magnify) magnification = magnify; float dx = 0.; float dy = 0.; if (point.x() < 0 || point.x() > naxis1 || point.y() < 0 || point.y() > naxis2) { emit clearMagnifiedScene(); return; } if (displayMode == "FITSmonochrome" || displayMode == "MEMview") { // qDebug() << point.x() + 1. - icdw->navigator_magnified_nx/2./magnification << point.y() + 1. - icdw->navigator_magnified_ny/2./magnification << // icdw->navigator_magnified_nx/magnification << icdw->navigator_magnified_ny/magnification; if (point.x() + 1. - icdw->navigator_magnified_nx/2./magnification < 0) dx = point.x() + 1. - icdw->navigator_magnified_nx/2./magnification; if (point.x() + 1. - icdw->navigator_magnified_nx/2./magnification >= naxis1) dx = point.x() + 1. - icdw->navigator_magnified_nx/2./magnification; QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(point.x() + 1. - icdw->navigator_magnified_nx/2./magnification, point.y() + 1. - icdw->navigator_magnified_ny/2./magnification, icdw->navigator_magnified_nx/magnification, icdw->navigator_magnified_ny/magnification); magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap); // qDebug() << magnifiedPixmap.width() << magnifiedPixmap.height() << icdw->navigator_magnified_nx/magnification << icdw->navigator_magnified_ny/magnification; } else if (displayMode == "FITScolor") { QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(point.x() + 1. - icdw->navigator_magnified_nx/2/magnification, point.y() + 1. - icdw->navigator_magnified_ny/2/magnification, icdw->navigator_magnified_nx/magnification, icdw->navigator_magnified_ny/magnification); magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap); } else { // Do not emit signal for PNG mode return; } emit updateNavigatorMagnified(magnifiedPixmapItem, magnification, dx, dy); } void IView::loadFromRAM(MyImage *it, int indexColumn) { scene->removeCrosshair(); clearAxes(); currentMyImage = it; if (indexColumn == 0 || indexColumn == 3) { // Load image into memory if not yet present if (!weightMode) { it->readImage(false); fitsData = it->dataCurrent; } else { it->readWeight(); fitsData = it->dataWeight; it->weightInMemory = true; } } else if (indexColumn == 4 && it->backupL1InMemory) fitsData = it->dataBackupL1; else if (indexColumn == 5 && it->backupL2InMemory) fitsData = it->dataBackupL2; else if (indexColumn == 6 && it->backupL3InMemory) fitsData = it->dataBackupL3; else { return; } naxis1 = it->naxis1; naxis2 = it->naxis2; plateScale = it->plateScale; naxis1 = it->naxis1; naxis2 = it->naxis2; wcs = it->wcs; wcsInit = it->wcsInit; finderdw->dateObs = it->dateobs; finderdw->geoLon = it->geolon; finderdw->geoLat = it->geolat; sendWCStoWCSdockWidget(); this->setWindowTitle("iView --- Memory viewer : "+it->chipName); connect(currentMyImage, &MyImage::WCSupdated, this, &IView::WCSupdatedReceived); // Get the dynamic range // Normal viewer mode if (dataIntSet) { delete[] dataInt; dataInt = nullptr; } dataInt = new unsigned char[naxis1*naxis2]; dataIntSet = true; getGlobalImageStatistics(); // AUTO if (icdw->ui->minLineEdit->text().isEmpty() || icdw->ui->maxLineEdit->text().isEmpty() || icdw->ui->autocontrastPushButton->isChecked()) { autoContrast(); } // MANUAL else { // get background statisics (median and sd) dynRangeMin = icdw->ui->minLineEdit->text().toFloat(); dynRangeMax = icdw->ui->maxLineEdit->text().toFloat(); } mapFITS(); // Update the view QRect geometry = adjustGeometry(); myGraphicsView->setScene(scene); myGraphicsView->scale(icdw->zoom2scale(0),icdw->zoom2scale(0)); myGraphicsView->setGeometry(geometry); myGraphicsView->show(); myGraphicsView->setMinimumSize(200,200); myGraphicsView->setMaximumSize(10000,10000); currentMyImage = it; // For later use, in particular when updating CRPIX1/2 currentFileName = currentMyImage->baseName+".fits"; // Get the center image poststamp; copy() refers to the top left corner, and then width and height QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(naxis1/2.-icdw->navigator_magnified_nx/2., naxis2/2.-icdw->navigator_magnified_ny/2., icdw->navigator_magnified_nx, icdw->navigator_magnified_ny); magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap); // Update the navigator magnified window with the center image poststamp emit updateNavigatorMagnified(magnifiedPixmapItem, icdw->zoom2scale(zoomLevel)*magnify, 0., 0.); // Update the navigator binned window with the binned poststamp emit updateNavigatorBinned(binnedPixmapItem); emit updateNavigatorBinnedWCS(wcs, wcsInit); emit newImageLoaded(); } void IView::loadColorFITS(qreal scaleFactor) { QFile redFile(dirName+'/'+ChannelR); QFile greenFile(dirName+'/'+ChannelG); QFile blueFile(dirName+'/'+ChannelB); if (!redFile.exists() || !greenFile.exists() || !blueFile.exists()) return; QString showName = "Color calibrated preview"; bool testR = loadFITSdata(dirName+'/'+ChannelR, fitsDataR, "redChannel"); bool testG = loadFITSdata(dirName+'/'+ChannelG, fitsDataG, "greenChannel"); bool testB = loadFITSdata(dirName+'/'+ChannelB, fitsDataB, "blueChannel"); if (!testR || !testG || !testB) { qDebug() << __func__ << "One or more of the three color channels could not be read!"; qDebug() << ChannelR << ChannelG << ChannelB; return; } allChannelsRead = true; // Map dynamic range to INT, update the scene mapFITS(); // Update the view QRect geometry = adjustGeometry(); myGraphicsView->setScene(scene); myGraphicsView->scale(scaleFactor, scaleFactor); myGraphicsView->setGeometry(geometry); myGraphicsView->show(); myGraphicsView->setMinimumSize(200,200); myGraphicsView->setMaximumSize(10000,10000); QString prependPath = dirName; removeLastCharIf(prependPath, '/'); QString path = getLastWord(prependPath,'/'); this->setWindowTitle("iView --- "+path+"/ --- "+showName); icdw->ui->quitPushButton->hide(); // Update the navigator binned window with the binned poststamp emit updateNavigatorBinned(binnedPixmapItem); emit updateNavigatorBinnedWCS(wcs, wcsInit); } bool IView::loadFITSdata(QString filename, QVector &data, QString colorMode) { if (displayMode.contains("SCAMP") || displayMode == "CLEAR") { return false; } scene->removeCrosshair(); clearAxes(); if (weightMode) { filename.replace(".fits", ".weight.fits"); } // Setup the MyImage int verbose = 0; if (currentMyImage != nullptr) { delete currentMyImage; currentMyImage = nullptr; } QVector dummyMask; dummyMask.clear(); currentMyImage = new MyImage(filename, dummyMask, &verbose); currentMyImage->readImage(filename); plateScale = currentMyImage->plateScale; naxis1 = currentMyImage->naxis1; naxis2 = currentMyImage->naxis2; fullheader = currentMyImage->fullheader; wcs = currentMyImage->wcs; finderdw->dateObs = currentMyImage->dateobs; finderdw->geoLon = currentMyImage->geolon; finderdw->geoLat = currentMyImage->geolat; (void) wcsset(wcs); wcsInit = true; sendWCStoWCSdockWidget(); connect(currentMyImage, &MyImage::WCSupdated, this, &IView::WCSupdatedReceived); // Move the data from the transient MyImage over to the class member. data.swap(currentMyImage->dataCurrent); // 'fitsData' in the rest of the code // Get the dynamic range // Normal viewer mode if (displayMode == "FITSmonochrome") { if (dataIntSet) { delete[] dataInt; dataInt = nullptr; } dataInt = new unsigned char[naxis1*naxis2]; dataIntSet = true; // determine best dynamic range for display (not yet applied) // AUTO getGlobalImageStatistics(); if (icdw->ui->minLineEdit->text().isEmpty() || icdw->ui->maxLineEdit->text().isEmpty() || icdw->ui->autocontrastPushButton->isChecked()) { autoContrast(); } // MANUAL else { // get background statisics (medVal and rmsVal) dynRangeMin = icdw->ui->minLineEdit->text().toFloat(); dynRangeMax = icdw->ui->maxLineEdit->text().toFloat(); } } else if (displayMode == "FITScolor") { if (colorMode == "redChannel" && dataIntRSet) { delete[] dataIntR; dataIntR = nullptr; } if (colorMode == "greenChannel" && dataIntGSet) { delete[] dataIntG; dataIntG = nullptr; } if (colorMode == "blueChannel" && dataIntBSet) { delete[] dataIntB; dataIntB = nullptr; } if (colorMode == "redChannel") { dataIntR = new unsigned char[naxis1*naxis2]; dataIntRSet = true; } if (colorMode == "greenChannel") { dataIntG = new unsigned char[naxis1*naxis2]; dataIntGSet = true; } if (colorMode == "blueChannel") { dataIntB = new unsigned char[naxis1*naxis2]; dataIntBSet = true; } // Loading a color view of the RGB FITS channels // (only executes fully once all channels have been read) icdw->ui->autocontrastPushButton->setChecked(true); getGlobalImageStatistics(colorMode); autoContrast(); } return true; } void IView::mapFITS() { // record the source/ref catalog states bool sourceCatShown = ui->actionSourceCat->isChecked(); bool refCatShown = ui->actionRefCat->isChecked(); bool G2shown = false; if (displayMode == "FITScolor") { G2shown = colordw->ui->G2referencesPushButton->isChecked(); } //************************************************** // ADDITIONAL SECTION TO TEST TRANSFORMATIONS // QTransform *transform = nullptr; // transformation maxtrix if(wcs) { // Transformation prameters, to be filled explicitly from WCS matrix // Must be computed with respect to global reference system valid for all images. Not sure how to do this /* qreal scale = 1.; // scaling factor qreal phi = 0.; // rotation angle qreal dx = 0.; // translation qreal dy = 0.; // translation transform = new QTransform(); // Adjust according to CD matrix qreal matrix[][3] = { {cd11, cd21, 0.0}, {cd12, cd22, 0.0}, {crpix1, crpix2, 1.0}, }; qreal matrix[][3] = { {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}, }; transform->setMatrix(matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2], matrix[2][0], matrix[2][1], matrix[2][2]); transform->rotate(0.); dx = naxis1/2. - (transform->m11()*naxis1/2.+transform->m21()*naxis2/2.); dy = naxis2/2. - (transform->m12()*naxis1/2.+transform->m22()*naxis2/2.); transform->translate(-wcs->crpix[0], -wcs->crpix[1]); */ } else { // A WCS lock toggle button should be deactivated } // the scene MUST have it's final size BEFORE we add an item // WARNING: with some images (large coadds) then these images appear shifted to the right and cannot be viewed completely. // if(scene->width() < 1 || scene->height() < 1) // scene->setSceneRect( 0, 0, naxis1, naxis2); // end additional section //************************************************** clearItems(); if (displayMode == "FITSmonochrome" || displayMode == "MEMview") { compressDynrange(fitsData, dataInt); QImage fitsImage(dataInt, naxis1, naxis2, naxis1, QImage::Format_Grayscale8); fitsImage = fitsImage.mirrored(false, true); // apply transformation if there is one // if(transform) fitsImage = fitsImage.transformed(*transform,Qt::SmoothTransformation); pixmapItem = new QGraphicsPixmapItem(QPixmap::fromImage(fitsImage)); // while transformation the translations gets lost because the image is cropped to its contents, so we have to translate afterwards // if(transform) pixmapItem->setOffset(transform->m31(), transform->m32()); // qDebug() << transform->m11() << transform->m12() << transform->m13(); // qDebug() << transform->m21() << transform->m22() << transform->m23(); // qDebug() << transform->m31() << transform->m32() << transform->m33(); scene->clear(); scene->addItem(pixmapItem); myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); } else if (displayMode == "FITScolor") { compressDynrange(fitsDataR, dataIntR, colordw->colorFactorApplied[0]); compressDynrange(fitsDataG, dataIntG, colordw->colorFactorApplied[1]); compressDynrange(fitsDataB, dataIntB, colordw->colorFactorApplied[2]); QImage colorFitsImage(naxis1, naxis2, QImage::Format_ARGB32); for (long i=0; isetOffset(transform->m31(), transform->m32()); scene->clear(); scene->addItem(pixmapItem); } else { qDebug() << __func__ << "Invalid mode in mapFITS()"; } binnedPixmapItem = new QGraphicsPixmapItem(pixmapItem->pixmap().scaled(icdw->navigator_binned_nx, icdw->navigator_binned_ny, Qt::KeepAspectRatio, Qt::FastTransformation)); /* if (transform) { delete transform; transform = nullptr; } */ // Replot the source and reference catalogs (if the corresponding actions are checked) if (sourceCatShown && ui->actionSourceCat->isVisible()) { ui->actionSourceCat->setChecked(true); showSourceCat(); } if (refCatShown && ui->actionRefCat->isVisible()) { ui->actionRefCat->setChecked(true); showReferenceCat(); } if (displayMode == "FITScolor") { if (G2shown) { colordw->ui->G2referencesPushButton->setChecked(true); showG2References(true); } } finderdw->bypassResolver(); } void IView::compressDynrange(const QVector &fitsdata, unsigned char *intdata, float colorCorrectionFactor) { float rescale = 255. / (dynRangeMax - dynRangeMin); float tmpdata; // NOT THREADSAFE! //#pragma omp parallel for long i=0; for (auto &it : fitsdata) { // Truncate dynamic range float fitsdataCorrected = it * colorCorrectionFactor; if (fitsdataCorrected > dynRangeMax) tmpdata = dynRangeMax; else if (fitsdataCorrected < dynRangeMin) tmpdata = dynRangeMin; else tmpdata = fitsdataCorrected; // Compress to uchar (not thread safe) intdata[i] = (unsigned char) ((tmpdata-dynRangeMin) * rescale); ++i; } } void IView::updateColorViewExternal(float redFactor, float blueFactor) { colordw->colorFactorZeropoint[0] = redFactor; colordw->colorFactorZeropoint[1] = 1.0; colordw->colorFactorZeropoint[2] = blueFactor; QString red = QString::number(redFactor, 'f', 3); QString blue = QString::number(blueFactor, 'f', 3); colordw->ui->redFactorLineEdit->setText(red); colordw->ui->blueFactorLineEdit->setText(blue); colordw->textToSlider(red, "red"); colordw->textToSlider(blue, "blue"); updateColorViewInternal(redFactor, blueFactor); } void IView::updateColorViewInternal(float redFactor, float blueFactor) { if (displayMode != "FITScolor") return; colordw->colorFactorApplied[0] = redFactor; colordw->colorFactorApplied[1] = 1.0; colordw->colorFactorApplied[2] = blueFactor; mapFITS(); } void IView::showSourceCat() { // Leave if no image is displayed sourcecatSourcesShown = false; if (scene->items().isEmpty()) return; if (ui->actionSourceCat->isChecked()) { /* QString imageName = imageList.at(currentId); QFileInfo fi(imageName); QString baseName = fi.completeBaseName(); // The catalog is also valid for skysubtracted images if (baseName.endsWith(".sub")) baseName.chop(4); */ QString chipName = imageListChipName.at(currentId); QFile catalog(dirName+"/cat/iview/"+chipName+".iview"); QString line; QStringList lineList; qreal x; qreal y; qreal size; QPen pen(QColor("#00ff66")); int penWidth = 2./icdw->zoom2scale(zoomLevel); penWidth = penWidth < 1 ? 1 : penWidth; pen.setWidth(penWidth); QPoint point; // Refresh item list sourceCatItems.clear(); // Read all source positions if ( catalog.open(QIODevice::ReadOnly)) { QTextStream stream( &catalog ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); // skip header lines if (line.contains("#")) continue; lineList = line.split(" "); x = lineList.at(0).toFloat(); // must flip y y = naxis2 - lineList.at(1).toFloat(); size = 10.*lineList.at(2).toFloat(); // (factor 3 if using flux radius) // correct for an offset introduced by where the scene draws the ellipses if (size<5.) size = 5.; // Lower limit for symbol size if (size>20.) size = 20.; // Upper limit for symbol size point.setX(x-0.5*size); // Not sure where the +1 comes from. Perhaps from the flip and counting from 0 or one? point.setY(y-0.5*size+1.); myGraphicsView->mapToScene(point); // Not sure this is needed; Uncomment if objects are not plotted in the right position sourceCatItems.append(scene->addEllipse(point.x(), point.y(), size, size, pen)); /* // Does not draw ellipses in the right position. Some offset... qreal aell = 6.*lineList.at(2).toFloat(); qreal bell = 6.*lineList.at(3).toFloat(); qreal theta = lineList.at(4).toFloat(); QGraphicsEllipseItem *ellipse = scene->addEllipse(point.x(), point.y(), aell, bell, pen); ellipse->setTransformOriginPoint(x+1,y+1.); ellipse->setRotation(-theta); sourceCatItems.append(ellipse); */ } catalog.close(); } } else { if (!sourceCatItems.isEmpty()) { for (auto &it: sourceCatItems) scene->removeItem(it); sourceCatItems.clear(); } } if (!sourceCatItems.isEmpty()) sourcecatSourcesShown = true; else sourcecatSourcesShown = false; myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::showReferenceCat() { refcatSourcesShown = false; // Leave if no image is displayed if (scene->items().isEmpty()) return; QColor color = QColor("#ff3300"); int width = 2. / icdw->zoom2scale(zoomLevel); width = width < 1 ? 1 : width; if (!refCatItems.isEmpty()) { for (auto &it: refCatItems) scene->removeItem(it); refCatItems.clear(); } if (ui->actionRefCat->isChecked()) { refCatItems.clear(); // Try and read the reference catalog in the standard relative position int symbolSize = 15; if (!readRaDecCatalog(dirName+"/cat/refcat/theli_mystd.iview", refCatItems, symbolSize, width, color)) { // Perhaps we are looking at a coadded image. Then go one directory up first if (!readRaDecCatalog(dirName+"/../cat/refcat/theli_mystd.iview", refCatItems, symbolSize, width, color)) { // No overlap with data field? Let the user provide one manually: QString refcatFileName = QFileDialog::getOpenFileName(this, tr("Select reference catalog (theli_mystd.iview)"), dirName, "theli_mystd.iview"); if (QFile(refcatFileName).exists()) { if (!readRaDecCatalog(refcatFileName, refCatItems, symbolSize, width, color)) { qDebug() << __func__ << " : Could not read manually provided reference catalog."; // Remove any previous catalog display. if (!refCatItems.isEmpty()) { for (auto &it: refCatItems) scene->removeItem(it); refCatItems.clear(); } } } } } } else { // Remove any previous catalog display. if (!refCatItems.isEmpty()) { for (auto &it: refCatItems) scene->removeItem(it); refCatItems.clear(); } wcsdw->setDisabled(true); } if (!refCatItems.isEmpty()) { refcatSourcesShown = true; wcsdw->setEnabled(true); } else { refcatSourcesShown = false; wcsdw->setDisabled(true); } myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::showG2References(bool checked) { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (G2referencePathName.isEmpty()) return; if (checked) { QDir calibDir(G2referencePathName); QStringList calibSourcesList = calibDir.entryList(QStringList("PHOTCAT_sources_matched*.iview")); // Clear the item list G2refCatItems.clear(); // Read the catalogs, append to the item list with different symbols int width = 2; for (auto &it : calibSourcesList) { if (it.contains("SDSS")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 29, width, QColor("#ee0000")); if (it.contains("PANSTARRS")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 24, width, QColor("#00eeee")); if (it.contains("ATLAS-REFCAT2")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 19, width, QColor("#00ee00")); if (it.contains("SKYMAPPER")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 29, width, QColor("#eeee00")); } } else { // Remove any previous catalog display. if (!G2refCatItems.isEmpty()) { for (auto &it: G2refCatItems) scene->removeItem(it); G2refCatItems.clear(); } } myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::showAbsPhotReferences(bool checked) { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (checked) { // Clear previous items if (!AbsPhotRefCatItems.isEmpty()) { for (auto &it: AbsPhotRefCatItems) scene->removeItem(it); AbsPhotRefCatItems.clear(); } QString dirName = AbsPhotReferencePathName; QString catNameMatched = "ABSPHOT_sources_matched.iview"; QString catNameDownloaded = "ABSPHOT_sources_downloaded.iview"; if (AbsPhotReferencePathName.isEmpty()) { qDebug() << __func__ << "No path name defined for absolute reference catalog. AbsPhot references will not be displayed."; return; } // Clear the item list AbsPhotRefCatItems.clear(); int width = 2; readRaDecCatalog(dirName+"/"+catNameDownloaded, AbsPhotRefCatItems, 20, width, QColor("#ee0000")); // readRaDecCatalog(dirName+"/"+catNameDownloaded, AbsPhotRefCatItems, 18, width, QColor("#000000")); readRaDecCatalog(dirName+"/"+catNameMatched, AbsPhotRefCatItems, 20, width, QColor("#eeee00")); // readRaDecCatalog(dirName+"/"+catNameMatched, AbsPhotRefCatItems, 18, width, QColor("#000000")); } else { // Remove any previous catalog display. if (!AbsPhotRefCatItems.isEmpty()) { for (auto &it: AbsPhotRefCatItems) scene->removeItem(it); AbsPhotRefCatItems.clear(); } } myGraphicsView->setScene(scene); myGraphicsView->show(); } bool IView::readRaDecCatalog(QString fileName, QList &items, double size, int width, QColor color) { QString line; QStringList lineList; QPen pen(color); pen.setWidth(width); QPoint point; // Read all source positions QFile file(fileName); if ( file.open(QIODevice::ReadOnly)) { QTextStream stream( &file ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); // skip header lines if (line.contains("#")) continue; lineList = line.split(" "); double ra = lineList.at(0).toDouble(); double dec = lineList.at(1).toDouble(); double x = 0.; double y = 0.; sky2xyQImage(ra, dec, x, y); // correct for an offset introduced by where the scene draws the ellipses (or rectangles) point.setX(x-0.5*size); point.setY(y-0.5*size); myGraphicsView->mapToScene(point); // qDebug() << point.x() << naxis1 << point.y() << naxis2 << ra << dec << x << y << size; // only show reference sources within the image boundaries if (point.x() >= 0 && point.x() <= naxis1 && point.y() >= 0 && point.y() <= naxis2) { // qDebug() << x << point.x() << y << point.y() << ra << dec; items.append(scene->addRect(point.x(), point.y(), size, size, pen)); // qDebug() << "itemAdded"; } } file.close(); if (!items.isEmpty()) return true; else { return false; } } else { // error handling in caller function return false; } } // returns coordinates in QImage system! void IView::sky2xyQImage(double alpha, double delta, double &x, double &y) { if (!wcsInit) return; double world[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; world[0] = alpha; world[1] = delta; int stat[1]; wcss2p(wcs, 1, 2, world, &phi, &theta, imgcrd, pixcrd, stat); x = pixcrd[0]; y = naxis2 - pixcrd[1]; } // returns coordinates in FITS void IView::sky2xyFITS(double alpha, double delta, double &x, double &y) { if (!wcsInit) return; double world[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; world[0] = alpha; world[1] = delta; int stat[1]; wcss2p(wcs, 1, 2, world, &phi, &theta, imgcrd, pixcrd, stat); x = pixcrd[0]; y = pixcrd[1]; } QString IView::dec2hex(double angle) { double hh; double mm; double ss; int sign; sign = (angle < 0.0 ? -1 : 1); angle *= sign; angle = 60.0 * modf(angle, &hh); ss = 60.0 * modf(angle, &mm); QString h = QString::number(hh, 'f', 0); QString m = QString::number(mm, 'f', 0); QString s = QString::number(ss, 'f', 3); if (hh < 10) h.prepend("0"); if (mm < 10) m.prepend("0"); if (ss < 10) s.prepend("0"); QString p; if (sign > 0) p = "+"; else p = "-"; return p+h+":"+m+":"+s; } void IView::getGlobalImageStatistics(QString colorMode) { // Quasi-random sampling an array at every dim_small pixel int ranStep = 2./3.*naxis1 + sqrt(naxis1); QVector subSample; if (displayMode == "FITSmonochrome" || displayMode == "MEMview") { get_array_subsample(fitsData, subSample, ranStep); // GLOBAL statistics globalMedian = medianMask_T(subSample, QVector(), "ignoreZeroes"); globalMean = meanMask_T(subSample, QVector()); globalRMS = 1.486*madMask_T(subSample, QVector(), "ignoreZeroes"); } else if (displayMode == "FITScolor") { QVector subSampleR; QVector subSampleG; QVector subSampleB; if (colorMode == "redChannel") { get_array_subsample(fitsDataR, subSampleR, ranStep); globalMedianR = medianMask_T(subSampleR, QVector(), "ignoreZeroes"); } if (colorMode == "greenChannel") { get_array_subsample(fitsDataG, subSampleG, ranStep); globalMedianG = medianMask_T(subSampleG, QVector(), "ignoreZeroes"); } if (colorMode == "blueChannel") { get_array_subsample(fitsDataB, subSampleB, ranStep); globalMedianB = medianMask_T(subSampleB, QVector(), "ignoreZeroes"); // In addition, compute overall statistics across all three bands (once the blue is read, we have all of them available) get_array_subsample(fitsDataR, subSampleR, ranStep); get_array_subsample(fitsDataG, subSampleG, ranStep); for (long i=0; i(), "ignoreZeroes"); globalMean = meanMask_T(subSampleR, QVector()); globalRMS = 1.486*madMask_T(subSampleR, QVector(), "ignoreZeroes"); } } } void IView::autoContrast() { dynRangeMin = globalMedian - 2.*globalRMS; dynRangeMax = globalMedian + 10.*globalRMS; int validDigits = 3-log(fabs(dynRangeMax))/log(10); if (validDigits<0) validDigits = 0; icdw->ui->minLineEdit->setText(QString::number(dynRangeMin,'f',validDigits)); icdw->ui->maxLineEdit->setText(QString::number(dynRangeMax,'f',validDigits)); } void IView::writePreferenceSettings() { QSettings settings("IVIEW", "PREFERENCES"); settings.setValue("zoomFitPushButton", icdw->ui->zoomFitPushButton->isChecked()); settings.setValue("autocontrastPushButton", icdw->ui->autocontrastPushButton->isChecked()); } // TODO: make this dependent on which dockwidget is shown, otherwise we'll get valgrind issues void IView::readPreferenceSettings() { QSettings settings("IVIEW", "PREFERENCES"); if (!displayMode.contains("SCAMP")) { icdw->ui->zoomFitPushButton->setChecked(settings.value("zoomFitPushButton").toBool()); icdw->ui->autocontrastPushButton->setChecked(settings.value("autocontrastPushButton").toBool()); } } void IView::solutionAcceptanceStateReceived(bool state) { emit solutionAcceptanceState(state); scampCorrectlyClosed = true; this->close(); } void IView::autoContrastPushButton_toggled_receiver(bool checked) { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (checked) { autoContrast(); // Must clear all items (sky circles) on the scene, then redraw afterwards clearAxes(); scene->removeCrosshair(); if (!skyCircleItems.isEmpty()) skyCircleItems.clear(); if (!acceptedSkyCircleItems.isEmpty()) { for (auto &it : acceptedSkyCircleItems) { scene->removeItem(it); } } mapFITS(); myGraphicsView->setScene(scene); myGraphicsView->show(); redrawSkyCirclesAndCats(); emit updateNavigatorBinned(binnedPixmapItem); emit updateNavigatorBinnedWCS(wcs, wcsInit); } } void IView::replotCatalogAfterZoom() { bool sourceCatShown = ui->actionSourceCat->isChecked(); bool refCatShown = ui->actionRefCat->isChecked(); clearItems(); if (sourceCatShown && ui->actionSourceCat->isVisible()) { ui->actionSourceCat->setChecked(true); showSourceCat(); } if (refCatShown && ui->actionRefCat->isVisible()) { ui->actionRefCat->setChecked(true); showReferenceCat(); } scene->zoomScale = icdw->zoom2scale(zoomLevel); finderdw->bypassResolver(); } void IView::zoomFitPushButton_clicked_receiver(bool checked) { // Leave if no image is displayed if (scene->items().isEmpty()) return; if (checked) { myGraphicsView->fitInView(scene->items(Qt::AscendingOrder).at(0), Qt::KeepAspectRatio); double scale = myGraphicsView->transform().m11(); QString scaleFactor; if (scale > 1.) scaleFactor = QString::number(scale,'f',2)+":1"; else scaleFactor = "1:"+QString::number(1./scale,'f',2); // icdw->ui->zoomValueLabel->setText(scaleFactor); } replotCatalogAfterZoom(); } void IView::zoomInPushButton_clicked_receiver() { // Leave if no image is displayed if (scene->items().isEmpty()) return; ++zoomLevel; myGraphicsView->resetMatrix(); myGraphicsView->scale(icdw->zoom2scale(zoomLevel), icdw->zoom2scale(zoomLevel)); replotCatalogAfterZoom(); } void IView::zoomOutPushButton_clicked_receiver() { // Leave if no image is displayed if (scene->items().isEmpty()) return; --zoomLevel; myGraphicsView->resetMatrix(); myGraphicsView->scale(icdw->zoom2scale(zoomLevel), icdw->zoom2scale(zoomLevel)); replotCatalogAfterZoom(); } void IView::zoomZeroPushButton_clicked_receiver() { // Leave if no image is displayed if (scene->items().isEmpty()) return; zoomLevel = 0; // Do this to update the zoom label icdw->zoom2scale(zoomLevel); myGraphicsView->resetMatrix(); replotCatalogAfterZoom(); } void IView::minmaxLineEdit_returnPressed_receiver(QString rangeMin, QString rangeMax) { clearAxes(); dynRangeMin = rangeMin.toFloat(); dynRangeMax = rangeMax.toFloat(); mapFITS(); redrawUpdateAxes(); // redshift axes myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::colorFactorChanged_receiver(QString redFactor, QString blueFactor) { // Re-emit the signal from the dock widget to the color calibration dialog emit colorFactorChanged(redFactor, blueFactor); // Apply color factors: mapFITS(); } void IView::filterLineEdit_textChanged(const QString &arg1) { QString filter = arg1; if (filter.isEmpty() || !filter.contains(".fits") || !filter.contains("*")) { filter = "*.fits"; filterLineEdit->setText(filter); } setImageList(filter); numImages = imageList.length(); pageLabel->setText("? / "+QString::number(numImages)); // Rewind // iview->startAction_triggered(); } void IView::fovCenterChangedReceiver(QPointF newCenter) { QPointF center = binnedToQimage(newCenter); // qDebug() << newCenter << center; myGraphicsView->centerOn(center); } void IView::targetResolvedReceived(QString alphaStr, QString deltaStr) { if (alphaStr.contains(":")) alphaStr = hmsToDecimal(alphaStr); if (deltaStr.contains(":")) deltaStr = dmsToDecimal(deltaStr); double x = 0.; double y = 0.; sky2xyQImage(alphaStr.toDouble(), deltaStr.toDouble(), x, y); if (x > 0. && x < naxis1-1 && y > 0. && y < naxis2-1) { myGraphicsView->centerOn(QPointF(x,y)); scene->addCrosshair(x,y); } else { /* * if (sender() == finderdw->ui->targetresolverToolButton) { finderdw->ui->targetNameNonsiderealLineEdit->setText("outside f.o.v"); } if (sender() == finderdw->ui->MPCresolverToolButton) { finderdw->ui->targetNameSiderealLineEdit->setText("outside f.o.v"); } */ } } void IView::WCSupdatedReceived() { sendWCStoWCSdockWidget(); icdw->receiveWCS(wcs, wcsInit); } THELI-3.1.3/src/iview/iview.h000066400000000000000000000335221417631501300155770ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVIEW_H #define IVIEW_H #include "mygraphicsview.h" #include "mygraphicsscene.h" #include "mygraphicsellipseitem.h" #include "dockwidgets/ivconfdockwidget.h" #include "dockwidgets/ivscampdockwidget.h" #include "dockwidgets/ivcolordockwidget.h" #include "dockwidgets/ivwcsdockwidget.h" #include "dockwidgets/ivstatisticsdockwidget.h" #include "dockwidgets/ivfinderdockwidget.h" #include "dockwidgets/ivredshiftdockwidget.h" #include "../myimage/myimage.h" #include "myaxis.h" #include "fitsio2.h" #include "wcs.h" #include "wcshdr.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Ui { class IView; } class IView : public QMainWindow { Q_OBJECT public: explicit IView(QWidget *parent = nullptr); explicit IView(QString mode, QWidget *parent = nullptr); explicit IView(QString mode, QList &list, QString dirname, QWidget *parent = nullptr); explicit IView(QString mode, QString name, QWidget *parent = nullptr); explicit IView(QString mode, QString dirname, QString filter, QWidget *parent = nullptr); explicit IView(QString mode, QString dirname, QString fileName, QString filter, QWidget *parent = nullptr); explicit IView(QString mode, QString dirname, QString rChannel, QString gChannel, QString bChannel, float factorR, float factorB, QWidget *parent = nullptr); ~IView(); QString dirName; QString startDirName = ""; // the dir name of the first image loaded (never changed after init) QString filterName; QString currentSuffix; QString middleMouseMode = "DragMode"; bool startDirNameSet = false; bool scampInteractiveMode = false; bool scampCorrectlyClosed = false; void setMiddleMouseMode(QString mode); void switchMode(QString mode = ""); void loadPNG(QString filename, int currentId = 0); void autoContrast(); void setImageList(QString filter); void redrawSkyCirclesAndCats(); void clearItems(); void updateCDmatrixFITS(); void setCatalogOverlaysExternally(bool sourcecatShown, bool refcatShown); void xy2sky(double x, double y, QString button = ""); bool weightMode = false; // whether iview displays the image data or the weight bool refcatSourcesShown = false; bool sourcecatSourcesShown = false; QString G2referencePathName = ""; QString AbsPhotReferencePathName = ""; IvConfDockWidget *icdw; IvScampDockWidget *scampdw; IvColorDockWidget *colordw; IvStatisticsDockWidget *statdw = new IvStatisticsDockWidget(this); IvFinderDockWidget *finderdw = new IvFinderDockWidget(this); IvWCSDockWidget *wcsdw = new IvWCSDockWidget(this); IvRedshiftDockWidget *zdw = new IvRedshiftDockWidget(this); QList observedAxisLineItems; QList restframeAxisLineItems; QList spectrumAxisLineItems; QList observedAxisMainLineItems; QList restframeAxisMainLineItems; QList spectrumAxisMainLineItems; QList observedAxisTextItems; QList restframeAxisTextItems; QList spectrumAxisTextItems; MyGraphicsView *myGraphicsView; // MyGraphicsScene *scene = new MyGraphicsScene(this); MyGraphicsScene *scene = new MyGraphicsScene(); int numImages = 0; int zoomLevel = 0; float dynRangeMin; float dynRangeMax; QLabel *pageLabel = new QLabel(this); QStringList imageList; QStringList imageListChipName; QList skyCircleItems; QList acceptedSkyCircleItems; int currentId = 0; int verbosity = 0; float globalMedian = 0.; float globalMedianR = 0.; float globalMedianG = 0.; float globalMedianB = 0.; float globalRMS = 0.; float globalMean = 0.; QList myImageList; MyImage *currentMyImage = nullptr; QString currentFileName = ""; int naxis1 = 0; int naxis2 = 0; QVector fitsData; QVector fitsDataR; QVector fitsDataG; QVector fitsDataB; QString displayMode = "CLEAR"; void qimageToBinned(qreal qx, qreal qy, qreal &bx, qreal &by); QRect qimageToBinned(const QRectF qrect); QPointF qimageToBinned(const QPointF qpoint); void binnedToQimage(qreal bx, qreal by, qreal &qx, qreal &qy); QPointF binnedToQimage(const QPointF bpoint); MyAxis observedAxis; MyAxis restframeAxis; MyAxis spectrumAxis; signals: void abortPlay(); void colorFactorChanged(QString redFactor, QString blueFactor); void closed(); void statisticsRequested(long x, long y); void solutionAcceptanceState(bool state); void middleMouseModeChanged(QString mode); void currentlyDisplayedIndex(int index); void updateNavigatorMagnified(QGraphicsPixmapItem *magnifiedPixmapItem, qreal scaleFactor, float dx, float dy); void updateNavigatorBinned(QGraphicsPixmapItem *binnedPixmapItem); void updateNavigatorBinnedViewport(QRect rect); void statisticsSampleAvailable(const QVector &sample); void statisticsSampleColorAvailable(const QVector &sampleR, const QVector &sampleG, const QVector &sampleB); void updateNavigatorBinnedWCS(wcsprm *cd, bool wcsinit); void clearMagnifiedScene(); void newImageLoaded(); void wavelengthUpdated(QString lobs, QString lrest); private slots: void adjustBrightnessContrast(QPointF point); void appendSkyCircle(); void backAction_triggered(); void clearSeparationVector(); void drawSeparationVector(QPointF pointStart, QPointF pointEnd); void drawSkyCircle(QPointF pointStart, QPointF pointEnd); void drawMaskingPolygon(QPointF pointStart, QPointF pointEnd); void drawSkyRectangle(QPointF pointStart, QPointF pointEnd); void endAction_triggered(); void forwardAction_triggered(); void initDynrangeDrag(); void initSeparationVector(QPointF pointStart); void loadImage(); void middlePressResetCRPIXreceived(); void nextAction_triggered(); void on_actionDragMode_triggered(); void on_actionSkyMode_triggered(); void on_actionWCSMode_triggered(); void on_actionMaskingMode_triggered(); void previousAction_triggered(); // void startAction_triggered(); // public void showCurrentMousePos(QPointF point); void sendStatisticsCenter(QPointF point); void showSourceCat(); void showReferenceCat(); void updateSkyCircles(); void updateCRPIX(QPointF pointStart, QPointF pointEnd); void updateCRPIXFITS(); void updateCDmatrix(double cd11, double cd12, double cd21, double cd22); void updateNavigatorMagnifiedReceived(QPointF point); // void mouseEnteredViewReceived(); // void mouseLeftViewReceived(); void on_actionImage_statistics_triggered(); void filterLineEdit_textChanged(const QString &arg1); void collectLocalStatisticsSample(QPointF point); void updateStatisticsButton(); void updateRedshiftButton(); void updateFinderButton(); void fovCenterChangedReceiver(QPointF newCenter); void on_actionFinder_triggered(); void WCSupdatedReceived(); void on_actionRedshift_triggered(); void showWavelength(QPointF point); void redrawUpdateAxes(); public slots: void autoContrastPushButton_toggled_receiver(bool checked); void clearAll(); void colorFactorChanged_receiver(QString redFactor, QString blueFactor); void loadFITSexternal(QString fileName, QString filter); void loadFromRAM(MyImage *it, int level); // void loadFromRAMlist(const QModelIndex &index); void loadFITSexternalRAM(int index); void mapFITS(); void minmaxLineEdit_returnPressed_receiver(QString rangeMin, QString rangeMax); void showG2References(bool checked); void showAbsPhotReferences(bool checked); void solutionAcceptanceStateReceived(bool state); void startAction_triggered(); void updateColorViewInternal(float redFactor, float blueFactor); void updateColorViewExternal(float redFactor, float blueFactor); void zoomFitPushButton_clicked_receiver(bool checked); void zoomInPushButton_clicked_receiver(); void zoomOutPushButton_clicked_receiver(); void zoomZeroPushButton_clicked_receiver(); void viewportChangedReceived(QRect viewport_rect); void targetResolvedReceived(QString alphaStr, QString deltaStr); void updateAxes(); void updateFinesse(int value); void resetRedshift(); void redshiftChanged(QString text); protected: void closeEvent(QCloseEvent *event) override; void resizeEvent(QResizeEvent *event); private: Ui::IView *ui; QLabel *coordsLabel; QActionGroup *middleMouseActionGroup = new QActionGroup(this); int screenHeight; int screenWidth; float dynRangeMinDragStart = 0.; float dynRangeMaxDragStart = 0.; double crpix1_start = 0.; // set when the middle mouse button is pressed in wcs mode double crpix2_start = 0.; // set when the middle mouse button is pressed in wcs mode double plateScale = 0.; double skyRa = 0.; double skyDec = 0.; bool startLeftClickInsideItem = false; int timerId; QString ChannelR; QString ChannelG; QString ChannelB; bool allChannelsRead = false; unsigned char *dataInt; unsigned char *dataIntR; unsigned char *dataIntG; unsigned char *dataIntB; unsigned char *dataBinnedInt; unsigned char *dataBinnedIntR; unsigned char *dataBinnedIntG; unsigned char *dataBinnedIntB; QGraphicsPixmapItem *pixmapItem = nullptr; QGraphicsPixmapItem *magnifiedPixmapItem = nullptr; QGraphicsPixmapItem *binnedPixmapItem = nullptr; bool dataBinnedIntSet = false; bool dataBinnedIntRSet = false; bool dataBinnedIntGSet = false; bool dataBinnedIntBSet = false; bool dataIntSet = false; bool dataIntRSet = false; bool dataIntGSet = false; bool dataIntBSet = false; int magnify = 7; double rad = 3.1415926535 / 180.; bool fromMemory = false; struct wcsprm *wcs; bool wcsInit = false; char *fullheader = nullptr; QTimer *timer = new QTimer(this); QList vectorLineItems; QList vectorTextItems; QList sourceCatItems; QList refCatItems; QList G2refCatItems; QList AbsPhotRefCatItems; QList skyRectItems; QList skyTextItems; QList maskPolygonItems; QList maskRectItems; QLabel *speedLabel = new QLabel(this); QSpinBox *speedSpinBox = new QSpinBox(this); QLabel *filterLabel = new QLabel(this); QLineEdit *filterLineEdit = new QLineEdit(this); bool icdwDefined = false; bool scampdwDefined = false; bool binnedPixmapUptodate = false; void addDockWidgets(); QRect adjustGeometry(); void clearSkyCircleItems(); void clearSkyRectItems(); void clearMaskPolygonItems(); void clearMaskRectItems(); void clearVectorItems(); void compressDynrange(const QVector &fitsdata, unsigned char *intdata, float colorCorrectionFactor = 1.0); QString dec2hex(double angle); void dumpSkyCircleCoordinates(); void getGlobalImageStatistics(QString colorMode = ""); QString getVectorLabel(double separation); void getVectorOffsets(const qreal dx, const qreal dy, qreal &x_yoffset, qreal &y_xoffset, qreal &d_xoffset, qreal &d_yoffset); double haversine(double x1, double y1, double x2, double y2); void hideWCSdockWidget(); void imageListToChipName(); void initGUI(); void initGUIstep2(); void loadColorFITS(qreal scaleFactor); void loadFITS(QString filename, int currentId = 0, qreal scaleFactor = 1.0); bool loadFITSdata(QString filename, QVector &data, QString colorMode = ""); void makeConnections(); void measureAngularSeparations(QPointF pointStart, QPointF pointEnd, double &sepX, double &sepY, double &sepD); void readPreferenceSettings(); bool readRaDecCatalog(QString fileName, QList &items, double size, int width, QColor color); void replotCatalogAfterZoom(); void setCurrentId(QString filename); void setImageListFromMemory(); void showWCSdockWidget(); void showAxes(); void sky2xyQImage(double ra, double dec, double &x, double &y); void sky2xyFITS(double ra, double dec, double &x, double &y); void writePreferenceSettings(); template int sgn(T val) { return (T(0) < val) - (val < T(0)); } void sendWCStoWCSdockWidget(); void checkFinder(); void checkFinderBypass(); void showAxesHelper(QList &lineItemList, QList &mainLineItemList, QList &textItemList, const MyAxis &axis, QString type); void clearAxesHelper(QList &lineItemList, QList &mainLineItemList, QList &textItemList); void clearAxes(); void updateAxesHelper(); }; #endif // IVIEW_H THELI-3.1.3/src/iview/iview.ui000066400000000000000000000225111417631501300157610ustar00rootroot00000000000000 IView 0 0 664 711 0 0 iView 0 0 QFrame::Panel QFrame::Sunken 2 0 0 0 0 0 0 0 0 664 23 Fi&le toolBar TopToolBarArea false &Load image from drive &Close :/icons/icon_start.png:/icons/icon_start.png First in series :/icons/icon_previous.png:/icons/icon_previous.png Previous in series true :/icons/icon_back.png:/icons/icon_back.png Play back series true :/icons/icon_forward.png:/icons/icon_forward.png Play forward series :/icons/icon_next.png:/icons/icon_next.png Next in series :/icons/icon_end.png:/icons/icon_end.png Last in series true SourceCat Overlay source catalog true RefCat Overlay reference catalog true :/icons/hand.png:/icons/hand.png Drag Mode Middle mouse button drags image true :/icons/pipette.png:/icons/pipette.png Sky Mode Middle mouse button creates sky measurement areas true :/icons/wcs.png:/icons/wcs.png WCS Mode Middle mouse button changes CRPIX1/2 true :/icons/sigma.png:/icons/sigma.png Image statistics Display local and global image statistics true :/icons/satellite-icon.png:/icons/satellite-icon.png Masking Mask satellites and other image defects true :/icons/magnifyer.png:/icons/magnifyer.png Finder Locate a target in the image true :/icons/spec.png:/icons/spec.png Redshift Redshift estimation for FITS spectra THELI-3.1.3/src/iview/myaxis.cc000066400000000000000000000102311417631501300161140ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myaxis.h" #include MyAxis::MyAxis(QObject *parent) : QObject(parent) { } void MyAxis::init(double crval_in, double cd_in, long naxis1_in, long naxis2_in, int offset, QString direction, QColor color, QString type) { pen.setColor(color); pen.setWidth(0); axisOffset = offset; tickDirection = direction; crval = crval_in; cd = cd_in; naxis1 = naxis1_in; naxis2 = naxis2_in; getWavelengthRange(); ybase = naxis2/2 + axisOffset; axisLine.setLine(1, ybase, naxis1, ybase); if (type.isEmpty()) getTickmarks(); if (type == "spectrum") initSpectrumTickmarks(); } double MyAxis::pixelToWavelength(double x) { return (crval + cd * x) / (1.+z_0); } double MyAxis::wavelengthToPixel(double lambda) { return (lambda*(1.+z_0) - crval) / cd; } void MyAxis::getTickmarks() { tickLabels.clear(); tickMarks.clear(); // Step size depends on resolution if (cd < 1.0) tickstep = 100; else if (cd < 2.0 && cd >= 1.0) tickstep = 200; else if (cd < 4.0 && cd >= 2.0) tickstep = 500; else tickstep = 1000; // Redshift correction, and lock onto even numbered tick values tickstep /= (1.+z); if (tickstep < 50) tickstep = 50; else if (tickstep >= 50 && tickstep < 150) tickstep = 100; else if (tickstep >= 150 && tickstep < 250) tickstep = 200; else if (tickstep >= 250 && tickstep < 750) tickstep = 500; else tickstep = 1000; int start = floor(lambdaMin/tickstep) * tickstep; int stop = ceil(lambdaMax/tickstep) * tickstep; // The following takes into account that the y-axis in QPixmap is flipped. int flip = -1; if (tickDirection == "up") flip = 1; for (int i=start; i<=stop; i=i+tickstep) { float xpos = wavelengthToPixel(i); if (i>=lambdaMin && i<=lambdaMax) { tickLabels.append(QString::number(i)); QLineF line = QLineF(xpos, ybase, xpos, ybase+flip*tickLength); tickMarks.append(line); } } } void MyAxis::initSpectrumTickmarks() { tickLabels.clear(); tickMarks.clear(); } void MyAxis::addSpecies(const QList > &list) { // The following takes into account that the y-axis in QPixmap is flipped. int flip = -1; if (tickDirection == "up") flip = 1; for (auto &it : list) { float lambda = it.second; float xpos = wavelengthToPixel(it.second); if (lambda >= lambdaMin && lambda <= lambdaMax) { tickLabels.append(it.first + " " + QString::number(it.second, 'f', 0)); QLineF line = QLineF(xpos, ybase, xpos, ybase-flip*tickLength); tickMarks.append(line); } } } // must be updated everytime z changes void MyAxis::getWavelengthRange() { float lambda1 = pixelToWavelength(0); float lambda2 = pixelToWavelength(naxis1); lambdaMin = lambda1 < lambda2 ? lambda1 : lambda2; lambdaMax = lambda1 > lambda2 ? lambda1 : lambda2; } void MyAxis::redshiftChangedReceiver(QString zstring) { z = zstring.toFloat(); } void MyAxis::clear() { tickLabels.clear(); tickMarks.clear(); } void MyAxis::initRedshift(QPointF pointStart) { z_0 = z; } void MyAxis::closeRedshift() { z = z_0; } void MyAxis::redshiftSpectrum(QPointF pointStart, QPointF currentPoint) { float dx = currentPoint.x() - pointStart.x(); float dz = dx / finesse * (1.+z); float z_tmp = z + dz; if (z_tmp < 0) z_tmp = 0.; z_0 = z_tmp; getWavelengthRange(); emit redshiftRecomputed(); emit redshiftUpdated(z_0); } THELI-3.1.3/src/iview/myaxis.h000066400000000000000000000047211417631501300157650ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYAXIS_H #define MYAXIS_H #include #include #include #include #include #include #include class MyAxis : public QObject { Q_OBJECT double wavelengthToPixel(double lambda); void initSpectrumTickmarks(); public: explicit MyAxis(QObject *parent = nullptr); QLineF axisLine; QList tickMarks; QStringList tickLabels; QString tickDirection = "down"; QPen pen; float finesse = 2000.; long naxis1 = 0; long naxis2 = 0; double crval = 0.; double cd = 1.0; float z = 0.; // redshift float z_0 = 0.; // the previous value held by z; float x_0 = 0.; // The x coordinate of the mouse cursor when the left button is clicked float lambdaMin = 0.; // wavelength range maximally covered by the axis float lambdaMax = 0.; int tickLength = 10; int ybase = 0.; // The y coordinate at which the axis is drawn. int axisOffset = 0; // draw the observed axis line this much below the center of the image int tickstep = 100; // Wavelength interval at which tickmarks are drawn void init(double crval_in, double cd_in, long naxis1_in, long naxis2_in, int offset, QString direction, QColor color, QString type = ""); void addSpecies(const QList > &list); void clear(); void getTickmarks(); signals: void redshiftRecomputed(); void redshiftUpdated(float z_0); public slots: double pixelToWavelength(double x); void getWavelengthRange(); void redshiftChangedReceiver(QString zstring); void initRedshift(QPointF pointStart); void redshiftSpectrum(QPointF pointStart, QPointF currentPoint); void closeRedshift(); }; #endif // MYAXIS_H THELI-3.1.3/src/iview/mybinnedgraphicsview.cc000066400000000000000000000105641417631501300210340ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mybinnedgraphicsview.h" #include "iview.h" #include "wcs.h" MyBinnedGraphicsView::MyBinnedGraphicsView() : QGraphicsView() { QBrush brush(QColor("#000000")); brush.setStyle(Qt::SolidPattern); this->setBackgroundBrush(brush); } void MyBinnedGraphicsView::mouseMoveEvent(QMouseEvent *event) { QPoint currentPos = event->pos(); // Display the current pixel coordinates under the cursor QPointF currentPoint = mapToScene(currentPos); emit currentMousePos(currentPoint); if (leftButtonPressed) { // scroll main view only if rectangle is within binnedPixMap qreal x1; qreal x2; qreal y1; qreal y2; binnedSceneRect.getCoords(&x1, &y1, &x2, &y2); qreal halfSceneWidth = (x2-x1) / 2.; qreal halfSceneHeight = (y2-y1) / 2.; qreal xcen = fovRectItem->scenePos().x() + nx / 2.; qreal ycen = fovRectItem->scenePos().y() + ny / 2.; qreal xcen1 = fovRectItem->scenePos().x() + halfSceneWidth; qreal ycen1 = fovRectItem->scenePos().y() + halfSceneHeight; qreal xr1 = xcen1 - fovRectItem->rect().width() / 2.; qreal xr2 = xcen1 + fovRectItem->rect().width() / 2.; qreal yr1 = ycen1 - fovRectItem->rect().height() / 2.; qreal yr2 = ycen1 + fovRectItem->rect().height() / 2.; qreal vxmin = x1 <= x2 ? x1 : x2; qreal vxmax = x1 >= x2 ? x1 : x2; qreal vymin = y1 <= y2 ? y1 : y2; qreal vymax = y1 >= y2 ? y1 : y2; if (xr1 > vxmin && xr2 < vxmax && yr1 > vymin && yr2 < vymax) { fovBeingDragged = true; fovRectItem->setFlags(QGraphicsEllipseItem::ItemIsMovable); QPoint rectCenter = QPoint(xcen, ycen); QPointF rectCenterQimage = mapToScene(rectCenter); emit fovRectCenterChanged(rectCenterQimage); } } QGraphicsView::mouseMoveEvent(event); } void MyBinnedGraphicsView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { rightDragStartPos = event->pos(); rightButtonPressed = true; emit rightPress(); } if (event->button() == Qt::LeftButton) { leftDragStartPos = event->pos(); QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y()); leftButtonPressed = true; emit leftPress(pointStart); } if (event->button() == Qt::MiddleButton) { // setDragMode(QGraphicsView::ScrollHandDrag); // previousMousePoint = event->pos(); if (middleMouseMode == "DragMode") { middleButtonPressed = true; _pan = true; _panStartX = event->x(); _panStartY = event->y(); setCursor(Qt::OpenHandCursor); // event->accept(); } } QGraphicsView::mousePressEvent(event); } void MyBinnedGraphicsView::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { rightButtonPressed = false; emit rightButtonReleased(); } if (event->button() == Qt::LeftButton) { leftButtonPressed = false; fovBeingDragged = false; // old_x = fovRectItem->scenePos().x() + nx/2.; // old_y = fovRectItem->scenePos().y() + ny/2.; // qDebug() << "OLD" << old_x << old_y; emit leftButtonReleased(); } if (event->button() == Qt::MiddleButton) { middleButtonPressed = false; if (middleMouseMode == "DragMode") { _pan = false; setCursor(Qt::ArrowCursor); // event->accept(); // return; } } QGraphicsView::mouseReleaseEvent(event); } void MyBinnedGraphicsView::updateMiddleMouseMode(QString mode) { middleMouseMode = mode; } THELI-3.1.3/src/iview/mybinnedgraphicsview.h000066400000000000000000000053611417631501300206750ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYBINNEDGRAPHICSVIEW_H #define MYBINNEDGRAPHICSVIEW_H #include #include #include #include #include #include "myqgraphicsrectitem.h" class MyBinnedGraphicsView : public QGraphicsView { Q_OBJECT private: QPointF rightDragStartPos; QPointF rightDragCurrentPos; QPointF rightDragEndPos; QPointF leftDragStartPos; QPointF leftDragCurrentPos; QPointF leftDragEndPos; // unused QPointF middleDragStartPos; QPointF middleDragCurrentPos; QPointF middleDragEndPos; bool rightButtonPressed = false; bool leftButtonPressed = false; bool middleButtonPressed = false; QPoint previousMousePoint; bool _pan = false; int _panStartX = 0; int _panStartY = 0; bool _wcs = false; QPoint wcsStart; public: explicit MyBinnedGraphicsView(); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); QScrollBar *sxbar = nullptr; QScrollBar *sybar = nullptr; QString middleMouseMode = "DragMode"; int nx = 0; int ny = 0; QRectF binnedSceneRect; MyQGraphicsRectItem *fovRectItem = new MyQGraphicsRectItem(); // QGraphicsRectItem *fovRectItem = new QGraphicsRectItem(); int x = 0; int y = 0; bool fovBeingDragged = false; int old_x = 0; int old_y = 0; signals: void currentMousePos(QPointF); void rightDragTravelled(QPointF); void middleDragTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSreleased(); void leftDragTravelled(QPointF pointStart, QPointF pointEnd); void rightPress(); void leftPress(QPointF pointStart); void middlePress(QPointF point); void leftButtonReleased(); void rightButtonReleased(); void middleButtonReleased(); void middlePressResetCRPIX(); void fovRectCenterChanged(QPointF point); public slots: void updateMiddleMouseMode(QString mode); }; #endif // MYBINNEDGRAPHICSVIEW_H THELI-3.1.3/src/iview/mygraphicsellipseitem.cc000066400000000000000000000021151417631501300212070ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mygraphicsellipseitem.h" #include #include MyGraphicsEllipseItem::MyGraphicsEllipseItem() { this->setAcceptedMouseButtons(Qt::LeftButton); } void MyGraphicsEllipseItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton) { this->setSelected(true); } QGraphicsEllipseItem::mousePressEvent(event); } THELI-3.1.3/src/iview/mygraphicsellipseitem.h000066400000000000000000000020011417631501300210430ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYGRAPHICSELLIPSEITEM_H #define MYGRAPHICSELLIPSEITEM_H #include #include #include class MyGraphicsEllipseItem : public QGraphicsEllipseItem { public: MyGraphicsEllipseItem(); void mousePressEvent(QGraphicsSceneMouseEvent *event); }; #endif // MYGRAPHICSELLIPSEITEM_H THELI-3.1.3/src/iview/mygraphicsscene.cc000066400000000000000000000061261417631501300177760ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mygraphicsscene.h" #include #include #include #include #include MyGraphicsScene::MyGraphicsScene() { } // Override key event to delete selected items with the backspace or delete key void MyGraphicsScene::keyReleaseEvent(QKeyEvent * keyEvent) { if(keyEvent->key() == Qt::Key_Backspace || keyEvent->key() == Qt::Key_Delete) { QList selectedItems = this->selectedItems(); // get list of selected items foreach(QGraphicsItem* item, selectedItems) { removeItem(item); delete item; item = nullptr; } emit itemDeleted(); } } void MyGraphicsScene::leaveEvent(QEvent *event) { if (event->type() == QEvent::Leave) { emit mouseLeftScene(); QGraphicsScene::event(event); } } void MyGraphicsScene::addCrosshair(double x, double y) { removeCrosshair(); QPen pen(QColor("#00ffaa")); pen.setWidth(0); QPen penBlack(QColor("#000000")); penBlack.setWidth(0); double width = 20/zoomScale; double widthBlack = (width - 2/zoomScale); crosshairCircleItem = addEllipse(x-width/2, y-width/2, width, width, pen); crosshairCircleBlackItem = addEllipse(x-widthBlack/2, y-widthBlack/2, widthBlack, widthBlack, penBlack); crosshairLineNItem = addLine(x, y-width/2, x, y-width, pen); crosshairLineSItem = addLine(x, y+width/2, x, y+width, pen); crosshairLineEItem = addLine(x-width/2, y, x-width, y, pen); crosshairLineWItem = addLine(x+width/2, y, x+width, y, pen); crosshairShown = true; } void MyGraphicsScene::removeCrosshair() { if (crosshairCircleItem != nullptr) { removeItem(crosshairCircleItem); crosshairCircleItem = nullptr; } if (crosshairCircleBlackItem != nullptr) { removeItem(crosshairCircleBlackItem); crosshairCircleBlackItem = nullptr; } if (crosshairLineNItem != nullptr) { removeItem(crosshairLineNItem); crosshairLineNItem = nullptr; } if (crosshairLineSItem != nullptr) { removeItem(crosshairLineSItem); crosshairLineSItem = nullptr; } if (crosshairLineEItem != nullptr) { removeItem(crosshairLineEItem); crosshairLineEItem = nullptr; } if (crosshairLineWItem != nullptr) { removeItem(crosshairLineWItem); crosshairLineWItem = nullptr; } crosshairShown = false; } THELI-3.1.3/src/iview/mygraphicsscene.h000066400000000000000000000030701417631501300176330ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYGRAPHICSSCENE_H #define MYGRAPHICSSCENE_H #include #include #include #include class MyGraphicsScene : public QGraphicsScene { Q_OBJECT public: MyGraphicsScene(); void leaveEvent(QEvent *event); QGraphicsEllipseItem *crosshairCircleItem = nullptr; QGraphicsEllipseItem *crosshairCircleBlackItem = nullptr; QGraphicsLineItem *crosshairLineNItem = nullptr; QGraphicsLineItem *crosshairLineSItem = nullptr; QGraphicsLineItem *crosshairLineEItem = nullptr; QGraphicsLineItem *crosshairLineWItem = nullptr; bool crosshairShown = false; double zoomScale = 1.0; signals: void itemDeleted(); void mouseLeftScene(); protected: void keyReleaseEvent(QKeyEvent * keyEvent); public slots: void removeCrosshair(); void addCrosshair(double x, double y); }; #endif // MYGRAPHICSSCENE_H THELI-3.1.3/src/iview/mygraphicsview.cc000066400000000000000000000136161417631501300176550ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mygraphicsview.h" #include "iview.h" #include MyGraphicsView::MyGraphicsView() : QGraphicsView() { QBrush brush(QColor("#000000")); brush.setStyle(Qt::SolidPattern); this->setBackgroundBrush(brush); } void MyGraphicsView::mouseMoveEvent(QMouseEvent *event) { QPoint currentPos = event->pos(); // Display the current pixel coordinates under the cursor QPointF currentPoint = mapToScene(currentPos); emit currentMousePos(currentPoint); // Also, if the right mouse button is pressed while moving, // adjust brightness and contrast if (rightButtonPressed) { emit rightDragTravelled(rightDragStartPos - currentPos); } if (middleButtonPressed) { // emit middleDragTravelled(previousMousePoint - currentPos); // emit middleDragTravelled(currentPos); if (middleMouseMode == "SkyMode") { QPointF pointStart = mapToScene(middleDragStartPos.x(), middleDragStartPos.y()); emit middleSkyDragTravelled(pointStart, currentPoint); } else if (middleMouseMode == "DragMode") { if (_pan) { horizontalScrollBar()->setValue(horizontalScrollBar()->value() - 2.*(event->x() - _panStartX)); verticalScrollBar()->setValue(verticalScrollBar()->value() - 2.*(event->y() - _panStartY)); _panStartX = event->x(); _panStartY = event->y(); // event->accept(); // return; } } else if (middleMouseMode == "WCSMode") { QPointF pointStart = mapToScene(wcsStart); emit middleWCSTravelled(pointStart, currentPoint); } else if (middleMouseMode == "MaskingMode") { QPointF pointStart = mapToScene(middleDragStartPos.x(), middleDragStartPos.y()); emit middleMaskingDragTravelled(pointStart, currentPoint); } } if (leftButtonPressed) { QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y()); emit leftDragTravelled(pointStart, currentPoint); } QGraphicsView::mouseMoveEvent(event); } void MyGraphicsView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { rightDragStartPos = event->pos(); rightButtonPressed = true; emit rightPress(); } if (event->button() == Qt::LeftButton) { leftDragStartPos = event->pos(); QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y()); leftButtonPressed = true; emit leftPress(pointStart); } if (event->button() == Qt::MiddleButton) { // setDragMode(QGraphicsView::ScrollHandDrag); // previousMousePoint = event->pos(); if (middleMouseMode == "SkyMode") { middleDragStartPos = event->pos(); middleButtonPressed = true; emit middlePress(middleDragStartPos); } if (middleMouseMode == "MaskingMode") { middleDragStartPos = event->pos(); middleButtonPressed = true; emit middlePress(middleDragStartPos); } else if (middleMouseMode == "DragMode") { middleButtonPressed = true; _pan = true; _panStartX = event->x(); _panStartY = event->y(); setCursor(Qt::OpenHandCursor); // event->accept(); } else if (middleMouseMode == "WCSMode") { emit middlePressResetCRPIX(); middleButtonPressed = true; wcsStart = event->pos(); setCursor(Qt::SizeAllCursor); } } QGraphicsView::mousePressEvent(event); } void MyGraphicsView::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { rightButtonPressed = false; emit rightButtonReleased(); } if (event->button() == Qt::LeftButton) { leftButtonPressed = false; emit leftButtonReleased(); } if (event->button() == Qt::MiddleButton) { middleButtonPressed = false; if (middleMouseMode == "SkyMode") { // setDragMode(QGraphicsView::NoDrag); emit middleButtonReleased(); } if (middleMouseMode == "MaskingMode") { emit middleButtonReleased(); } else if (middleMouseMode == "DragMode") { _pan = false; setCursor(Qt::ArrowCursor); // event->accept(); // return; } else if (middleMouseMode == "WCSMode") { emit middleWCSreleased(); setCursor(Qt::ArrowCursor); // event->accept(); // return; } } QGraphicsView::mouseReleaseEvent(event); } void MyGraphicsView::leaveEvent(QEvent *event) { emit mouseLeftView(); QGraphicsView::leaveEvent(event); } void MyGraphicsView::enterEvent(QEvent *event) { emit mouseEnteredView(); QGraphicsView::enterEvent(event); } void MyGraphicsView::paintEvent(QPaintEvent *event) { QRect viewport_rect(0, 0, viewport()->width(), viewport()->height()); emit viewportChanged(viewport_rect); QGraphicsView::paintEvent(event); } void MyGraphicsView::updateMiddleMouseMode(QString mode) { middleMouseMode = mode; } THELI-3.1.3/src/iview/mygraphicsview.h000066400000000000000000000052001417631501300175050ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYGRAPHICSVIEW_H #define MYGRAPHICSVIEW_H #include #include #include #include class MyGraphicsView : public QGraphicsView { Q_OBJECT private: QPointF rightDragStartPos; QPointF rightDragCurrentPos; QPointF rightDragEndPos; QPointF leftDragStartPos; QPointF leftDragCurrentPos; QPointF leftDragEndPos; // unused QPointF middleDragStartPos; QPointF middleDragCurrentPos; QPointF middleDragEndPos; bool rightButtonPressed = false; bool leftButtonPressed = false; bool middleButtonPressed = false; QPoint previousMousePoint; bool _pan = false; int _panStartX = 0; int _panStartY = 0; bool _wcs = false; QPoint wcsStart; public: explicit MyGraphicsView(); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void leaveEvent(QEvent *event); void enterEvent(QEvent *event); void paintEvent(QPaintEvent *event); QScrollBar *sxbar = nullptr; QScrollBar *sybar = nullptr; QString middleMouseMode = "DragMode"; int x = 0; int y = 0; signals: void currentMousePos(QPointF); void rightDragTravelled(QPointF); void middleSkyDragTravelled(QPointF pointStart, QPointF pointEnd); void middleMaskingDragTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSreleased(); void leftDragTravelled(QPointF pointStart, QPointF pointEnd); void rightPress(); void leftPress(QPointF pointStart); void middlePress(QPointF point); void leftButtonReleased(); void rightButtonReleased(); void middleButtonReleased(); void middlePressResetCRPIX(); void mouseLeftView(); void mouseEnteredView(); void viewportChanged(QRect viewport_rect); public slots: void updateMiddleMouseMode(QString mode); }; #endif // MYGRAPHICSVIEW_H THELI-3.1.3/src/iview/mymagnifiedgraphicsview.cc000066400000000000000000000075401417631501300215200ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mymagnifiedgraphicsview.h" #include "iview.h" MyMagnifiedGraphicsView::MyMagnifiedGraphicsView() : QGraphicsView() { QBrush brush(QColor("#000000")); brush.setStyle(Qt::SolidPattern); this->setBackgroundBrush(brush); } void MyMagnifiedGraphicsView::mouseMoveEvent(QMouseEvent *event) { QPoint currentPos = event->pos(); // Display the current pixel coordinates under the cursor QPointF currentPoint = mapToScene(currentPos); emit currentMousePos(currentPoint); // Also, if the right mouse button is pressed while moving, // adjust brightness and contrast if (rightButtonPressed) { emit rightDragTravelled(rightDragStartPos - currentPos); } if (middleButtonPressed) { // emit middleDragTravelled(previousMousePoint - currentPos); // emit middleDragTravelled(currentPos); if (middleMouseMode == "DragMode") { if (_pan) { horizontalScrollBar()->setValue(horizontalScrollBar()->value() - 2.*(event->x() - _panStartX)); verticalScrollBar()->setValue(verticalScrollBar()->value() - 2.*(event->y() - _panStartY)); _panStartX = event->x(); _panStartY = event->y(); // event->accept(); // return; } } } if (leftButtonPressed) { QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y()); emit leftDragTravelled(pointStart, currentPoint); } QGraphicsView::mouseMoveEvent(event); } void MyMagnifiedGraphicsView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { rightDragStartPos = event->pos(); rightButtonPressed = true; emit rightPress(); } if (event->button() == Qt::LeftButton) { leftDragStartPos = event->pos(); QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y()); leftButtonPressed = true; emit leftPress(pointStart); } if (event->button() == Qt::MiddleButton) { // setDragMode(QGraphicsView::ScrollHandDrag); // previousMousePoint = event->pos(); if (middleMouseMode == "DragMode") { middleButtonPressed = true; _pan = true; _panStartX = event->x(); _panStartY = event->y(); setCursor(Qt::OpenHandCursor); // event->accept(); } } QGraphicsView::mousePressEvent(event); } void MyMagnifiedGraphicsView::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { rightButtonPressed = false; emit rightButtonReleased(); } if (event->button() == Qt::LeftButton) { leftButtonPressed = false; emit leftButtonReleased(); } if (event->button() == Qt::MiddleButton) { middleButtonPressed = false; if (middleMouseMode == "DragMode") { _pan = false; setCursor(Qt::ArrowCursor); // event->accept(); // return; } } QGraphicsView::mouseReleaseEvent(event); } void MyMagnifiedGraphicsView::updateMiddleMouseMode(QString mode) { middleMouseMode = mode; } THELI-3.1.3/src/iview/mymagnifiedgraphicsview.h000066400000000000000000000046101417631501300213550ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYMAGNIFIEDGRAPHICSVIEW_H #define MYMAGNIFIEDGRAPHICSVIEW_H #include #include #include #include class MyMagnifiedGraphicsView : public QGraphicsView { Q_OBJECT private: QPointF rightDragStartPos; QPointF rightDragCurrentPos; QPointF rightDragEndPos; QPointF leftDragStartPos; QPointF leftDragCurrentPos; QPointF leftDragEndPos; // unused QPointF middleDragStartPos; QPointF middleDragCurrentPos; QPointF middleDragEndPos; bool rightButtonPressed = false; bool leftButtonPressed = false; bool middleButtonPressed = false; QPoint previousMousePoint; bool _pan = false; int _panStartX = 0; int _panStartY = 0; bool _wcs = false; QPoint wcsStart; public: explicit MyMagnifiedGraphicsView(); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); QScrollBar *sxbar = nullptr; QScrollBar *sybar = nullptr; QString middleMouseMode = "DragMode"; int x = 0; int y = 0; signals: void currentMousePos(QPointF); void rightDragTravelled(QPointF); void middleDragTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSreleased(); void leftDragTravelled(QPointF pointStart, QPointF pointEnd); void rightPress(); void leftPress(QPointF pointStart); void middlePress(QPointF point); void leftButtonReleased(); void rightButtonReleased(); void middleButtonReleased(); void middlePressResetCRPIX(); public slots: void updateMiddleMouseMode(QString mode); }; #endif // MYMAGNIFIEDGRAPHICSVIEW_H THELI-3.1.3/src/iview/myqgraphicsrectitem.cc000066400000000000000000000027621417631501300207000ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myqgraphicsrectitem.h" #include #include #include MyQGraphicsRectItem::MyQGraphicsRectItem() : QGraphicsRectItem() { } // Constrains the rectangle movement to the scene range QVariant MyQGraphicsRectItem::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == ItemPositionChange && scene()) { // value is the new position. QPointF newPos = value.toPointF(); QRectF rect = scene()->sceneRect(); if (!rect.contains(newPos)) { // Keep the item inside the scene rect. newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left()))); newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top()))); return newPos; } } return QGraphicsItem::itemChange(change, value); } THELI-3.1.3/src/iview/myqgraphicsrectitem.h000066400000000000000000000021521417631501300205330ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYQGRAPHICSRECTITEM_H #define MYQGRAPHICSRECTITEM_H #include class MyQGraphicsRectItem : public QObject, public QGraphicsRectItem { Q_OBJECT // inherit constructors using QGraphicsRectItem::QGraphicsRectItem; public: explicit MyQGraphicsRectItem(); protected: virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); signals: public slots: }; #endif // MYQGRAPHICSRECTITEM_H THELI-3.1.3/src/iview/redshift.cc000066400000000000000000000216571417631501300164300ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "iview.h" #include "ui_iview.h" #include "ui_ivredshiftdockwidget.h" #include "ui_ivconfdockwidget.h" #include "../functions.h" #include "mygraphicsview.h" #include "mygraphicsscene.h" #include void IView::updateAxesHelper() { observedAxis.init(currentMyImage->wcs->crval[0], currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, 75, "down", QColor("#00aaff")); restframeAxis.init(currentMyImage->wcs->crval[0], currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, 25, "down", QColor("#ffdd00")); spectrumAxis.init(currentMyImage->wcs->crval[0], currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, -25, "down", QColor("#ffdd00"), "spectrum"); // observedAxis.init(currentMyImage->crval1, currentMyImage->header., currentMyImage->naxis1, currentMyImage->naxis2, 75, "down", QColor("#00aaff")); // restframeAxis.init(currentMyImage->crval1, currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, 25, "down", QColor("#ffdd00")); // spectrumAxis.init(currentMyImage->crval1, currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, -25, "down", QColor("#ffdd00"), "spectrum"); // Populate the spectrum axis with emission lines spectrumAxis.tickLength = 20.; if (zdw->ui->HCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->HList); if (zdw->ui->NCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->NList); if (zdw->ui->OCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->OList); if (zdw->ui->SCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->SList); if (zdw->ui->CCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->CList); if (zdw->ui->HeCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->HeList); if (zdw->ui->ArCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->ArList); if (zdw->ui->NeCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->NeList); if (zdw->ui->MgCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->MgList); if (zdw->ui->NaCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->NaList); if (zdw->ui->CaCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->CaList); if (zdw->ui->FeCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->FeList); } void IView::updateAxes() { if (!zdw->isVisible()) return; // This slot is invoked (among others) everytime a new image is loaded clearAxes(); updateAxesHelper(); // Do not show axes if redshift Dockwidget is not visible if (!zdw->isVisible()) return; showAxes(); } // Invoked e.g. after right-click dragging. Must not redraw graphics scene, as this is done in main iView void IView::redrawUpdateAxes() { if (!zdw->isVisible()) return; updateAxesHelper(); showAxesHelper(observedAxisLineItems, observedAxisMainLineItems, observedAxisTextItems, observedAxis, "observed"); showAxesHelper(restframeAxisLineItems, restframeAxisMainLineItems, restframeAxisTextItems, restframeAxis, "restframe"); showAxesHelper(spectrumAxisLineItems, spectrumAxisMainLineItems, spectrumAxisTextItems, spectrumAxis, "spectrum"); } void IView::showAxes() { if (!zdw->isVisible()) return; showAxesHelper(observedAxisLineItems, observedAxisMainLineItems, observedAxisTextItems, observedAxis, "observed"); showAxesHelper(restframeAxisLineItems, restframeAxisMainLineItems, restframeAxisTextItems, restframeAxis, "restframe"); showAxesHelper(spectrumAxisLineItems, spectrumAxisMainLineItems, spectrumAxisTextItems, spectrumAxis, "spectrum"); myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::showAxesHelper(QList &lineItemList, QList &mainLineItemList, QList &textItemList, const MyAxis &axis, QString type) { // Remove all previously displayed items // Tickmarks if (!lineItemList.isEmpty()) { for (auto &it: lineItemList) scene->removeItem(it); lineItemList.clear(); } // Main axis if (!mainLineItemList.isEmpty()) { for (auto &it: mainLineItemList) scene->removeItem(it); mainLineItemList.clear(); } // Add the main axis line if requested (not for the emission line tickmarks) if (type != "spectrum") mainLineItemList.append(scene->addLine(axis.axisLine)); for (auto &it: axis.tickMarks) { lineItemList.append(scene->addLine(it)); } for (auto &it: lineItemList) { it->setPen(axis.pen); } for (auto &it: mainLineItemList) { it->setPen(axis.pen); } // Add the labels; this is in the same order as the line items, so the matching is preserved for (auto &it : axis.tickLabels) { textItemList.append(scene->addText(it)); } // Setup the font QFont currentFont = this->font(); qreal rescale; if (!icdw->ui->zoomFitPushButton->isChecked()) rescale = icdw->zoom2scale(zoomLevel); else rescale = myGraphicsView->transform().m11(); currentFont.setPointSize(int(float(currentFont.pointSize())/rescale)); int i=0; QTransform transform; transform.rotate(-45); for (auto &it : textItemList) { it->setFont(currentFont); QString plainText = it->toPlainText(); // use a semi-transparent background if (type != "observed") it->setHtml(QString("
" + QString(" ") + plainText + QString(" ") + QString("
") )); else it->setHtml(QString("
" + QString(" ") + plainText + QString(" ") + QString("
") )); it->setDefaultTextColor(QColor("#000000")); qreal xpos = lineItemList.at(i)->line().x1(); qreal ypos = lineItemList.at(i)->line().y1(); ++i; int offset = 0; if (type == "observed") offset = 5; if (type == "restframe") offset = 5; if (type == "spectrum") offset = -10; it->setPos(xpos-20/icdw->zoom2scale(zoomLevel), ypos+offset/icdw->zoom2scale(zoomLevel)); if (type == "spectrum") it->setTransform(transform); } } void IView::clearAxes() { if (!zdw->isVisible()) return; observedAxis.clear(); restframeAxis.clear(); spectrumAxis.clear(); clearAxesHelper(observedAxisLineItems, observedAxisMainLineItems, observedAxisTextItems); clearAxesHelper(restframeAxisLineItems, restframeAxisMainLineItems, restframeAxisTextItems); clearAxesHelper(spectrumAxisLineItems, spectrumAxisMainLineItems, spectrumAxisTextItems); myGraphicsView->setScene(scene); myGraphicsView->show(); } void IView::clearAxesHelper(QList &lineItemList, QList &mainLineItemList, QList &textItemList) { // Remove all previously displayed items if (!lineItemList.isEmpty()) { for (auto &it: lineItemList) scene->removeItem(it); lineItemList.clear(); } if (!mainLineItemList.isEmpty()) { for (auto &it: mainLineItemList) scene->removeItem(it); mainLineItemList.clear(); } if (!textItemList.isEmpty()) { for (auto &it: textItemList) scene->removeItem(it); textItemList.clear(); } } // Sends the wavelength under the cursor to redshiftDockWidget void IView::showWavelength(QPointF point) { if (!zdw->isVisible()) return; // This function receives the image coords from a mouseMoveEvent // and translates them to wavelengths // constant offsets required to show same coordinates as in skycat / ds9 float x_cursor = point.x() + 0.5; double lambdaObs = observedAxis.pixelToWavelength(x_cursor); double lambdaRest = restframeAxis.pixelToWavelength(x_cursor); emit wavelengthUpdated(QString::number(lambdaObs, 'f', 1), QString::number(lambdaRest, 'f', 1)); } void IView::updateFinesse(int value) { restframeAxis.finesse = 2000.*pow(2,value-5)/(1.+restframeAxis.z); spectrumAxis.finesse = 2000.*pow(2,value-5)/(1.+restframeAxis.z); } void IView::resetRedshift() { restframeAxis.z = 0.; restframeAxis.z_0 = 0.; spectrumAxis.z = 0.; spectrumAxis.z_0 = 0.; zdw->ui->zLineEdit->setText("0.000"); } void IView::redshiftChanged(QString text) { float z = 0.; if (text.isEmpty()) z = 0.; else z = text.toFloat(); restframeAxis.z = z; spectrumAxis.z = z; restframeAxis.z_0 = z; spectrumAxis.z_0 = z; updateAxes(); } THELI-3.1.3/src/iview/transformations.cc000066400000000000000000000046011417631501300200370ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "iview.h" #include "ui_iview.h" // qimage: the coordinate system of the displayed QImage // myimage: the coordinate system of the FITS image void IView::qimageToBinned(qreal qx, qreal qy, qreal &bx, qreal &by) { qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1; bx = qx * qreal(icdw->navigator_binned_nx) / norm; by = qy * qreal(icdw->navigator_binned_ny) / norm; } QPointF IView::qimageToBinned(const QPointF qpoint) { qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1; qreal qx = qpoint.x(); qreal qy = qpoint.y(); qreal bx = qx * qreal(icdw->navigator_binned_nx) / norm; qreal by = qy * qreal(icdw->navigator_binned_ny) / norm; QPointF bpoint; bpoint.setX(bx); bpoint.setY(by); return bpoint; } QRect IView::qimageToBinned(const QRectF qrect) { qreal qx1 = 0.; qreal qy1 = 0.; qreal qx2 = 0.; qreal qy2 = 0.; qrect.getCoords(&qx1, &qy1, &qx2, &qy2); qreal bx1; qreal bx2; qreal by1; qreal by2; qimageToBinned(qx1, qy1, bx1, by1); qimageToBinned(qx2, qy2, bx2, by2); QRect brect; brect.setCoords(bx1, by1, bx2, by2); return brect; } void IView::binnedToQimage(qreal bx, qreal by, qreal &qx, qreal &qy) { qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1; qx = bx * norm / qreal(icdw->navigator_binned_nx); qy = by * norm / qreal(icdw->navigator_binned_ny); } QPointF IView::binnedToQimage(const QPointF bpoint) { qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1; qreal bx = bpoint.x(); qreal by = bpoint.y(); qreal qx = bx * norm / qreal(icdw->navigator_binned_nx); qreal qy = by * norm / qreal(icdw->navigator_binned_ny); QPointF qpoint; qpoint.setX(qx); qpoint.setY(qy); return qpoint; } THELI-3.1.3/src/main.cc000066400000000000000000000224041417631501300144100ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainwindow.h" #include "functions.h" #include #include #include #include #include #include #include #include #include #include #include #include "fitsio.h" void dependencyCheck(); void compatibilityCheck(); int main(int argc, char *argv[]) { QApplication a(argc, argv); std::locale::global( std::locale( "C" ) ); // Read the THELIDIR environment variable if (!QProcessEnvironment::systemEnvironment().contains("THELIDIR")) { // See if we can find it under /usr/share/theli/ QDir thelidir1("/usr/share/theli/config/"); QDir thelidir2("/usr/share/theli/python/"); if (thelidir1.exists() && thelidir2.exists()) { // system-wide installation found, we are good! } else { QMessageBox::critical(0,"THELI","THELI configuration files not found under /usr/share/theli/\n\n" "You can fix this by setting the THELIDIR environment variable. For example, if the THELI source tree was installed under \n" ""+QDir::homePath()+"/THELI/ and you are using the 'bash' shell, " "then you would include the following line in your .bashrc file:\n\n" "export THELIDIR="+QDir::homePath()+"/THELI/", QMessageBox::Ok); exit (1); } } // Dependency checks dependencyCheck(); // Compatibility checks compatibilityCheck(); // Required when starting the first time QString dotTheliName = QDir::homePath()+"/.theli/"; QDir dotTheli(dotTheliName); dotTheli.mkdir(dotTheliName); dotTheli.mkdir(dotTheliName+"/instruments_user"); // Fetch the process ID of the main program QString mainPID = QString::number(QCoreApplication::applicationPid()); MainWindow w(mainPID); w.show(); return a.exec(); } void dependencyCheck() { // Dependency checks QString scamp = findExecutableName("scamp"); // testing different executable names QString swarp = findExecutableName("swarp"); QString sourceExtractor = findExecutableName("source-extractor"); QString python = findExecutableName("python"); QString anet1 = findExecutableName("build-astrometry-index"); QString anet2 = findExecutableName("solve-field"); QString anet3 = findExecutableName("astrometry-engine"); QString scampDep = ""; QString swarpDep = ""; QString sourceExtractorDep = ""; QString anetDep = ""; QString pythonDep = ""; int missingDep = 0; if (anet1.isEmpty()) { anetDep += "astrometry.net 'build-astrometry-index' not found.\n"; } if (anet2.isEmpty()) { anetDep = "astrometry.net 'solve-field' not found.\n"; } // if (anet3.isEmpty()) { // anetDep += "astrometry.net 'astrometry-engine' not found.\n"; // } if (python.isEmpty()) { pythonDep = "python v3 required (working binary names: 'python3' or 'python').\n"; } else { // Check that we are using python3 QString pythonCommand = python + " --version"; QString result = read_system_command(pythonCommand); QStringList list = result.split(" "); if (list.length() > 1) { int version = list.at(1).split('.').at(0).toInt(); if (version < 3) { pythonDep = "python v3 or later required. Installed version: " + result + "\n"; ++missingDep; } } } if (!anetDep.isEmpty()) { qDebug() << "Astrometry.net installation was not found. Corresponding solvers are deactivated."; qDebug() << "Astrometry.net is available at https://github.com/dstndstn/astrometry.net/releases\n"; } if (scamp.isEmpty()) { scampDep = "'Scamp' v2.0.4 or later required (working binary names: 'scamp' or 'Scamp').\n\nhttps://github.com/astromatic/scamp\n"; ++missingDep; } else { // Check if scamp has the right version QString scampCommand = scamp + " -v"; QString result = read_system_command(scampCommand); QStringList list = result.split(" "); if (list.length() < 3) { qDebug() << "WARNING: Unexpected output format when checking Scamp version:" << result; qDebug() << "WARNING: Required version: 2.0.4 or later"; } else { // Minimum scamp version required: 2.0.4 int version = list[2].remove('.').toInt(); if (version < 204) { scampDep = "'Scamp' v2.0.4 or later required.\n\nhttps://github.com/astromatic/scamp\nInstalled: " + result + "\n"; ++missingDep; } } } if (swarp.isEmpty()) { swarpDep = "'Swarp' v2.38.0 or later required (working binary names: 'swarp', 'Swarp' or 'SWarp').\n\nhttps://github.com/astromatic/swarp\n"; ++missingDep; } else { // Check if swarp has the right version QString swarpCommand = swarp + " -v"; QString result = read_system_command(swarpCommand); QStringList list = result.split(" "); if (list.length() < 3) { qDebug() << "WARNING: Unexpected output format when checking swarp version:" << result; qDebug() << "WARNING: Required version: 2.38.0 or later"; } else { // Minimum swarp version required: 2.38.0 int version = list[2].remove('.').toInt(); if (version < 2380) { swarpDep = "'swarp' v2.38.0 or later required.\n\nhttps://github.com/astromatic/swarp\nInstalled: " + result + "\n"; ++missingDep; } } } if (sourceExtractor.isEmpty()) { sourceExtractorDep = "'Source Extractor' v2.19.5 or later required (working binary names: 'source-extractor', 'sextractor', 'SExtractor', or 'sex'), available from\nhttps://github.com/astromatic/sextractor\n"; ++missingDep; } else { // Check if Source Extractor has the right version // expected formats are: // Source Extractor version 2.25.0 (2020-03-19) // Source Extractor version 2.25.0 (2018-02-08) QString sourceExtractorCommand = sourceExtractor + " -v"; QString result = read_system_command(sourceExtractorCommand); QString resultOrig = result; result.remove("SExtractor", Qt::CaseInsensitive); result.remove("Source", Qt::CaseInsensitive); result.remove("Extractor", Qt::CaseInsensitive); result.remove("version", Qt::CaseInsensitive); result = result.simplified(); QStringList list = result.split(" "); if (list.length() != 2) { qDebug() << "WARNING: Unexpected output format when checking Source Extractor version:" << resultOrig; qDebug() << "WARNING: Required version: 2.19.5 or later"; } else { // Minimum Source Extractor version required: 2.19.5 int version = list[0].remove('.').toInt(); if (version < 2195) { sourceExtractorDep = "'Source Extractor' v2.19.5 or later required.\n\nhttps://github.com/astromatic/sextractor\nInstalled: " + result + "\n"; ++missingDep; } } } if (missingDep == 0) return; QString title = "Missing dependency:\n\n"; if (missingDep > 1) title = "Missing dependencies:\n\n"; QMessageBox::critical(0, "THELI", title +scampDep +swarpDep +pythonDep +sourceExtractorDep, QMessageBox::Ok); exit (1); } void compatibilityCheck() { if (!fits_is_reentrant()) { QMessageBox msgBox; msgBox.setText("CFITSIO library not reentrant!"); msgBox.setInformativeText("Your cfitsio library does not support parallelization. The maximum number of usable CPUs has been limited to 1.\n\n" "To use parallelization, recompile the cfitsio library using\n\n" "./configure --enable-reentrant"); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Abort); msgBox.setDefaultButton(QMessageBox::Ok); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Abort: exit (1); case QMessageBox::Ok: break; default: // should never be reached break; } } } THELI-3.1.3/src/mainwindow.cc000066400000000000000000002420501417631501300156410ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "functions.h" #include "status.h" #include "iview/iview.h" #include "colorpicture/colorpicture.h" #include "instrumentdefinition.h" #include "tools/tools.h" #include "instrumentdata.h" #include "processingInternal/controller.h" #include "processingInternal/data.h" #include "dockwidgets/confdockwidget.h" #include "dockwidgets/monitor.h" #include "dockwidgets/memoryviewer.h" #include "tools/cpu.h" #include "tools/ram.h" #include "ui_confdockwidget.h" #include "ui_memoryviewer.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include MainWindow::MainWindow(QString pid, QWidget *parent) : QMainWindow(parent), mainPID(pid), ui(new Ui::MainWindow) { ui->setupUi(this); // WARNING! THIS IS A VERY CAREFULLY BALANCED SETUP // TO DO THINGS IN THE RIGHT ORDER. // some of the routines called here are also used later on, e.g. // changing settings parameters and so on. For some of them we don't want // them to execute all of their code, for example when they are called during the first init of the GUI. doingInitialLaunch = true; initProcessingStatus(); initEnvironment(thelidir, userdir); instrument_userDir = userdir+"/instruments_user/"; instrument_dir = thelidir+"/config/instruments/"; // Setup hardware QSysInfo *sysInfo = new QSysInfo; kernelType = sysInfo->kernelType(); // returns "linux" or "darwin" productName = sysInfo->prettyProductName().replace(" ","_"); systemRAM = get_memory(); delete sysInfo; QPalette palette; palette.setColor(QPalette::Base,QColor("#ffffff")); palette.setColor(QPalette::Background,QColor("#cccccc")); ui->statusBar->setPalette(palette); ui->statusBar->setAutoFillBackground(true); ui->menuBar->setPalette(palette); ui->menuBar->setAutoFillBackground(true); addProgressBars(); establish_connections(); // Meaningful overview comments shown when running a task populateTaskCommentMap(); // must populate the instrument listview before reading the settings QString projectname; readPreferenceSettings(projectname); // the next one can be adjusted when manually loading a project file // actually, think it is not needed here because it must also be invoked by readGUIsettings() below // fill_setupInstrumentComboBox(); // Create dock widgets (before reading settings) cdw = new ConfDockWidget(this); monitor = new Monitor(this); // perhaps before initializeGuiLayout? // Also calls fill_setupInstrumentComboBox() readGUISettings(projectname); // Update some confdockwidget displays according to settings cdw->toggle_skyparams(); cdw->toggle_skyparamThresholds(""); // If the user launches THELI the very first time, then on_setupInstrumentComboBox_clicked does // not get triggered (don't know why not); do it manually: if (instData.name.isEmpty()) on_setupInstrumentComboBox_clicked(); // Fix some paint events triggered by readSettings(). // The reason is that the settings are not written in order. // Settings change the dir names, triggering a paint event, // which results in red background for some elements because // the main dir is not set first. Hence the repaint. repaintDataDirs(); // The entity that keeps track of the data, incl connections QString statusOld = status.getStatusFromHistory(); // NOTE: setting up the controller may take a while (when creating object masks) controller = new Controller(&instData, statusOld, cdw, monitor, this); // LineEdit changes update controller for (auto &it : status.listDataDirs) { // connect(it, &QLineEdit::textChanged, controller, &Controller::updateSingle); connect(it, &QLineEdit::editingFinished, controller, &Controller::dataTreeEditedReceived); // editing finished not emitted if dirs are empty (because of the validator) connect(it, &QLineEdit::textChanged, this, &MainWindow::emitEditingFinished); } // Initial configuration of MainWindow initGUI(); // Repaint background of previously executed tasks. // initGUI loads the style sheet, thus defaulting to backgrounds status.history2checkbox(); // this->setStyleSheet("QComboBox:hover { background-color: #99ccff };"); // The entity that keeps track of the data, incl connections // QString statusOld = status.getStatusFromHistory(); // Another dock widget, must be done after instantiating the controller memoryViewer = new MemoryViewer(controller, this); controller->memoryViewer = memoryViewer; controller->instrument_dir = instrument_dir; controller->connectDataWithMemoryViewer(); connect(controller, &Controller::clearMemoryView, memoryViewer, &MemoryViewer::clearMemoryViewReceived, Qt::DirectConnection); connect(controller, &Controller::populateMemoryView, memoryViewer, &MemoryViewer::populateMemoryViewReceived); connect(controller, &Controller::addBackupDirToMemoryviewer, memoryViewer, &MemoryViewer::addBackupDirReceived); // Combine mode changes update controller connect(cdw->ui->overscanMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors); connect(cdw->ui->biasMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors); connect(cdw->ui->darkMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors); connect(cdw->ui->flatoffMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors); connect(cdw->ui->flatMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors); connect(ui->setupInstrumentComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateController); // Initiate the controller functors; updateControllerFunctors(""); // Internal processing connect(controller, &Controller::loadViewer, this, &MainWindow::launchViewer); connect(controller, &Controller::loadAbsZP, this, &MainWindow::loadCoaddAbsZP); connect(controller, &Controller::messageAvailable, monitor, &Monitor::displayMessage); connect(controller, &Controller::appendOK, monitor, &Monitor::appendOK); connect(controller, &Controller::showMessageBox, this, &MainWindow::showMessageBoxReceived); connect(controller, &Controller::progressUpdate, this, &MainWindow::progressUpdateReceived); connect(controller, &Controller::resetProgressBar, this, &MainWindow::resetProgressBarReceived); connect(controller, &Controller::targetResolved, cdw, &ConfDockWidget::targetResolvedReceived); connect(controller, &Controller::scienceDataDirUpdated, this, &MainWindow::scienceDataDirUpdatedReceived); connect(controller, &Controller::updateMemoryProgressBar, this, &MainWindow::updateMemoryProgressBarReceived); connect(controller, &Controller::forceFinish, this, &MainWindow::taskFinished); connect(controller, &Controller::refreshMemoryViewer, this, &MainWindow::refreshMemoryViewerReceiver); connect(this, &MainWindow::resetErrorStatus, controller, &Controller::resetErrorStatusReceived); connect(this, &MainWindow::rereadScienceDataDir, controller, &Controller::rereadScienceDataDirReceived); connect(this, &MainWindow::newProjectLoaded, controller, &Controller::newProjectLoadedReceived); connect(this, &MainWindow::messageAvailable, monitor, &Monitor::displayMessage); connect(this, &MainWindow::warning, monitor, &Monitor::raise); connect(ui->setupMainLineEdit, &QLineEdit::textChanged, cdw, &ConfDockWidget::updateAPIsolutions); connect(ui->setupStandardLineEdit, &QLineEdit::textChanged, cdw, &ConfDockWidget::updateAPIsolutions); connect(cdw, &QDockWidget::dockLocationChanged, this, &MainWindow::cdw_dockLocationChanged); connect(cdw, &QDockWidget::topLevelChanged, this, &MainWindow::cdw_topLevelChanged); // Must be done after readGUIsettings() addDockWidgets(); doingInitialLaunch = false; memoryViewer->populate(); // Need this after connecting status dirs to paint checkboxes correctly. // Doesn't work if done further above, not sure why // Does the right thing (repaint check boxes), but it seems random at best. Only updates tabwidet shown status.updateStatus(); // repaint; doesn't seem to help in painting the checkboxes correctly // update(); startProgressBars(); // must (or should) be done after settings are read and controller is live estimateBinningFactor(); setHomeDir(); // mostly first time launch, only updateExcludedDetectors(cdw->ui->excludeDetectorsLineEdit->text()); } void MainWindow::closeEvent(QCloseEvent *event) { bool accept = true; QString filepath; if (kernelType == "linux") filepath = QDir::homePath()+"/.config/THELI/"; else if (kernelType == "darwin") filepath = QDir::homePath()+"/Library/Preferences/THELI/"; if (writePreferenceSettings() != QSettings::NoError) { qDebug() << "closeEvent: Could not save preference settings."; } if (writeGUISettings() == QSettings::NoError) accept = accept && true; else if (writeGUISettings() == QSettings::AccessError) { const QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Application"), tr("A file access error occurred while writing the project configuration to\n")+ filepath+"\n", QMessageBox::Ok | QMessageBox::Cancel); switch (ret) { case QMessageBox::Ok: accept = accept && true; break; case QMessageBox::Cancel: accept = accept && false; break; default: break; } } else if (writeGUISettings() == QSettings::FormatError) { const QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Application"), tr("A formatting error occurred when writing the project configuration to\n")+ filepath+"\n", QMessageBox::Ok | QMessageBox::Cancel); switch (ret) { case QMessageBox::Ok: accept = accept && true; break; case QMessageBox::Cancel: accept = accept && false; break; default: break; } } // write out data in memory long numUnsavedImagesLatestStage = 0; long numUnsavedImagesBackup = 0; controller->checkForUnsavedImages(numUnsavedImagesLatestStage, numUnsavedImagesBackup); if (numUnsavedImagesLatestStage > 0 || numUnsavedImagesBackup > 0) { long mBytesLatest = numUnsavedImagesLatestStage*instData.storage; long mBytesBackup = numUnsavedImagesBackup*instData.storage; long mBytesAll = mBytesLatest + mBytesBackup; QString saveLatestString = ""; QString saveAllString = ""; if (numUnsavedImagesLatestStage > 0) saveLatestString = "The current project keeps "+QString::number(numUnsavedImagesLatestStage) + " unsaved images of the latest processing stage in memory.\n"; if (numUnsavedImagesBackup > 0) saveAllString = "The current project keeps "+QString::number(numUnsavedImagesBackup) + " unsaved images with earlier processing stages in memory.\n"; QMessageBox msgBox; msgBox.setModal(true); msgBox.setInformativeText(tr("Unsaved images detected.\n") + saveLatestString + saveAllString + "\n"); QAbstractButton *pButtonSaveLatest = msgBox.addButton(tr("Save latest images (")+QString::number(mBytesLatest)+" MB) and close", QMessageBox::YesRole); QAbstractButton *pButtonSaveAll = msgBox.addButton(tr("Save all images (")+QString::number(mBytesAll)+" MB) and close", QMessageBox::YesRole); QAbstractButton *pButtonContinue = msgBox.addButton(tr("Close without saving"), QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); if (numUnsavedImagesLatestStage == 0) pButtonSaveLatest->hide(); if (numUnsavedImagesBackup == 0) pButtonSaveAll->hide(); msgBox.exec(); if (msgBox.clickedButton() == pButtonSaveLatest) { if (sufficientSpaceAvailable(mBytesLatest)) { // sufficientSpaceAvailable() displays a warning message controller->writeUnsavedImagesToDrive(false); accept = accept && true; } else { accept = accept && false; } } else if (msgBox.clickedButton() == pButtonSaveAll) { if (sufficientSpaceAvailable(mBytesAll)) { controller->writeUnsavedImagesToDrive(true); accept = accept && true; } else { accept = accept && false; } } else if (msgBox.clickedButton() == pButtonContinue) { accept = accept && true; } else if (msgBox.clickedButton() == pButtonCancel) { accept = accept && false; } } if (accept) event->accept(); else event->ignore(); } void MainWindow::emitEditingFinished(const QString &arg1) { QLineEdit* lineedit = qobject_cast(sender()); if (arg1.isEmpty()) lineedit->editingFinished(); } MainWindow::~MainWindow() { // delete class variables that have been assigned with 'new': delete instrument_model; instrument_model = nullptr; delete ui; } void MainWindow::addProgressBars() { // Add diskspace progress bar to the status bar and connect it to a timer that updates it repeatedly. // Don't have to delete the statusBar separately because it is a child of 'ui' and constructed after 'ui' driveProgressBar = new QProgressBar(this); driveProgressBar->setMinimumWidth(200); driveProgressBar->setMaximumWidth(200); cpuProgressBar = new QProgressBar(this); cpuProgressBar->setMinimumWidth(200); cpuProgressBar->setMaximumWidth(200); memoryProgressBar = new QProgressBar(this); memoryProgressBar->setMinimumWidth(200); memoryProgressBar->setMaximumWidth(200); ui->processProgressBar->setMinimumWidth(200); ui->processProgressBar->setMaximumWidth(200); // progress bars cannot be added to menuBar under MacOs (at least in 2011) /* if (kernelType == "darwin") ui->statusBar->addPermanentWidget(driveProgressBar, 0); else { // bar doesnt show under linux, either QWidgetAction* actionProgressBar = new QWidgetAction(this); actionProgressBar->setDefaultWidget(driveProgressBar); ui->menuBar->addAction(actionProgressBar); } */ QSysInfo *sysInfo = new QSysInfo; QString kernelType = sysInfo->kernelType(); // Push the progress bars to the right, with little spacers in between; QWidget* empty = new QWidget(); QWidget* empty1 = new QWidget(); QWidget* empty2 = new QWidget(); empty->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); empty1->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); empty2->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); empty1->setMinimumWidth(10); empty2->setMinimumWidth(10); if (kernelType == "linux") { ui->toolBar->addWidget(empty); ui->toolBar->addWidget(driveProgressBar); ui->toolBar->addWidget(empty1); ui->toolBar->addWidget(cpuProgressBar); ui->toolBar->addWidget(empty2); ui->toolBar->addWidget(memoryProgressBar); } else if (kernelType == "darwin") { // Progress Bars not supported in macOS in the top toolBar ui->statusBar->addWidget(empty); ui->statusBar->addWidget(driveProgressBar); ui->statusBar->addWidget(empty1); ui->statusBar->addWidget(cpuProgressBar); ui->statusBar->addWidget(empty2); ui->statusBar->addWidget(memoryProgressBar); } delete sysInfo; sysInfo = nullptr; } // should be done after controller has been established and settings have been read void MainWindow::startProgressBars() { // Start the progress bars myCPU = new CPU(this); myRAM = new RAM(this); // Memory and CPU bars get updated every 2 seconds // Must be declared / launched after data tree has been mapped. ramTimer = new QTimer(this); cpuTimer = new QTimer(this); driveTimer = new QTimer(this); connect(ramTimer, SIGNAL(timeout()), SLOT(displayRAMload())); connect(cpuTimer, SIGNAL(timeout()), SLOT(displayCPUload())); connect(driveTimer, SIGNAL(timeout()), SLOT(displayDriveSpace())); ramTimer->start(2000); cpuTimer->start(2000); driveTimer->start(2000); cpuProgressBar->setRange(0, 100*QThread::idealThreadCount()); long totalMemory = get_memory(); myRAM->totalRAM = totalMemory; memoryProgressBar->setRange(0, totalMemory / 1024); // [MB] memoryProgressBar->setValue(0); } void MainWindow::displayCPUload() { // int CPUload = myCPU->getCPUload(); float CPUload = myCPU->getCurrentValue(); QString CPUstring = QString::number(int(CPUload)) + " %"; cpuProgressBar->setFormat("CPU: "+CPUstring); cpuProgressBar->setValue(int(CPUload)); } void MainWindow::displayRAMload() { float RAMload = myRAM->getCurrentValue(); QString RAMstring = QString::number(long(RAMload)) + " MB"; memoryProgressBar->setFormat("RAM: %p% ("+RAMstring+")"); memoryProgressBar->setValue(int(RAMload)); } void MainWindow::displayDriveSpace() { // Storage space in the main/home directory QString maindir = ui->setupMainLineEdit->text(); double GBtotal_data, GBfree_data, GBused_data; double GBtotal_home, GBfree_home, GBused_home; QStorageInfo storage_home(QDir::homePath()); if (storage_home.isValid() && storage_home.isReady()) { GBtotal_home = storage_home.bytesTotal()/1024./1024./1024.; GBfree_home = storage_home.bytesAvailable()/1024./1024./1024.; GBused_home = GBtotal_home - GBfree_home; } else { emit messageAvailable("Controller::displayDriveSpace(): Cannot determine home directory!", "error"); return; } QStorageInfo storage_data(maindir); if (storage_data.isValid() && storage_data.isReady()) { GBtotal_data = storage_data.bytesTotal()/1024./1024./1024.; GBfree_data = storage_data.bytesAvailable()/1024./1024./1024.; GBused_data = GBtotal_data - GBfree_data; } else { GBtotal_data = GBtotal_home; GBfree_data = GBfree_home; GBused_data = GBused_home; } driveProgressBar->setRange(0, GBtotal_data); QString datadiskstring = QString::number(GBfree_data,'f',2) + " GB left"; // check if the data disk warning should be activated if (GBfree_data <= diskwarnPreference/1024.) { // preference is given in MB if (!datadiskspace_warned) { datadiskspace_warned = true; if (maindir.isEmpty()) maindir = QDir::homePath(); QMessageBox::warning( this, "THELI: DATA DISK SPACE LOW", "The remaining disk space on\n\n" + maindir+"\n\nis less than your warning threshold of " + QString::number(diskwarnPreference)+" MB.\n" "The threshold can be set under Edit->Preferences in the main menu. " "This warning will not be shown anymore in this session, " "unless you update the threshold to a new value."); } } else datadiskspace_warned = false; if (GBfree_home <= 0.1) { if (!homediskspace_warned) { homediskspace_warned = true; QMessageBox::warning( this, "THELI: HOME DISK SPACE LOW", "THELI: You are running low (<100 MB) on disk space in your home directory!\n"); } } else homediskspace_warned = false; driveProgressBar->setFormat("Drive: "+datadiskstring); driveProgressBar->setValue(GBused_data); } void MainWindow::addDockWidgets() { addDockWidget(Qt::RightDockWidgetArea, cdw); cdw->setFloating(false); addDockWidget(Qt::RightDockWidgetArea, monitor); monitor->setFloating(false); addDockWidget(Qt::RightDockWidgetArea, memoryViewer); memoryViewer->setFloating(false); // Create tabbed dock widgets tabifyDockWidget(cdw, monitor); tabifyDockWidget(monitor, memoryViewer); cdw->raise(); } void MainWindow::resetProgressBarReceived() { ui->processProgressBar->setValue(0); } void MainWindow::updateController() { controller->instData = &instData; controller->updateAll(); } void MainWindow::updateControllerFunctors(QString text) { if (cdw->ui->overscanMethodComboBox->currentText() == "Line median") controller->combineOverscan_ptr = &medianMask; else if (cdw->ui->overscanMethodComboBox->currentText() == "Line mean") controller->combineOverscan_ptr = &meanMask; else controller->combineOverscan_ptr = nullptr; if (cdw->ui->biasMethodComboBox->currentText() == "Median") controller->combineBias_ptr = &medianMask; else controller->combineBias_ptr = &meanMask; if (cdw->ui->darkMethodComboBox->currentText() == "Median") controller->combineDark_ptr = &medianMask; else controller->combineDark_ptr = &meanMask; if (cdw->ui->flatoffMethodComboBox->currentText() == "Median") controller->combineFlatoff_ptr = &medianMask; else controller->combineFlatoff_ptr = &meanMask; if (cdw->ui->flatMethodComboBox->currentText() == "Median") controller->combineFlat_ptr = &medianMask; else controller->combineFlat_ptr = &meanMask; if (cdw->ui->BACmethodComboBox->currentText() == "Median") controller->combineBackground_ptr = &medianMask; else controller->combineBackground_ptr = &meanMask; } // currently not in use /* bool MainWindow::maybeSave() { const QMessageBox::StandardButton ret = QMessageBox::question(this, tr("Application"), tr("Reduced enough data ?"), QMessageBox::Ok | QMessageBox::Cancel); switch (ret) { case QMessageBox::Ok: return true; case QMessageBox::Cancel: return false; default: break; } return true; } */ void MainWindow::initGUI() { QFile file(":/qss/default.qss"); file.open(QFile::ReadOnly); QString styleSheet = QString::fromLatin1(file.readAll()); qApp->setStyleSheet(styleSheet); QIcon key(":/icons/key.png"); QIcon redoarrow(":/icons/redoarrow.png"); QIcon projectLoad(":/icons/open_project.png"); QIcon projectReset(":/icons/db-restart-icon.png"); QIcon projectDataReset(":/icons/db-reset.png"); // configuration dialog ui->HDUreformatConfigureToolButton->setIcon(key); ui->calibratorConfigureToolButton->setIcon(key); ui->BACconfigureToolButton->setIcon(key); ui->chopnodConfigureToolButton->setIcon(key); ui->COCconfigureToolButton->setIcon(key); ui->binnedPreviewConfigureToolButton->setIcon(key); ui->globalweightConfigureToolButton->setIcon(key); ui->individualweightConfigureToolButton->setIcon(key); ui->separateConfigureToolButton->setIcon(key); ui->absphotomindirectConfigureToolButton->setIcon(key); ui->absphotomdirectConfigureToolButton->setIcon(key); ui->astromphotomConfigureToolButton->setIcon(key); ui->createsourcecatConfigureToolButton->setIcon(key); ui->skysubConfigureToolButton->setIcon(key); ui->coadditionConfigureToolButton->setIcon(key); ui->setupProjectLoadToolButton->setIcon(projectLoad); ui->setupProjectResetToolButton->setIcon(projectReset); ui->setupProjectResetDataToolButton->setIcon(projectDataReset); this->setWindowTitle("THELI "+GUIVERSION+" Project: "+ui->setupProjectLineEdit->text()); // Check the status of currently selected tasks (if any; simulator mode) // and push a suitable message to plainTextedit on_startPushButton_clicked(); // Mandatory checkboxes have yellow background // Don't know the parameter referring to the background color of the checkbox marker alone /* QList mandatoryCheckboxList; mandatoryCheckboxList.append(ui->applyHDUreformatCheckBox); mandatoryCheckboxList.append(ui->applyGlobalweightCheckBox); mandatoryCheckboxList.append(ui->applyIndividualweightCheckBox); mandatoryCheckboxList.append(ui->applyCreatesourcecatCheckBox); mandatoryCheckboxList.append(ui->applyAstromphotomCheckBox); mandatoryCheckboxList.append(ui->applyCoadditionCheckBox); for (auto &it : mandatoryCheckboxList) { it->setStyleSheet("base: #fff669;"); } */ QIcon yield(":/icons/Signal-yield-icon.png"); QIcon stop(":/icons/Actions-process-stop-icon.png"); ui->yieldToolButton->setIcon(yield); ui->stopToolButton->setIcon(stop); } void MainWindow::establish_connections() { // Other, 'singular' connectors // Data dirs for (auto &it : status.listDataDirs) { // LineEdits adjust their background color connect(it, &QLineEdit::textChanged, this, &MainWindow::repaintDataDirs); // LineEdits editing finished must update GUI settings connect(it, &QLineEdit::editingFinished, this, &MainWindow::writeGUISettings); } // TODO: move to confdockwidget // connect(ui->ARCselectimageLineEdit, &QLineEdit::textChanged, this, &MainWindow::repaintDataDirs); // Close the main GUI connect(ui->actionClose, &QAction::triggered, this, &MainWindow::shutDown); // Connect configureToolButtons with the confStackedWidget for (auto &it : status.listToolButtons) { connect(it, &QToolButton::clicked, this, &MainWindow::link_ConfToolButtons_confStackedWidget); } // Connect task checkboxes (load corresponding config page, and run simulator mode) for (auto &it : status.listCheckBox) { connect(it, &QCheckBox::clicked, this, &MainWindow::link_taskCheckBoxes_confStackedWidget); connect(it, &QCheckBox::clicked, this, &MainWindow::on_startPushButton_clicked); } // Connect actions connect(ui->actionPreferences, &QAction::triggered, this, &MainWindow::loadPreferences); connect(ui->actionAbsZP, &QAction::triggered, this, &MainWindow::load_dialog_abszeropoint); connect(ui->actioniView, &QAction::triggered, this, &MainWindow::loadIView); connect(ui->actionNew_instrument, &QAction::triggered, this, &MainWindow::load_dialog_newinst); connect(ui->actionColor_picture, &QAction::triggered, this, &MainWindow::load_dialog_colorpicture); connect(ui->actionImage_statistics, &QAction::triggered, this, &MainWindow::load_dialog_imageStatistics); // Connect validators connect_validators(); connect(ui->setupProjectResetToolButton, &QPushButton::clicked, this, &MainWindow::resetParameters); connect(ui->setupProjectResetDataToolButton, &QPushButton::clicked, this, &MainWindow::restoreOriginalData); } void MainWindow::cdw_dockLocationChanged(const Qt::DockWidgetArea &area) { if (cdw->isFloating()) this->adjustSize(); } void MainWindow::cdw_topLevelChanged(bool topLevel) { // Minimum size for the MainWindow after DockWidget goes floating if (topLevel) this->adjustSize(); } void MainWindow::updateDiskspaceWarning(int newLimit) { diskwarnPreference = newLimit; datadiskspace_warned = false; } void MainWindow::updateNumcpu(int cpu) { numCPU = cpu; } void MainWindow::link_ConfToolButtons_confStackedWidget() { QObject* obj = sender(); cdw->raise(); if (obj == ui->HDUreformatConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->calibratorConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->chopnodConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(1); else if (obj == ui->BACconfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(1); else if (obj == ui->COCconfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(2); else if (obj == ui->binnedPreviewConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(2); else if (obj == ui->globalweightConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(3); else if (obj == ui->individualweightConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(3); else if (obj == ui->separateConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(3); else if (obj == ui->absphotomindirectConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(4); else if (obj == ui->absphotomdirectConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(5); else if (obj == ui->createsourcecatConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(5); else if (obj == ui->astromphotomConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(6); else if (obj == ui->skysubConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(7); else if (obj == ui->coadditionConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(8); } void MainWindow::link_taskCheckBoxes_confStackedWidget() { QObject* obj = sender(); if (obj == ui->applyHDUreformatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->applyProcessbiasCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->applyProcessdarkCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->applyProcessflatoffCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->applyProcessflatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->applyProcessscienceCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0); else if (obj == ui->applyChopnodCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(1); else if (obj == ui->applyBackgroundCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(1); else if (obj == ui->applyCollapseCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(2); else if (obj == ui->applyBinnedpreviewCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(2); else if (obj == ui->applyGlobalweightCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(3); else if (obj == ui->applyIndividualweightCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(3); else if (obj == ui->applySeparateCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(3); else if (obj == ui->applyAbsphotindirectCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(4); else if (obj == ui->applyStarflatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(5); else if (obj == ui->applyCreatesourcecatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(5); else if (obj == ui->applyAstromphotomCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(6); else if (obj == ui->applySkysubCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(7); else if (obj == ui->applyCoadditionCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(8); // Show the configuration tab (in case e.g. currently the monitor is displayed) cdw->raise(); } void MainWindow::checkPaths() { // Cast sender to LineEdit because we know it's a LineEdit. // Then we have access to its content. QLineEdit* lineedit = qobject_cast(sender()); checkPathsLineEdit(lineedit); } bool MainWindow::checkPathsLineEdit(QLineEdit *lineEdit) { // Checks whether the entries in this lineEdit exist as directories. // The return value is ignored in some cases. // Turn the lineEdit to a stringList QStringList list = datadir2StringList(lineEdit); QString dirname = lineEdit->text(); // The following does not make much sense if we have multiple entries in a LineEdit. // But we catch that with the following two ifs QDir dir = QDir(dirname); // Process path fields if // -- unrelated to the data tree // -- the main data dir itself = QFile( // -- they are absolute paths // -- baddir string is empty if (lineEdit == cdw->ui->ARCselectimageLineEdit) { paintPathLineEdit(lineEdit, dirname, "file"); return true; } if (lineEdit == ui->setupMainLineEdit) { if (dir.isAbsolute()) { paintPathLineEdit(lineEdit, dirname); return true; } else { QPalette palette; palette.setColor(QPalette::Base,QColor("#ff99aa")); lineEdit->setPalette(palette); return false; } } if (dir.isAbsolute() || dirname.isEmpty()) { paintPathLineEdit(lineEdit, dirname); return true; } // Process the remaining data paths (BIAS, FLAT etc.), all relative. QString baddir_summary = ""; QString main = ui->setupMainLineEdit->text(); // Loop over the directories and check whether they are good or bad. // If a bad one is found, we paint the background red after the loop, otherwise green. for (int i=0; isetupMainLineEdit) { // Check subdirs as well for ( auto &it : status.listDataDirs) { test = checkPathsLineEdit(it); // Simulate a run if maindir exists (to repaint the command lists) if (test && sender() !=0 && it == ui->setupMainLineEdit) { on_startPushButton_clicked(); } } } else { QLineEdit* lineEdit = qobject_cast(sender()); if (lineEdit != 0) { test = checkPathsLineEdit(lineEdit); if (test) on_startPushButton_clicked(); } else { emit messageAvailable("MainWindow::repaintDataDirs(): bad LineEdit", "warning"); emit warning(); } } } // invoked when changing the instrument category in the preference dialog void MainWindow::linkPrefInst_with_MainInst(int index) { instrumentPreference = index; fill_setupInstrumentComboBox(); } // invoked when reading a project requires a change of category in the preference dialog // (the inst combobox is populated correctly already) void MainWindow::updatePreferences() { QSettings settings("THELI", "PREFERENCES"); settings.setValue("setupProjectLineEdit", ui->setupProjectLineEdit->text()); settings.sync(); if (settings.status() != QSettings::NoError) { emit messageAvailable("MainWindow::updatePreferences(): Failed updating the instrument category preference. Settings status = " + settings.status(), "error"); emit warning(); } } void MainWindow::updateFontSize(int index) { QFont currentFont = this->font(); currentFont.setPointSize(index); this->setFont(currentFont); } void MainWindow::updateFont(QFont font) { this->setFont(font); } void MainWindow::resetInstrumentData() { instData.numChips = 1; instData.numUsedChips = 1; instData.name = ""; instData.shortName = ""; instData.nameFullPath = ""; instData.obslat = 0.; instData.obslon = 0.; instData.bayer = ""; instData.flip = ""; instData.type = "OPT"; instData.pixscale = 1.0; // in arcsec // instData.gain = 1.0; instData.radius = 0.1; // exposure coverage radius in degrees instData.storage = 0; // MB used for a single image instData.storageExposure = 0.; // MB used for the entire (multi-chip) exposure instData.overscan_xmin.clear(); instData.overscan_xmax.clear(); instData.overscan_ymin.clear(); instData.overscan_ymax.clear(); instData.cutx.clear(); instData.cuty.clear(); instData.sizex.clear(); instData.sizey.clear(); instData.crpix1.clear(); instData.crpix2.clear(); } void MainWindow::initInstrumentData(QString instrumentNameFullPath) { resetInstrumentData(); QFile instDataFile(instrumentNameFullPath); instDataFile.setFileName(instrumentNameFullPath); instData.nameFullPath = instrumentNameFullPath; // read the instrument specific data if( !instDataFile.open(QIODevice::ReadOnly)) { emit messageAvailable("MainWindow::initInstrumentData(): "+instrumentNameFullPath+" "+instDataFile.errorString(), "error"); emit warning(); // to raise the monitor return; } instData.flip = ""; bool bayerFound = false; QTextStream in(&(instDataFile)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty() || line.contains("#")) continue; // scalars if (line.contains("INSTRUMENT=")) instData.name = line.split("=")[1]; if (line.contains("INSTSHORT=")) instData.shortName = line.split("=")[1]; if (line.contains("NCHIPS=")) instData.numChips = line.split("=")[1].toInt(); if (line.contains("TYPE=")) instData.type = line.split("=")[1]; if (line.contains("BAYER=")) { // BAYER is not mandatory; if not found, we must set it to blank instData.bayer = line.split("=")[1]; bayerFound = true; } if (line.contains("OBSLAT=")) instData.obslat = line.split("=")[1].toFloat(); if (line.contains("OBSLONG=")) instData.obslon = line.split("=")[1].toFloat(); if (line.contains("PIXSCALE=")) instData.pixscale = line.split("=")[1].toFloat(); // if (line.contains("GAIN=")) instData.gain = line.split("=")[1].toFloat(); QString tmp = ""; if (line.contains("FLIP=")) { tmp = line.split("=")[1]; if (tmp == "NOFLIP") instData.flip = ""; else instData.flip = tmp; } // vectors if (line.contains("OVSCANX1=") || line.contains("OVSCANX2=") || line.contains("OVSCANY1=") || line.contains("OVSCANY2=") || line.contains("CUTX=") || line.contains("CUTY=") || line.contains("SIZEX=") || line.contains("SIZEY=") || line.contains("REFPIXX=") || line.contains("REFPIXY=")) { line = line.replace('=',' ').replace(')',' ').replace(')',""); line = line.simplified(); QStringList values = line.split(" "); QVector vecData; // NOTE: already subtracting -1 to make it conform with C++ indexing // (apart from SIZEX/Y, which is the actual number of pixels per axis and not a coordinate) for (int i=2; i> Tmatrices; for (int chip=0; chip tm = {1,0,0,1}; Tmatrices << tm; } getBinnedSize(&instData, Tmatrices, nGlobal, mGlobal, binFactor, xminOffset, yminOffset); // used to retrieve nglobal and mglobal instData.nGlobal = nGlobal; instData.mGlobal = mGlobal; instData.radius = 0.5 * sqrt(nGlobal*nGlobal + mGlobal*mGlobal)*instData.pixscale / 3600.; // in degrees // Lastly, how many MB does a single detector occupy instData.storage = instData.sizex[0]*instData.sizey[0]*sizeof(float) / 1024. / 1024.; instData.storageExposure = instData.storage * instData.numChips; // Always use full storage. This is computed before user may change number of used chips updateExcludedDetectors(cdw->ui->excludeDetectorsLineEdit->text()); } void MainWindow::testOverscan(QVector &overscan) { if (overscan.isEmpty()) return; // if the overscan is consistently -1, then the vector must be empty bool flag = true; for (auto &it : overscan) { if (it != -1) { flag = false; break; } } if (flag) overscan.clear(); } void MainWindow::fill_setupInstrumentComboBox() { // UNCOMMENT to see how the GUI is initialized // qDebug() << "fill_setupInstrumentComboBox"; QStringList instDirList; instDirList << thelidir+"/config/instruments/" << QDir::homePath()+"/.theli/instruments_user/"; // Loop over pre-defined and user-defined instruments instrument_model = new MyStringListModel; QStringList allInstrumentList; for (auto &instDirName : instDirList) { QDir instDir = QDir(instDirName); QStringList filter("*.ini"); instDir.setNameFilters(filter); instDir.setSorting(QDir::Name); QStringList currentInstrumentList = instDir.entryList(); if (currentInstrumentList.isEmpty()) continue; currentInstrumentList.replaceInStrings(".ini",""); allInstrumentList.append(currentInstrumentList); // instrument_model only used here, but it needs to exist throughpout the lifetime of the GUI. if (instDirName.contains("instruments_user")) instrument_model->instrument_userDir = instDirName; else instrument_model->instrument_dir = instDirName; } if (allInstrumentList.isEmpty()) { QMessageBox::critical(this, tr("THELI"), tr("No instrument configurations were found in /usr/share/theli/config/! Did you set the THELIDIR environment variable correctly?\n") +tr("If you are not using a system wide installation, then THELIDIR should point to the installation directory (where you find the src/ sub-directory)."), QMessageBox::Ok); return; } // allInstrumentList.sort(); instrument_model->setStringList(allInstrumentList); // CAREFUL! the following line also triggers // on_setupInstrumentComboBox_clicked() // and repaintDataDirs() (why??) ui->setupInstrumentComboBox->setModel(instrument_model); ui->setupInstrumentComboBox->setCurrentIndex(0); // We always do a software click as well. Unnecessary? // on_setupInstrumentComboBox_clicked(); // Override user's desktop preferences, to avoid a ComboBox to fill the entire screen // from top to bottom. Only show 20 items max (designer setting, but needs to be activated here) ui->setupInstrumentComboBox->setStyleSheet("combobox-popup: 0;"); } void MainWindow::updateInstrumentComboBoxBackgroundColor() { QPalette palette; if (instrument_type == "OPT") palette.setColor(QPalette::Button,QColor("#40acff")); else if (instrument_type == "NIR") palette.setColor(QPalette::Button,QColor("#70ffd4")); else if (instrument_type == "NIRMIR") palette.setColor(QPalette::Button,QColor("#ffe167")); else if (instrument_type == "MIR") palette.setColor(QPalette::Button,QColor("#ff616b")); else palette.setColor(QPalette::Button,QColor("#40acff")); // backwards compatibility; if undefined, use optical color ui->setupInstrumentComboBox->setPalette(palette); } void MainWindow::toggleButtonsWhileRunning() { if (!ui->startPushButton->isEnabled()) { ui->setupInstrumentComboBox->setDisabled(true); ui->setupProjectLineEdit->setDisabled(true); ui->setupProjectLoadToolButton->setDisabled(true); ui->setupProjectResetToolButton->setDisabled(true); ui->setupProjectResetDataToolButton->setDisabled(true); cdw->ui->ARCgetcatalogPushButton->setDisabled(true); cdw->ui->restoreHeaderPushButton->setDisabled(true); } else { ui->setupInstrumentComboBox->setEnabled(true); ui->setupProjectLineEdit->setEnabled(true); ui->setupProjectLoadToolButton->setEnabled(true); ui->setupProjectResetToolButton->setEnabled(true); ui->setupProjectResetDataToolButton->setEnabled(true); cdw->ui->ARCgetcatalogPushButton->setEnabled(true); cdw->ui->restoreHeaderPushButton->setEnabled(true); } } QString MainWindow::getInstDir(QString instname) { instrument_name = ui->setupInstrumentComboBox->currentText(); QFile file; file.setFileName(instrument_dir+instname); if (file.exists()) return instrument_dir; else { file.setFileName(instrument_userDir+instname); if (file.exists()) return instrument_userDir; else { emit messageAvailable("Could not find instrument "+ instname +" config file in either of", "error"); emit messageAvailable(instrument_dir, "error"); emit messageAvailable(instrument_userDir, "error"); emit warning(); } } return ""; } void MainWindow::checkMemoryConstraints() { // systemRAM is in kB; if (instData.storageExposure >= systemRAM / 1024.) { QMessageBox::warning( this, "Low physical RAM detected", "A single "+instData.name + " exposure occupies " + QString::number(long(instData.storageExposure)) + " MB in memory.\n" + "Your machine has only "+QString::number(long(systemRAM/1024)) + " MB installed. " + "Processing might be fine, but performance will be significantly reduced."); } } void MainWindow::on_setupInstrumentComboBox_clicked() { // Read some instrument parameters and the file path instrument_name = ui->setupInstrumentComboBox->currentText(); if (instrument_name.isEmpty()) return; // can happen if e.g. there are no user-defined instruments QString matchingInstDir = getInstDir(instrument_name+".ini"); instrument_file.setFileName(matchingInstDir+instrument_name+".ini"); instrument_bayer = get_fileparameter(&instrument_file, "BAYER"); instrument_type = get_fileparameter(&instrument_file, "TYPE"); instrument_nchips = get_fileparameter(&instrument_file, "NCHIPS").toInt(); // Pass on to ConfDockWidget cdw->instrument_dir = matchingInstDir; cdw->instrument_name = instrument_name; cdw->instrument_type = instrument_type; cdw->instrument_bayer = instrument_bayer; // UNUSED? cdw->instrument_nchips = instrument_nchips; cdw->instrument_file.setFileName(matchingInstDir+instrument_name+".ini"); // The structure holding the content of the instrument file initInstrumentData(matchingInstDir+instrument_name+".ini"); updateInstrumentComboBoxBackgroundColor(); if (!readingSettings) { // TODO: rather, look into the image headers and calculate the most likely pixel scale (dropping into 1x1 or 2x2 binning mode) cdw->ui->COApixscaleLineEdit->setText(get_fileparameter(&instrument_file, "PIXSCALE")); if (instData.pixscale < 0.1) cdw->ui->ASTcrossidLineEdit->setText(QString::number(10.*instData.pixscale, 'f', 2)); else if (instData.pixscale < 0.5) cdw->ui->ASTcrossidLineEdit->setText(QString::number(5.*instData.pixscale, 'f', 1)); else cdw->ui->ASTcrossidLineEdit->setText(QString::number(int(5.*instData.pixscale))); } if (instrument_type == "MIR") { // UNCOMMENT to see how the GUI is initialized // qDebug() << "U0 - MIR setup"; ui->applyChopnodCheckBox->show(); ui->chopnodConfigureToolButton->show(); ui->applyBackgroundCheckBox->hide(); ui->BACconfigureToolButton->hide(); cdw->ui->overscanCheckBox->setDisabled(true); cdw->ui->overscanMethodComboBox->setDisabled(true); } else if (instrument_type == "NIR") { // UNCOMMENT to see how the GUI is initialized // qDebug() << "U0 - NIR setup"; ui->applyChopnodCheckBox->hide(); ui->chopnodConfigureToolButton->hide(); ui->applyBackgroundCheckBox->show(); ui->BACconfigureToolButton->show(); cdw->ui->overscanCheckBox->setDisabled(true); cdw->ui->overscanMethodComboBox->setDisabled(true); } else if (instrument_type == "NIRMIR") { // UNCOMMENT to see how the GUI is initialized // qDebug() << "U0 - NIRMIR setup"; ui->applyChopnodCheckBox->show(); ui->chopnodConfigureToolButton->show(); ui->applyBackgroundCheckBox->show(); ui->BACconfigureToolButton->show(); cdw->ui->overscanCheckBox->setDisabled(true); cdw->ui->overscanMethodComboBox->setDisabled(true); } else if (instrument_type == "OPT" || instrument_type == "") { // UNCOMMENT to see how the GUI is initialized // qDebug() << "U0 - OPT setup"; ui->applyChopnodCheckBox->hide(); ui->chopnodConfigureToolButton->hide(); ui->applyBackgroundCheckBox->show(); ui->BACconfigureToolButton->show(); cdw->ui->overscanCheckBox->setEnabled(true); cdw->ui->overscanMethodComboBox->setEnabled(true); if (cdw->ui->saturationLineEdit->text().isEmpty()) cdw->ui->saturationLineEdit->setText("65535"); } cdw->ui->BIPSpinBox->setValue(estimateBinningFactor()); // Update settings writeGUISettings(); checkMemoryConstraints(); } void MainWindow::scienceDataDirUpdatedReceived(QString allDirs) { ui->setupScienceLineEdit->setText(allDirs); emit rereadScienceDataDir(); } void MainWindow::progressUpdateReceived(float progressReceived) { controller->progress = progressReceived; ui->processProgressBar->setValue(int(progressReceived)); } bool MainWindow::sufficientSpaceAvailable(long spaceNeeded) { QString unitsNeeded = " MB"; QString unitsFree = " MB"; long spaceFree = remainingDataDriveSpace(ui->setupMainLineEdit->text()); // in MBytes QString spaceNeededString = QString::number(spaceNeeded) + unitsNeeded; QString spaceFreeString = QString::number(spaceFree) + unitsFree; // Unit conversions if (spaceNeeded > 1024.) { float spaceNeededFloat = spaceNeeded / 1024.; unitsNeeded = " GB"; spaceNeededString = QString::number(spaceNeededFloat, 'f', 1) + unitsNeeded; } if (spaceFree > 1024.) { float spaceFreeFloat = spaceFree / 1024.; unitsFree = " GB"; spaceFreeString = QString::number(spaceFreeFloat, 'f', 1) + unitsFree; } if (spaceNeeded > spaceFree) { QMessageBox::warning( this, tr("Insufficient space on drive"), tr("The current operation needs to write ") + spaceNeededString + tr(" to drive, however only") + spaceFreeString + tr(" are available on ")+ui->setupMainLineEdit->text()); return false; } return true; } void MainWindow::on_setupProjectLoadToolButton_clicked() { // First of all, check if we have unsaved images in memory long numUnsavedImagesLatestStage = 0; long numUnsavedImagesBackup = 0; controller->checkForUnsavedImages(numUnsavedImagesLatestStage, numUnsavedImagesBackup); if (numUnsavedImagesLatestStage > 0 || numUnsavedImagesBackup > 0) { long mBytesLatest = numUnsavedImagesLatestStage*instData.storage; long mBytesBackup = numUnsavedImagesBackup*instData.storage; long mBytesAll = mBytesLatest + mBytesBackup; QString saveLatestString = ""; QString saveAllString = ""; if (numUnsavedImagesLatestStage > 0) saveLatestString = "The current project keeps "+QString::number(numUnsavedImagesLatestStage) + " unsaved images of the latest processing stage in memory.\n"; if (numUnsavedImagesBackup > 0) saveAllString = "The current project keeps "+QString::number(numUnsavedImagesBackup) + " unsaved images with earlier processing stages in memory.\n"; QMessageBox msgBox; msgBox.setModal(true); msgBox.setInformativeText(tr("A new project is about to be loaded.\n") + saveLatestString + saveAllString + "\n"); QAbstractButton *pButtonSaveLatest = msgBox.addButton(tr("Save latest images (")+QString::number(mBytesLatest)+" MB) and close", QMessageBox::YesRole); QAbstractButton *pButtonSaveAll = msgBox.addButton(tr("Save all images (")+QString::number(mBytesAll)+" MB) and close", QMessageBox::YesRole); QAbstractButton *pButtonContinue = msgBox.addButton(tr("Close without saving"), QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); if (numUnsavedImagesLatestStage == 0) pButtonSaveLatest->hide(); if (numUnsavedImagesBackup == 0) pButtonSaveAll->hide(); msgBox.exec(); if (msgBox.clickedButton() == pButtonSaveLatest) { if (sufficientSpaceAvailable(mBytesLatest)) { // sufficientSpaceAvailable() displays a warning message controller->writeUnsavedImagesToDrive(false); } else return; } else if (msgBox.clickedButton() == pButtonSaveAll) { if (sufficientSpaceAvailable(mBytesAll)) { controller->writeUnsavedImagesToDrive(true); } else return; } else if (msgBox.clickedButton() == pButtonContinue) { // see below } else if (msgBox.clickedButton() == pButtonCancel) { return; } } QString projectname; if (kernelType == "linux") { projectname = QFileDialog::getOpenFileName(this, tr("Select THELI Project"), QDir::homePath()+"/.config/THELI/", tr("THELI projects (*.conf)")); } else { // kernelType == "darwin" projectname = QFileDialog::getOpenFileName(this, tr("Select THELI Project"), QDir::homePath()+"/Library/Preferences/THELI/", tr("THELI projects (*.plist)")); } // Truncate the suffix (OS dependent; Linux: .conf; MacOS Mojave: com.theli..plist) QFileInfo projectFileInfo(projectname); QString projectBaseName = projectFileInfo.completeBaseName(); if (kernelType == "darwin") projectBaseName.remove("com.theli."); if ( projectBaseName.isEmpty() ) { return; } // Before wiping the data tree, we must switch away from the memory view (if currently raised). // Even though we display an empty model, it still tries to access the old ones, even though everything should be protected. // So, we just switch to the config view and then back (until I sorted this out) bool viewSwitched = false; if (memoryViewer->isVisible()) { cdw->raise(); viewSwitched = true; } monitor->displayMessage("Freeing memory ...", "ignore"); controller->wipeDataTree(); // Now load the new GUI settings ui->setupProjectLineEdit->setText(projectBaseName); int settingsStatus = readGUISettings(projectBaseName); if (settingsStatus == 0) { // everything is OK } else if (settingsStatus == 1) { QMessageBox::warning( this, "THELI: Access error", "An access error occurred while reading the configuration file for project '"+projectBaseName+"'!\n"); } else if (settingsStatus == 2) { QMessageBox::warning( this, "THELI: Format error", "A format error occurred while reading the configuration file for project '"+projectBaseName+"'!\n"); } // Could also directly call controller->newProjectLoadedReceived() instead emit newProjectLoaded(); // Show memory view again (if it was hidden before) if (viewSwitched) memoryViewer->raise(); } void MainWindow::loadPreferences() { // send instrument name and project name (why?) updatePreferences(); // would have to set combobox, because the dialog exists already bool taskRunning; if (ui->startPushButton->isEnabled()) taskRunning = false; else taskRunning = true; preferences = new Preferences(taskRunning, this); connect(preferences, &Preferences::instPreferenceChanged, this, &MainWindow::linkPrefInst_with_MainInst); connect(preferences, &Preferences::fontSizeChanged, this, &MainWindow::updateFontSize); connect(preferences, &Preferences::fontChanged, this, &MainWindow::updateFont); connect(preferences, &Preferences::diskspacewarnChanged, this, &MainWindow::updateDiskspaceWarning); connect(preferences, &Preferences::numcpuChanged, this, &MainWindow::updateNumcpu); connect(preferences, &Preferences::memoryUsageChanged, controller, &Controller::updateMemoryPreference); connect(preferences, &Preferences::switchProcessMonitorChanged, this, &MainWindow::updateSwitchProcessMonitorPreference); connect(preferences, &Preferences::intermediateDataChanged, controller, &Controller::updateIntermediateDataPreference); connect(preferences, &Preferences::verbosityLevelChanged, controller, &Controller::updateVerbosity); connect(preferences, &Preferences::preferencesUpdated, controller, &Controller::loadPreferences); connect(preferences, &Preferences::warning, monitor, &Monitor::raise); connect(preferences, &Preferences::messageAvailable, monitor, &Monitor::displayMessage); connect(this, &MainWindow::runningStatusChanged, preferences, &Preferences::updateParallelization); connect(this, &MainWindow::sendingDefaultFont, preferences, &Preferences::receiveDefaultFont); QFont defaultFont = this->font(); emit sendingDefaultFont(defaultFont); // to preferences preferences->show(); } void MainWindow::updateSwitchProcessMonitorPreference(bool switchToMonitor) { switchProcessMonitorPreference = switchToMonitor; } void MainWindow::statusChangedReceived(QString newStatus) { status.statusstringToHistory(newStatus); } void MainWindow::updateExcludedDetectors(QString badDetectors) { if (doingInitialLaunch && readingSettings) return; if (controller) controller->successProcessing = true; // function called at launch when controller does not yet exist instData.badChips.clear(); QStringList chipStringList = badDetectors.replace(","," ").simplified().split(" "); if (!badDetectors.isEmpty()) { for (auto &chip : chipStringList) instData.badChips.append(chip.toInt()-1); } instData.numUsedChips = instData.numChips - instData.badChips.length(); instData.goodChips.clear(); for (int chip=0; chipsuccessProcessing = false; QMessageBox::critical(this, tr("THELI"), tr("No valid detectors remain after filtering bad detectors. Review the list of user-defined unusable detectors."), QMessageBox::Ok); } else { instData.validChip = instData.goodChips[0]; } // Map the chip numbers to the number in which they appear in order (e.g. in .scamp catalogs) int countGoodChip = 0; for (int chip=0; chipshow(); } void MainWindow::loadCoaddAbsZP(QString coaddImage, float maxVal) { AbsZeroPoint *abszeropoint = new AbsZeroPoint(coaddImage, this); abszeropoint->updateSaturationValue(maxVal); connect(abszeropoint, &AbsZeroPoint::abszpClosed, controller, &Controller::absZeroPointCloseReceived); abszeropoint->show(); } void MainWindow::load_dialog_imageStatistics() { QString mainDir = ui->setupMainLineEdit->text(); Data *scienceData = nullptr; if (controller->DT_SCIENCE.length() == 1) { scienceData = controller->DT_SCIENCE.at(0); } else if (controller->DT_SCIENCE.length() == 0) { QMessageBox::information(this, tr("Missing data"), tr("Image statistics:
No SCIENCE data were specified in the data tree.\n"), QMessageBox::Ok); return; } else { QMessageBox msgBox; msgBox.setInformativeText(tr("Image statistics: Choose SCIENCE data\n\n") + tr("The current SCIENCE data tree contains several entries. ") + tr("Select one for the statistics module:\n\n")); for (auto &data : controller->DT_SCIENCE) { msgBox.addButton(data->subDirName, QMessageBox::YesRole); } QAbstractButton *pCancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole); msgBox.exec(); QString choice = msgBox.clickedButton()->text().remove('&'); // remove & is a fix of unwanted KDE behaviour (KDE may insert '&' into button text) if (msgBox.clickedButton()== pCancel) return; for (auto &data : controller->DT_SCIENCE) { if (data->subDirName == choice) { scienceData = data; break; } } } ImageStatistics *imagestatistics = new ImageStatistics(controller->DT_SCIENCE, mainDir, scienceData->subDirName, &instData, this); // Inform image statistics when the user manually (de)activates an image. Must be connected here, as imagestatistics does not know about mainGUI connect(memoryViewer, &MemoryViewer::activationChanged, imagestatistics, &ImageStatistics::activationChangedReceiver); imagestatistics->show(); } void MainWindow::load_dialog_colorpicture() { ColorPicture *colorPicture = new ColorPicture(ui->setupMainLineEdit->text(), this); connect(colorPicture, &ColorPicture::showMessageBox, this, &MainWindow::showMessageBoxReceived); colorPicture->show(); } void MainWindow::load_dialog_newinst() { instrument->show(); } /* void MainWindow::loadIView() { QString main = ui->setupMainLineEdit->text(); QString science = ui->setupScienceLineEdit->text().split(" ").at(0); QString dirname = main+"/"+science; if (!QDir(dirname).exists()) dirname = QDir::homePath(); IView *iView = new IView("FITSmonochrome", dirname, "*.fits *.fit *.FITS *.FIT", this); iView->show(); } */ void MainWindow::loadIView() { QString main = ui->setupMainLineEdit->text(); QStringList scienceList = ui->setupScienceLineEdit->text().split(" "); QString dirName = ""; if (scienceList.length() == 1) dirName = main+"/"+scienceList.at(0); else { QMessageBox msgBox; msgBox.setInformativeText(tr("The current SCIENCE data tree contains several entries. ") + tr("Select one for which to display images:\n\n")); for (auto &name : scienceList) { msgBox.addButton(name, QMessageBox::YesRole); } QAbstractButton *pCancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole); msgBox.exec(); QString choice = msgBox.clickedButton()->text().remove('&'); // remove & is a KDE fix if (msgBox.clickedButton()== pCancel) return; for (auto &name : scienceList) { if (name == choice) { dirName = main + "/" + name; break; } } } if (!QDir(dirName).exists()) dirName = QDir::homePath(); IView *iView = new IView("FITSmonochrome", dirName, "*.fits", this); iView->show(); } // Used for displaying: // (*) binned mosaics void MainWindow::launchViewer(QString dirname, QString filter, QString mode) { // Load the FITS viewer IView *iView = new IView("FITSmonochrome", dirname, filter, this); connect(iView, &IView::closed, iView, &IView::deleteLater); iView->show(); iView->setMiddleMouseMode(mode); } /* void MainWindow::launchCoaddFluxcal(QString coaddImage) { AbsZeroPoint *abszeropoint = new AbsZeroPoint(coaddImage, &instData, this); abszeropoint->show(); } */ void MainWindow::resetParameters() { // First of all, check if we have unsaved images in memory long numUnsavedImagesLatestStage = 0; long numUnsavedImagesBackup = 0; controller->checkForUnsavedImages(numUnsavedImagesLatestStage, numUnsavedImagesBackup); if (numUnsavedImagesLatestStage > 0 || numUnsavedImagesBackup > 0) { long mBytesLatest = numUnsavedImagesLatestStage*instData.storage; long mBytesBackup = numUnsavedImagesBackup*instData.storage; long mBytesAll = mBytesLatest + mBytesBackup; QString saveLatestString = ""; QString saveAllString = ""; if (numUnsavedImagesLatestStage > 0) saveLatestString = "The current project keeps "+QString::number(numUnsavedImagesLatestStage) + " unsaved images of the latest processing stage in memory.\n"; if (numUnsavedImagesBackup > 0) saveAllString = "The current project keeps "+QString::number(numUnsavedImagesBackup) + " unsaved images with earlier processing stages in memory.\n"; QMessageBox msgBox; msgBox.setModal(true); msgBox.setInformativeText(tr("The parameters in the current project are about to be reset.\n") + saveLatestString + saveAllString + tr("\nAll processing parameters will be reset to their default values.") + tr(" Processing will continue with the FITS files currently found on your drive.") + tr(" Data currently kept in memory can be saved and thus included in reprocessing.\n\n")); QAbstractButton *pButtonSaveLatest = msgBox.addButton(tr("Save latest images (")+QString::number(mBytesLatest)+" MB) and close", QMessageBox::YesRole); QAbstractButton *pButtonSaveAll = msgBox.addButton(tr("Save all images (")+QString::number(mBytesAll)+" MB) and close", QMessageBox::YesRole); QAbstractButton *pButtonContinue = msgBox.addButton(tr("Close without saving"), QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); if (numUnsavedImagesLatestStage == 0) pButtonSaveLatest->hide(); if (numUnsavedImagesBackup == 0) pButtonSaveAll->hide(); msgBox.exec(); if (msgBox.clickedButton() == pButtonSaveLatest) { if (sufficientSpaceAvailable(mBytesLatest)) { // sufficientSpaceAvailable() displays a warning message controller->writeUnsavedImagesToDrive(false); } else return; } else if (msgBox.clickedButton() == pButtonSaveAll) { if (sufficientSpaceAvailable(mBytesAll)) { controller->writeUnsavedImagesToDrive(true); } else return; } else if (msgBox.clickedButton() == pButtonContinue) { // see below } else if (msgBox.clickedButton() == pButtonCancel) { return; } } else { QMessageBox msgBox; msgBox.setModal(true); msgBox.setInformativeText(tr("The parameters in the current project are about to be reset.\n") + tr(" All processing parameters will be reset to their default values. Processing will continue with the FITS files found on disk.\n")); QAbstractButton *pButtonOK = msgBox.addButton(tr("OK"), QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton() == pButtonCancel) return; else if (msgBox.clickedButton() == pButtonOK) { // see below } } // Purge all data from memory monitor->displayMessage("Freeing memory ...", "ignore"); controller->wipeDataTree(); // Reread data tree from disk monitor->displayMessage("Reading data structure from drive ...", "ignore"); controller->mapDataTree(); // Load defaults monitor->displayMessage("Restoring defaults ...", "ignore"); cdw->loadDefaults(); for (auto &it : status.listHistory) { it = false; } status.updateStatus(); writeGUISettings(); monitor->displayMessage("
*** DONE ***", "note"); } void MainWindow::populateTaskCommentMap() { taskCommentMap.clear(); taskCommentMap.insert("HDUreformat", "HDU reformatting"); taskCommentMap.insert("Processbias", "Processing biases in"); taskCommentMap.insert("Processdark", "Processing darks in"); taskCommentMap.insert("Processflatoff", "Processing flat off/darks in"); taskCommentMap.insert("Processflat", "Processing flats in"); taskCommentMap.insert("Processscience", "Debiasing and flatfielding data in"); taskCommentMap.insert("Chopnod", "Doing chopnod background correction for"); taskCommentMap.insert("Background", "Applying background model to"); taskCommentMap.insert("Collapse", "Applying collapse correction to"); taskCommentMap.insert("Binnedpreview", "Creating binned previews for"); taskCommentMap.insert("Globalweight", "Creating global weights for"); taskCommentMap.insert("Individualweight", "Creating individual weights for"); taskCommentMap.insert("Separate", "Separating different targes in"); taskCommentMap.insert("Absphotindirect", "Performing indirect absolute photometry"); taskCommentMap.insert("Createsourcecat", "Creating source catalogs for"); taskCommentMap.insert("Astromphotom", "Calculating astrometric solution for"); taskCommentMap.insert("Skysub", "Subtracting the sky for"); taskCommentMap.insert("Coaddition", "Performing coaddition for"); taskCommentMap.insert("GetCatalogFromWEB", "Downloading astrometric reference catalog for"); taskCommentMap.insert("GetCatalogFromIMAGE", "Extracting astrometric reference catalog for"); taskCommentMap.insert("Resolvetarget", "Resolving target coordinates for"); } void MainWindow::initProcessingStatus() { // Initialize the status' collective widget lists // the order is important!!! status.listCheckBox.append(ui->applyHDUreformatCheckBox); status.listCheckBox.append(ui->applyProcessbiasCheckBox); status.listCheckBox.append(ui->applyProcessdarkCheckBox); status.listCheckBox.append(ui->applyProcessflatoffCheckBox); status.listCheckBox.append(ui->applyProcessflatCheckBox); status.listCheckBox.append(ui->applyProcessscienceCheckBox); status.listCheckBox.append(ui->applyChopnodCheckBox); status.listCheckBox.append(ui->applyBackgroundCheckBox); status.listCheckBox.append(ui->applyCollapseCheckBox); status.listCheckBox.append(ui->applyBinnedpreviewCheckBox); status.listCheckBox.append(ui->applyGlobalweightCheckBox); status.listCheckBox.append(ui->applyIndividualweightCheckBox); status.listCheckBox.append(ui->applySeparateCheckBox); status.listCheckBox.append(ui->applyAbsphotindirectCheckBox); status.listCheckBox.append(ui->applyCreatesourcecatCheckBox); status.listCheckBox.append(ui->applyAstromphotomCheckBox); status.listCheckBox.append(ui->applyStarflatCheckBox); status.listCheckBox.append(ui->applySkysubCheckBox); status.listCheckBox.append(ui->applyCoadditionCheckBox); status.listToolButtons.append(ui->HDUreformatConfigureToolButton); status.listToolButtons.append(ui->calibratorConfigureToolButton); status.listToolButtons.append(ui->BACconfigureToolButton); status.listToolButtons.append(ui->chopnodConfigureToolButton); status.listToolButtons.append(ui->COCconfigureToolButton); status.listToolButtons.append(ui->binnedPreviewConfigureToolButton); status.listToolButtons.append(ui->globalweightConfigureToolButton); status.listToolButtons.append(ui->individualweightConfigureToolButton); status.listToolButtons.append(ui->separateConfigureToolButton); status.listToolButtons.append(ui->absphotomindirectConfigureToolButton); status.listToolButtons.append(ui->absphotomdirectConfigureToolButton); status.listToolButtons.append(ui->astromphotomConfigureToolButton); status.listToolButtons.append(ui->createsourcecatConfigureToolButton); status.listToolButtons.append(ui->skysubConfigureToolButton); status.listToolButtons.append(ui->coadditionConfigureToolButton); status.listDataDirs.append(ui->setupMainLineEdit); status.listDataDirs.append(ui->setupBiasLineEdit); status.listDataDirs.append(ui->setupDarkLineEdit); status.listDataDirs.append(ui->setupFlatoffLineEdit); status.listDataDirs.append(ui->setupFlatLineEdit); status.listDataDirs.append(ui->setupScienceLineEdit); status.listDataDirs.append(ui->setupSkyLineEdit); status.listDataDirs.append(ui->setupStandardLineEdit); // Populate the map that associates CheckBoxes and their texts // (so that we can lookup the CheckBox based on its string representation, // needed for some messages being sent to plainTextEdit when executing tasks. // Also, populate the index map; QString taskBasename; int i=0; for (auto &it: status.listCheckBox) { taskBasename = it->objectName().remove("apply").remove("CheckBox"); checkboxMap.insert(it, taskBasename); status.indexMap.insert(taskBasename, i); ++i; } // List name contains the taskBasename; // The Boolean list goes to false, // the value list to empy strings QString name; for (int i=0; iobjectName(); name.remove("apply"); name.remove("CheckBox"); status.listName << name; status.listHistory << false; status.listCurrentValue << " "; status.listFixedValue << " "; // just to create a QList with 'numtasks' elements } for (int i=0; ishow(); } void MainWindow::on_setupInstrumentComboBox_currentTextChanged(const QString &arg1) { // UNCOMMENT to see how the GUI is built up // qDebug() << "on_setupInstrumentComboBox_currentTextChanged()"; on_setupInstrumentComboBox_clicked(); } void MainWindow::on_processingTabWidget_currentChanged(int index) { if (index == 0 || index == 1) { cdw->ui->confStackedWidget->setCurrentIndex(0); cdw->ui->confBackwardPushButton->setDisabled(true); } // else if (index == 2) { // cdw->ui->confStackedWidget->setCurrentIndex(1); // cdw->ui->confBackwardPushButton->setEnabled(true); // } else { cdw->ui->confStackedWidget->setCurrentIndex(3); cdw->ui->confBackwardPushButton->setEnabled(true); // Fill the coadd filter combobox with values } writeGUISettings(); update(); } void MainWindow::shutDown() { this->close(); } void MainWindow::on_actionAdd_new_instrument_configuration_triggered() { load_dialog_newinst(); } void MainWindow::on_actionEdit_preferences_triggered() { loadPreferences(); } void MainWindow::restoreOriginalData() { bool accept = true; const QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Full data reset"), tr("WARNING: You are about to restore all raw data.\n\n") + tr("All processed data, both in memory and on drive, will be lost!\n"), QMessageBox::Ok | QMessageBox::Cancel); switch (ret) { case QMessageBox::Ok: accept = accept && true; break; case QMessageBox::Cancel: accept = accept && false; break; default: break; } if (!accept) return; QString newStatus = ""; status.statusstringToHistory(newStatus); // Reset status for (auto &it : status.listHistory) { it = false; } status.updateStatus(); // Restore data monitor->displayMessage("Freeing memory, restoring raw data ...", "ignore"); controller->restoreAllRawData(); memoryViewer->projectResetReceived(); // Switch to first processing tab page ui->processingTabWidget->setCurrentIndex(1); } void MainWindow::on_actionLicense_triggered() { license = new License(this); license->show(); } void MainWindow::on_actionAcknowledging_triggered() { acknowledging = new Acknowledging(this); acknowledging->show(); } void MainWindow::on_actionDocumentation_triggered() { tutorials = new Tutorials(this); tutorials->show(); } int MainWindow::estimateBinningFactor() { QScreen *screen = QGuiApplication::primaryScreen(); int x = screen->availableSize().width() - 240; // subtracting margins for the iview UI int y = screen->availableSize().height() - 120; int binFactorX = instData.nGlobal / x + 1; int binFactorY = instData.mGlobal / y + 1; int binFactor = binFactorX > binFactorY ? binFactorX : binFactorY; if (binFactor < 1) binFactor = 1; return binFactor; } void MainWindow::updateMemoryProgressBarReceived(long memoryUsed) { QString memoryString = QString::number(long(memoryUsed)) + " MB"; memoryProgressBar->setFormat("RAM: %p% ("+memoryString+")"); memoryProgressBar->setValue(memoryUsed); } void MainWindow::on_setupProjectLineEdit_textChanged(const QString &arg1) { this->setWindowTitle("THELI "+GUIVERSION+" Project: "+arg1); } // Used e.g. when user starts the very first time and nothing has been defined yet void MainWindow::setHomeDir() { if (ui->setupBiasLineEdit->text().isEmpty() && ui->setupDarkLineEdit->text().isEmpty() && ui->setupFlatoffLineEdit->text().isEmpty() && ui->setupFlatLineEdit->text().isEmpty() && ui->setupScienceLineEdit->text().isEmpty() && ui->setupSkyLineEdit->text().isEmpty() && ui->setupStandardLineEdit->text().isEmpty() && ui->setupMainLineEdit->text().isEmpty()) ui->setupMainLineEdit->setText(QDir::homePath()); } THELI-3.1.3/src/mainwindow.h000066400000000000000000000363701417631501300155110ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "readmes/multidirreadme.h" #include "readmes/license.h" #include "readmes/acknowledging.h" #include "readmes/tutorials.h" #include "abszp/abszeropoint.h" #include "instrumentdefinition.h" #include "instrumentdata.h" #include "colorpicture/colorpicture.h" #include "imagestatistics/imagestatistics.h" #include "threading/mainguiworker.h" #include "functions.h" #include "status.h" #include "processingExternal/errordialog.h" #include "processingInternal/controller.h" #include "preferences.h" #include "datadir.h" #include "ui_mainwindow.h" #include "dockwidgets/confdockwidget.h" #include "dockwidgets/monitor.h" #include "dockwidgets/memoryviewer.h" #include "tools/cpu.h" #include "tools/ram.h" #include #include #include #include #include #include #include #include #include #include #include namespace Ui { class MainWindow; } // Forward declaration class MyStringListModel; class MyStringValidator; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QString pid, QWidget *parent = nullptr); ~MainWindow(); QString GUIVERSION = "3.1.3"; QString instrument_dir; QString instrument_userDir; QString mainPID; IView *solutionViewer; Controller *controller = nullptr; ConfDockWidget *cdw; Monitor *monitor; MemoryViewer *memoryViewer = nullptr; Ui::MainWindow *ui; CPU *myCPU; RAM *myRAM; QTimer *ramTimer; QTimer *cpuTimer; QTimer *driveTimer; Status status; QMap taskCommentMap; QList threadList; instrumentDataType instData; QProgressBar *cpuProgressBar; QProgressBar *memoryProgressBar; QProgressBar *driveProgressBar; bool datadiskspace_warned; bool homediskspace_warned; int diskwarnPreference; bool doingInitialLaunch = false; bool readingSettings = false; bool checkPathsLineEdit(QLineEdit *lineEdit); void refreshMemoryViewerReceiver(); signals: QFont sendingDefaultFont(QFont); // implemented in designer void runningStatusChanged(bool running); void ControllerScanDataTree(QLineEdit *lineEdit); void newProjectLoaded(); void rereadScienceDataDir(); void messageAvailable(QString message, QString type); void warning(); void resetErrorStatus(QString dirName); public slots: void processMessage(QString text, QString type); void taskFinished(); void launchViewer(QString dirname, QString filter, QString mode); // void launchCoaddFluxcal(QString coaddImage); void appendOK(); // void resumeWorkerThread(QString acceptanceState); void on_startPushButton_clicked(); void showMessageBoxReceived(QString trigger, QString part1, QString part2); void progressUpdateReceived(float progress); void resetProgressBarReceived(); void updateSwitchProcessMonitorPreference(bool switchToMonitor); void statusChangedReceived(QString newStatus); void updateExcludedDetectors(QString badDetectors); protected: // Don't know yet what the 'override' means void closeEvent(QCloseEvent *event) override; QString thelidir; QString userdir; QFile instrument_file; QString instrument_name; QString instrument_type; QString instrument_bayer; int instrumentPreference; int numCPU = 1; int nframes = 1; int instrument_nchips = 1; long systemRAM; QString kernelType; QString productName; private slots: void resetParameters(); void checkPaths(); void connect_validators(); void establish_connections(); void initGUI(); void link_ConfToolButtons_confStackedWidget(); void link_taskCheckBoxes_confStackedWidget(); void loadPreferences(); void loadIView(); void load_dialog_newinst(); void load_dialog_imageStatistics(); void load_dialog_abszeropoint(); void load_dialog_colorpicture(); void cdw_dockLocationChanged(const Qt::DockWidgetArea &area); void cdw_topLevelChanged(bool topLevel); void on_actionAdd_new_instrument_configuration_triggered(); void on_actionEdit_preferences_triggered(); void on_actionKill_triggered(); void on_yieldToolButton_clicked(); void on_stopToolButton_clicked(); void on_processingTabWidget_currentChanged(int index); void on_setupInstrumentComboBox_currentTextChanged(const QString &arg1); void on_setupProjectLoadToolButton_clicked(); void on_setupReadmePushButton_clicked(); void scienceDataDirUpdatedReceived(QString allDirs); void startPushButton_clicked_dummy(QString string); void shutDown(); // void undoToolButton_clicked(); void updateFontSize(int index); void updateFont(QFont font); void updateDiskspaceWarning(int newLimit); void updateNumcpu(int cpu); void updateController(); void updateControllerFunctors(QString text); void validate(); int writePreferenceSettings(); int writeGUISettings(); // The following can also be under 'private', but then the declaration must be preceded like this: // Q_INVOKABLE QString taskHDUreformat(); QStringList taskHDUreformat(bool &stop, const QString mode); QStringList taskProcessbias(bool &stop, const QString mode); QStringList taskProcessdark(bool &stop, const QString mode); QStringList taskProcessflatoff(bool &stop, const QString mode); QStringList taskProcessflat(bool &stop, const QString mode); QStringList taskProcessscience(bool &stop, const QString mode); QStringList taskChopnod(bool &stop, const QString mode); QStringList taskBackground(bool &stop, const QString mode); QStringList taskCollapse(bool &stop, const QString mode); QStringList taskBinnedpreview(bool &stop, const QString mode); QStringList taskGlobalweight(bool &stop, const QString mode); QStringList taskIndividualweight(bool &stop, const QString mode); QStringList taskSeparate(bool &stop, const QString mode); QStringList taskCreatesourcecat(bool &stop, const QString mode); QStringList taskAstromphotom(bool &stop, const QString mode); QStringList taskAbsphotindirect(bool &stop, const QString mode); QStringList taskGetCatalogFromWEB(bool &stop, const QString mode); QStringList taskGetCatalogFromIMAGE(bool &stop, const QString mode); QStringList taskRestoreHeader(bool &stop, const QString mode); QStringList taskSkysub(bool &stop, const QString mode); QStringList taskCoaddition(bool &stop, const QString mode); QStringList taskResolveTargetSidereal(bool &stop, const QString mode); void check_taskHDUreformat(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessbias(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessdark(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessflatoff(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessflat(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessscience(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskChopnod(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskBackground(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskCollapse(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskBinnedpreview(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskGlobalweight(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskIndividualweight(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskSeparate(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskCreatesourcecat(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskAstromphotom(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskAbsphotindirect(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskGetCatalogFromWEB(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskGetCatalogFromIMAGE(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskRestoreHeader(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskSkysub(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskCoaddition(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskResolveTargetSidereal(DataDir *datadir, bool &stop, bool &skip, const QString mode); void restoreOriginalData(); void emitEditingFinished(const QString &arg1); void on_actionLicense_triggered(); void on_actionAcknowledging_triggered(); void on_actionDocumentation_triggered(); void loadCoaddAbsZP(QString coaddImage, float maxVal); void updateMemoryProgressBarReceived(long memoryUsed); void on_setupProjectLineEdit_textChanged(const QString &arg1); void displayCPUload(); void displayRAMload(); void displayDriveSpace(); private: // Variables we need to access frequently bool preventLoop_WriteSettings = false; QWidget *emptyWidget; MyStringListModel *instrument_model; Preferences *preferences; Instrument *instrument = new Instrument(this); MultidirReadme *multidirReadme; License *license; Acknowledging *acknowledging; Tutorials *tutorials; ErrorDialog *errordialog = new ErrorDialog(this); QSettings *settingsp; QMap checkboxMap; QStringList totalCommandList; QStringList cleanCommandList; QThread *workerThread; MainGUIWorker *mainGUIWorker; bool processSkyImages = false; // Flags that tell whether an error message has been shown or not. bool GAP_DYNAMIC_FOUND_shown = false; bool WINDOWSIZE_TOO_LARGE_shown = false; bool INSUFFICIENT_BACKGROUND_NUMBER_shown = false; bool SKY_FILE_NOT_FOUND_shown = false; bool NO_OVERLAP_WITH_SKYAREA_shown = false; bool MASTER_BIAS_NOT_FOUND_shown = false; bool MASTER_FLAT_NOT_FOUND_shown = false; bool MASTER_FLATOFF_NOT_FOUND_shown = false; bool MASTER_BIAS_NOT_FOUND_GLOBW_shown = false; bool MASTER_FLAT_NOT_FOUND_GLOBW_shown = false; bool NO_MJDOBS_FOR_PM_shown = false; bool CANNOT_UPDATE_HEADER_WITH_PM_READ_shown = false; bool CANNOT_UPDATE_HEADER_WITH_PM_WRITE_shown = false; bool CANNOT_UPDATE_HEADER_WITH_PA_shown = false; bool CANNOT_WRITE_RESAMPLE_LIST_shown = false; bool CANNOT_OPEN_FILE_shown = false; bool CANNOT_READ_HEADER_KEYS_shown = false; bool DUPLICATE_MJDOBS_shown = false; bool IMAGES_NOT_FOUND_shown = false; bool IncompatibleSizeRAW_shown = false; bool INCONSISTENT_DATA_STATUS_shown = false; bool switchProcessMonitorPreference = true; bool areAllPathsValid(); bool checkMultipledirConsistency(QString mode); QStringList createCommandlistBlock(QString taskBasename, QStringList goodDirList, bool &stop, const QString mode); QStringList displayCoaddFilterChoice(QString dirname, QString &filterChoice, QString mode); QString estimateStatusFromFilename(DataDir *datadir); void fill_setupInstrumentComboBox(); QString getStatusForSettings(); void handleDataDirs(QStringList &goodDirList, QLineEdit *scienceLineEdit, QLineEdit *calib1LineEdit, QLineEdit *calib2LineEdit, QString statusString, bool &success); void hasDirCurrentData(DataDir *datadir, bool &stop); void initProcessingStatus(); void initInstrumentData(QString instrumentNameFullPath); bool isRefcatRecent(QString dirname); void linkPrefInst_with_MainInst(int index); QString manualCoordsUpdate(QString science, QString coordsMode); QStringList matchCalibToScience(const QStringList scienceList, const QStringList calibList); // bool maybeSave(); void on_setupInstrumentComboBox_clicked(); void populateTaskCommentMap(); int readPreferenceSettings(QString &projectname); int readGUISettings(QString projectname); void repaintDataDirs(); QString sameRefCoords(QString coordsMode); void setStatusFromSettings(QString statusString); void testOverscan(QVector &overscan); void toggleButtonsWhileRunning(); void updatePreferences(); void updateInstrumentComboBoxBackgroundColor(); void updateProcessList(QStringList &commandList, QString taskBasename, QString arg1); void updateProcessList(QStringList &commandList, QString taskBasename, QString arg1, QString arg2); void addDockWidgets(); void resetProcessingErrorFlags(); bool sufficientSpaceAvailable(long spaceNeeded); QString getInstDir(QString instname); bool OSPBC_addCommandBlock(const QString taskBasename, const QString mode, bool &stop); bool OSPBC_isTaskCurrentlyVisible(QCheckBox *cb); QString OSPBC_determineExecutionMode(QObject *sender); bool OSPBC_multipleDirConsistencyCheck(); void displayMessage(QString messagestring, QString type); void checkMemoryConstraints(); void addProgressBars(); void resetInstrumentData(); int estimateBinningFactor(); void printCfitsioError(QString funcName, int status); bool checkCatalogUsability(QString mode); void startProgressBars(); void setHomeDir(); }; // Subclassing QStringListModel to allow certain entries being shown with different colors class MyStringListModel : public QStringListModel { public: MyStringListModel() { ; } QString instrument_dir; QString instrument_userDir; QVariant data(const QModelIndex & index, int role) const { if(!index.isValid()) return QVariant(); int row = index.row(); switch(role) { case Qt::DisplayRole: return this->stringList().at(row); case Qt::ForegroundRole: QFile file; QString name1 = instrument_dir+"/"+stringList().at(row)+".ini"; QString name2 = instrument_userDir+"/"+stringList().at(row)+".ini"; // Search until we found the instrument.ini file file.setFileName(name1); if (!file.exists()) file.setFileName(name2); QString type = get_fileparameter(&file, "TYPE"); if (type == "OPT") return QBrush(QColor("#0000cc")); else if (type == "NIR") return QBrush(QColor("#009900")); else if (type == "NIRMIR") return QBrush(QColor("#cc5500")); else if (type == "MIR") return QBrush(QColor("#ff0000")); else return QBrush(QColor("#0000cc")); } return QVariant(); } }; #endif // MAINWINDOW_H THELI-3.1.3/src/mainwindow.ui000066400000000000000000002505201417631501300156720ustar00rootroot00000000000000 MainWindow 0 0 468 736 0 0 THELI GUI false QMainWindow::AllowTabbedDocks|QMainWindow::AnimatedDocks|QMainWindow::GroupedDragging 0 0 0 0 252 252 252 165 205 208 252 252 252 165 205 208 165 205 208 165 205 208 true QFrame::Panel QFrame::Raised 1 40 40 40 40 Qt::ClickFocus WARNING: Restores all raw data! All processed data in memory and on drive will be lost. ... :/icons/db-reset.png:/icons/db-reset.png 48 48 true 0 0 75 true Project name false 40 40 40 40 Qt::ClickFocus Load an existing project ... :/icons/open_project.png:/icons/open_project.png 48 48 false true true 0 0 75 true Instrument false Qt::ClickFocus A meaningful name for this project, e.g. NGC1234_J-band 40 40 40 40 Qt::ClickFocus Reset all parameters for this project. Data kept in memory will optionally be written to the drive. ... :/icons/db-restart-icon.png:/icons/db-restart-icon.png 49 49 false true true Qt::NoFocus Select instrument. Blue=optical, green = 1.0-2.5 microns, orange=1-5 microns, red=mid-IR 20 Qt::Vertical QSizePolicy::Fixed 17 8 0 0 450 0 Qt::ClickFocus Displays top-level messages about the processing queue QFrame::Panel 2 true false Qt::Vertical QSizePolicy::Fixed 17 8 80 0 80 16777215 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 0 0 0 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 0 0 0 255 255 255 0 0 0 255 255 255 68 216 204 0 0 0 161 235 229 255 255 220 0 0 0 34 108 102 68 216 204 149 255 247 108 235 225 34 108 102 45 144 136 34 108 102 255 255 255 34 108 102 68 216 204 68 216 204 0 0 0 68 216 204 255 255 220 0 0 0 50 false Qt::ClickFocus Start the selected tasks false Start false 40 40 40 40 Lets the current task finish for the current data set, then stops (soft abort). true ... :/icons/Signal-yield-icon.png:/icons/Signal-yield-icon.png 40 40 40 40 40 40 Stops the current task gracefully (task will not finish), files on drive may need manual clean-up (hard abort). true ... :/icons/Actions-process-stop-icon.png:/icons/Actions-process-stop-icon.png 40 40 Qt::Horizontal 40 20 200 0 The progress of the currently ongoing task 0 Qt::AlignCenter 0 0 450 0 0 0 0 190 222 252 255 255 255 222 238 253 95 111 126 127 148 168 0 0 0 255 255 255 0 0 0 255 255 255 190 222 252 0 0 0 222 238 253 255 255 220 0 0 0 0 0 0 190 222 252 255 255 255 222 238 253 95 111 126 127 148 168 0 0 0 255 255 255 0 0 0 255 255 255 190 222 252 0 0 0 222 238 253 255 255 220 0 0 0 95 111 126 190 222 252 255 255 255 222 238 253 95 111 126 127 148 168 95 111 126 255 255 255 95 111 126 190 222 252 190 222 252 0 0 0 190 222 252 255 255 220 0 0 0 Qt::ClickFocus The data tree and processing tasks true 0 Data tree MAIN dir 0 0 30 0 30 16777215 85 170 255 85 170 255 85 170 255 75 true Qt::ClickFocus ? The main directory containing all data. ABSOLUTE PATH required. true BIAS BIAS directories, applied to SCIENCE and SKY. Applied to FLAT if no FLAT_OFF data specified. true DARK DARK directories, applied to SCIENCE and SKY, only true FLAT OFF/DARK Dark flats (NIR) or actual darks for flats true FLAT FLAT directories true SCIENCE Directories with SCIENCE exposures go here true SKY Directories with blank fields for the science exposures true false STANDARD false Directory with standard star exposures true Qt::Vertical 20 50 Calibration tasks 0 0 Qt::ClickFocus Applies an average row/column correction to remove linear gradients. Collapse correction 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true 0 0 Qt::ClickFocus Displays binned previews of the fully preprocessed data. Binned preview Qt::Vertical 20 2 0 0 Qt::ClickFocus MANDATORY: Header reformatting, splitting of multi-chip data true HDU reformatting and detector-level corrections 0 0 Qt::ClickFocus Create a master BIAS Process BIAS 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true 0 0 Qt::ClickFocus Create a master DARK Process DARK 0 0 Qt::ClickFocus Create a master dark flat or flat dark Process FLAT OFF / FLAT DARK 0 0 Qt::ClickFocus Create the master FLAT Process FLAT 0 0 Qt::ClickFocus Apply master BIAS / DARK / FLAT true Process SCIENCE with BIAS / DARK and FLAT false 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true false 0 0 Qt::ClickFocus Performs standard chop-nod sky subtraction for mid-infrared data Chop/Nod skysub (MIR) 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true 0 0 Qt::ClickFocus Performs static or dynamic background modeling. Background correction 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true Coaddition tasks 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true Qt::ClickFocus MANDATORY: Prepares the global weight maps true Global weight maps 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true Qt::ClickFocus MANDATORY: Calculates individual weight maps true Individual weight maps true 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true true Qt::ClickFocus Separates target groups if several targets have been combined so far in the same directory. Separate target groups false 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true false Qt::ClickFocus Performs absolute photometry using photometric standard star observations. Absolute photometry (using standard stars) 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true Qt::ClickFocus MANDATORY: Creates source catalogs for each image, used for photometry and astrometry. true Create catalogs 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true Qt::ClickFocus MANDATORY: Performs the astrometry true Astrometry / relative photometry false 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true false Qt::ClickFocus Star flat 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true Qt::ClickFocus Calculates a sky model, fit or constant sky. Mandatory for multi-chip data. Sky subtraction 20 20 20 20 Qt::ClickFocus icons/key.pngicons/key.png 40 40 true 50 false Qt::ClickFocus MANDATORY: Final image coaddition. true Coaddition Qt::Vertical 20 34 0 0 468 23 THELI About Documentation toolBar 22 22 TopToolBarArea false Create new instrument ... :/icons/iview.png:/icons/iview.png iView Launch iView :/icons/sigma.png:/icons/sigma.png Image statistics Loads the image statistics module :/icons/color.png:/icons/color.png Color picture Load the color picture module :/icons/addInst.png:/icons/addInst.png New instrument Add a new instrument configuration :/icons/abszp.png:/icons/abszp.png AbsZP Absolute photometric calibration &Close true Configuration Displays the task configuration options Displays the task configuration options true Monitor Displays output from the current processing tasks Displays output from the current processing tasks :/icons/settings-icon.png:/icons/settings-icon.png Preferences Edit preferences :/icons/settings-icon.png:/icons/settings-icon.png Edit preferences :/icons/addInst.png:/icons/addInst.png Add new instrument configuration :/icons/bones_final.png:/icons/bones_final.png Kill current task. Restart recommended. Kills the current task immediately. Files on drive may need manual clean-up. Data model in memory possibly corrupted. Restart recommended. About GPL License Acknowledging Tutorials Links to online documentation setupProjectLineEdit setupInstrumentComboBox setupMainLineEdit setupBiasLineEdit setupDarkLineEdit setupFlatoffLineEdit setupFlatLineEdit setupScienceLineEdit setupSkyLineEdit setupStandardLineEdit sendingDefaultFont(QFont) link_ConfToolButtons_confStackedWidget() resizeAfterUndocking() checkPaths() loadDefaults() toggle_skyparams() switch_static_dynamic() link_taskCheckBoxes_confStackedWidget() load_dialog_zp() updateConfPageLabel() message(QString,QString) THELI-3.1.3/src/myimage/000077500000000000000000000000001417631501300146035ustar00rootroot00000000000000THELI-3.1.3/src/myimage/astrometrynet.cc000066400000000000000000000127461417631501300200440ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // This file deals with running anettractor as an external tool #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../threading/anetworker.h" #include #include #include #include #include #include void MyImage::buildAnetCommand(QString pixscale_maxerr) { if (!successProcessing) return; anetCommand = findExecutableName("solve-field"); anetCommand += " -w "+QString::number(naxis1); anetCommand += " -e "+QString::number(naxis2); anetCommand += " -L "+QString::number(plateScale / pixscale_maxerr.toFloat(), 'f', 5); anetCommand += " -H "+QString::number(plateScale * pixscale_maxerr.toFloat(), 'f', 5); anetCommand += " -O"; // suppress output anetCommand += " -p"; // suppress output plots anetCommand += " -u app"; // units arcsec per pixel anetCommand += " -l 5"; // CPU timeout after 5 seconds anetCommand += " -T"; // don't compute SIP polynomials anetCommand += " -s MAG"; // sort column anetCommand += " -a "; // sort order: ascending (bright sources first) anetCommand += " -b " + path + "/astrom_photom_anet/backend.cfg"; // config file anetCommand += " -R none"; // suppress output anetCommand += " -B none"; // suppress output anetCommand += " -S none"; // suppress output anetCommand += " -M none"; // suppress output anetCommand += " -U none"; // suppress output anetCommand += " --temp-axy"; // suppress output anetCommand += " -W " + path + "/astrom_photom_anet/"+chipName+".wcs"; // output file anetCommand += " " + path + "/cat/"+chipName+".anet"; if (*verbosity > 1) emit messageAvailable("Executing the following astrometry.net command :

"+anetCommand+"
", "info"); } // start in new thread void MyImage::runAnetCommand() { if (!successProcessing) return; // Run the solve-field command workerThread = new QThread(); anetWorker = new AnetWorker(anetCommand, path); anetWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, anetWorker, &AnetWorker::runAnet); connect(anetWorker, &AnetWorker::errorFound, this, &MyImage::errorFoundReceived); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); // Direct connection required, otherwise the task hangs after the first solve-field command // (does not proceed to the next step in the controller's for loop) connect(anetWorker, &AnetWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(anetWorker, &AnetWorker::finished, anetWorker, &QObject::deleteLater); connect(anetWorker, &AnetWorker::messageAvailable, this, &MyImage::anetOutputReceived); workerThread->start(); workerThread->wait(); } QString MyImage::extractAnetOutput() { QString anetOutput = path + "/astrom_photom_anet/"+chipName+".wcs"; QFile wcsOutput(anetOutput); if (!wcsOutput.exists()) { emit messageAvailable(chipName + " : Did not solve!", "error"); emit critical(); return ""; } else { emit messageAvailable(chipName + " : Successfully solved", "note"); } QString header; fitsfile *fptr; int status = 0; int nkeys = 0; int keypos = 0; char card[FLEN_CARD]; fits_open_file(&fptr, anetOutput.toUtf8().data(), READONLY, &status); fits_get_hdrpos(fptr, &nkeys, &keypos, &status); for (int jj = 1; jj <= nkeys; ++jj) { fits_read_record(fptr, jj, card, &status); QString cardString(card); if (cardString.contains("EQUINOX =") || cardString.contains("RADESYS =") || cardString.contains("CTYPE1 =") || cardString.contains("CTYPE2 =") || cardString.contains("CUNIT1 =") || cardString.contains("CUNIT2 =") || cardString.contains("CRVAL1 =") || cardString.contains("CRVAL2 =") || cardString.contains("CRPIX1 =") || cardString.contains("CRPIX2 =") || cardString.contains("CD1_1 =") || cardString.contains("CD1_2 =") || cardString.contains("CD2_1 =") || cardString.contains("CD2_2 =")) { header.append(cardString); header.append("\n"); } } header.append("END\n"); if (status == END_OF_FILE) status = 0; else printCfitsioError(__func__, status); fits_close_file(fptr, &status); return header; } THELI-3.1.3/src/myimage/background.cc000066400000000000000000000503451417631501300172400ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "instrumentdata.h" #include "../functions.h" #include "myimage.h" #include #include #include #include #include #include void MyImage::backgroundModel(int filtersize, QString splinemode) { // Currently, we always do an interpolation, independently of 'splinemode' if (!successProcessing) return; if (backgroundModelDone) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Background mapping ... ", "image"); filterSize = filtersize; splineMode = splinemode; gridStep = filterSize / subSample; dataBackground_deletable = false; // QVector maskData(naxis1*naxis2, false); // The dimensions of the padded image (margins) getPadDimensions(); // Pad the image // padImage(); // Place a grid over the image planGrid(); // Calculate background value at each grid point getGridStatistics(); // replace blank grid points with local estimate replaceBlankGridStatistics(); // Spatial median filter of the statistics filterGridStatistics(); // Do the spline fit fitBackgroundGSL(); backgroundModelDone = true; } void MyImage::getMeanBackground() { if (!successProcessing) return; float skysum = 0.; for (auto &pixel : dataBackground) { skysum += pixel; } meanExposureBackground = skysum / (naxis1*naxis2); } void MyImage::fitBackgroundGSL() { if (!successProcessing) return; double *xa = new double[n_grid]; double *ya = new double[m_grid]; double *za = new double[nGridPoints]; // Prepare the input data for (int i=1; i<=n_grid; ++i) xa[i-1] = i*gridStep; for (int j=1; j<=m_grid; ++j) ya[j-1] = j*gridStep; long k=0; for (int j=0; j= naxis1 || j-pad_b < 0 || j-pad_b >= naxis2) qDebug() << "MyImage::background: GSLFIT: padding error"; double x = double(i); dataBackground[i-pad_l+naxis1*(j-pad_b)] = gsl_spline2d_eval(spline, x, y, xacc, yacc); } } gsl_spline2d_free(spline); gsl_interp_accel_free(xacc); gsl_interp_accel_free(yacc); delete [] xa; delete [] ya; delete [] za; xa = nullptr; ya = nullptr; za = nullptr; } void MyImage::getGridStatistics() { if (!successProcessing) return; // Calculate modes by stepping through grid points backStatsGrid.clear(); backStatsGrid.fill(-1e9, nGridPoints); rmsStatsGrid.clear(); rmsStatsGrid.fill(-1., nGridPoints); long sampleSize = gridStep * gridStep / 4; // This many pixels are evaluated at each grid point QVector backgroundSample; backgroundSample.reserve(sampleSize); // for (long index=0; index= naxis1 || j-pad_b < 0 || j-pad_b>=naxis2) continue; // Take into account global mask, and possibly object masks as well (if defined) // With global mask long ii = i-pad_l+naxis1*(j-pad_b); if (globalMaskAvailable && !globalMask[ii]) { if (!weightInMemory) { if (!objectMaskDone || !objectMask[ii]) { // !objectMask[ii] implies objectMaskDone = true backgroundSample.append(dataCurrent[ii]); } } else { if (dataWeight[ii] > 0. && (!objectMaskDone || !objectMask[ii])) { backgroundSample.append(dataCurrent[ii]); } } } // without global mask: external image, e.g. for absZP else { if (!weightInMemory) { if (!objectMaskDone || !objectMask[ii]) { backgroundSample.append(dataCurrent[ii]); } } else { if (dataWeight[ii] > 0. && (!objectMaskDone || !objectMask[ii])) { backgroundSample.append(dataCurrent[ii]); } } } } } QVector sky = modeMask(backgroundSample, "stable"); if (sky[1] > 0.) backStatsGrid[index] = sky[0]; // Histogram peak location (if rms could be evaluated, or data were present) if (sky[1] > 0.) rmsStatsGrid[index] = sky[1]; backgroundSample.clear(); } } // calculate average stdev (ignoring the padded border) skySigma = 0.; float count = 0.; for (auto &sigma : rmsStatsGrid) { if (sigma > 0.) { skySigma += sigma; ++count; } } skySigma /= count; // data_padded.clear(); // data_padded.squeeze(); // mask_padded.clear(); // mask_padded.squeeze(); } // replace a grid point that could not be evaluated with the mean of its closest neighbors void MyImage::replaceBlankGridStatistics() { if (!successProcessing) return; QVector backup = backStatsGrid; long gmax = n_grid < m_grid ? m_grid : n_grid; for (long j=0; j= n_grid ? n_grid-1 : i+s; int jmax = j+s >= m_grid ? m_grid-1 : j+s; sum = 0.; nfound = 0.; for (int jj=jmin; jj<=jmax; ++jj) { for (int ii=imin; ii<=imax; ++ii) { float gridVal = backup[ii+n_grid*jj]; if (gridVal > -1e9) { sum += gridVal; ++nfound; } } } ++s; } backStatsGrid[i+n_grid*j] = sum / nfound; } } } if (*verbosity > 1) { emit messageAvailable(chipName + " : mean / stdev = " + QString::number(meanMask_T(backStatsGrid), 'f', 3) + " / " + QString::number(skySigma, 'f', 3), "image"); } } void MyImage::filterGridStatistics() { if (!successProcessing) return; // WARNING: this function alters the values of 'backStatsGrid' // Create a copy QVector backStatsGridOrig = backStatsGrid; // Median filter QVector medianSample; medianSample.reserve(9); // maximally 3x3 for (long j=0; j= m_grid ? m_grid-1 : j+1; for (long i=0; i= n_grid ? n_grid-1 : i+1; for (int jj=jmin; jj<=jmax; ++jj) { for (int ii=imin; ii<=imax; ++ii) { medianSample.push_back(backStatsGridOrig[ii+n_grid*jj]); } } backStatsGrid[i+n_grid*j] = straightMedian_T(medianSample); medianSample.clear(); } } } void MyImage::getPadDimensions() { if (!successProcessing) return; // The actual padding width is twice as large as the gridStep // to ensure we have enough space to evaluate the grid without having to care for boundaries int w = 2 * gridStep; // Output contains left, bottom, right, top pad widths, and overall dimensions padDims.clear(); pad_r = w; // same as padWidth w unless +1 to make even dimension pad_t = w; pad_l = w; pad_b = w; if (padMode == "normal") { // make an image with even dimensions to avoid unclear quadrant swapping (if we FFT the padded image elsewhere) if ( naxis1 % 2 != 0) pad_r++; if ( naxis2 % 2 != 0) pad_t++; n_pad = naxis1 + pad_l + pad_r; m_pad = naxis2 + pad_b + pad_t; } else { // padMode = "dyadic" // pad first, then make dyadic image size n_pad = pow(2, ceilf( logf(naxis1+2*w) / logf(2.))); m_pad = pow(2, ceilf( logf(naxis2+2*w) / logf(2.))); pad_l = (n_pad - naxis1) / 2; pad_b = (m_pad - naxis2) / 2; pad_r = n_pad - naxis1 - pad_l; pad_t = m_pad - naxis2 - pad_b; } } /* // The following code pads the image with data. However, we don't need that. // The grid positions in the padded data are filled using known grid points inside the image. // Code is kept in case I need it in the future // Pads an image with a given border width. If mode="dyadic", expands it to the next largest power of 2 // We use twice the grid step so that we have sufficient space to comfortably place a grid over the image including the boundaries. // By making it twice as large, we don't need to introduce boundary conditions when evaluating histograms outside the nominal image area. void MyImage::padImage() { // resize the vector correspondingly data_padded.resize(n_pad*m_pad); mask_padded.fill(true, n_pad*m_pad); // everything is masked per default, then unmask the true image area long n = naxis1; long m = naxis2; // copy image to center of padded image for (long j=pad_b; j0) return w-i; else if (w+i>=max) return max-w-i-1; else return 0; } // Calculate a local moving median around the left and right edge void MyImage::padEdgeLR(int width, QString edge, long ipadmin, long ipadmax, long jpadmin, long jpadmax) { long n = naxis1; long m = naxis2; long imin; long imax; if (edge == "l") { imin = 0; imax = width; } else if (edge == "r") { imin = n-width; imax = n; } else return; // Containers for the median edge values, the mask, and the sample QVector edgeData; QVector edgeMask; QVector sample; edgeData.reserve(m); edgeMask.reserve(m); sample.reserve(width*width); // Calculate the padded values int wh = width / 2; int step = 3; // accelerator (if larger than 1; not implemented in GUI) for (long j=0; j edgeData; QVector edgeMask; QVector sample; edgeData.reserve(n); edgeMask.reserve(n); sample.reserve(width*width); // Calculate the padded values int wh = width / 2; int step = 3; // accelerator (if larger than 1; sparse sampling) for (long i=0; i sample; sample.reserve(width*width); for (long j=jmin; j grid_x(nGridPoints); QVector grid_y(nGridPoints); long count = 0; for (int j=1; j<=m_grid; ++j) { long jgrid = j*gridStep; for (int i=1; i<=n_grid; ++i) { long igrid = i*gridStep; grid_x[count] = igrid; // points along NAXIS1 grid_y[count] = jgrid; // points along NAXIS2 ++count; } } grid << grid_x << grid_y; } void MyImage::releaseBackgroundMemory(QString mode) { emit setMemoryLock(true); if (minimizeMemoryUsage || mode == "entirely") { dataBackground.clear(); dataBackground.squeeze(); backgroundModelDone = false; } else { dataBackground_deletable = true; } grid.clear(); grid.squeeze(); backStatsGrid.clear(); backStatsGrid.squeeze(); rmsStatsGrid.clear(); rmsStatsGrid.squeeze(); emit setMemoryLock(false); } void MyImage::releaseBackgroundMemoryBackgroundModel() { emit setMemoryLock(true); if (leftBackgroundWindow) { dataBackground.clear(); dataBackground.squeeze(); grid.clear(); grid.squeeze(); backStatsGrid.clear(); backStatsGrid.squeeze(); rmsStatsGrid.clear(); rmsStatsGrid.squeeze(); backgroundModelDone = false; } emit setMemoryLock(false); } void MyImage::subtractBackgroundModel() { if (!successProcessing) return; long i=0; for (auto &pixel : dataCurrent) { if (!globalMask.isEmpty()) { if (!globalMask[i]) pixel -= dataBackground[i]; } else { pixel -= dataBackground[i]; } ++i; } } THELI-3.1.3/src/myimage/fitsinterface.cc000066400000000000000000000435271417631501300177530ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include #include "../tools/cfitsioerrorcodes.h" #include "wcs.h" #include "wcshdr.h" #include "../functions.h" #include #include #include #include // Extract the FILTER keyword from a yet unopened FITS file void MyImage::readFILTER(QString loadFileName) { if (loadFileName.isEmpty()) loadFileName = path + pathExtension + "/" + baseName + ".fits"; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); char filterchar[80]; fits_read_key_str(fptr, "FILTER", filterchar, NULL, &status); fits_close_file(fptr, &status); QString filterstring(filterchar); printCfitsioError(__func__, status); filter = filterstring.simplified(); } // Extract the NAXIS1, NAXIS2, CRPIX1, CRPIX2, SKYVALUE and FLXSCALE keywords from a yet unopened (resampled) FITS file for swarpfilter() bool MyImage::informSwarpfilter(long &naxis1, long &naxis2, double &crpix1, double &crpix2, double &sky, double &fluxscale) { QString loadFileName = path + "/" + name; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); fits_read_key_dbl(fptr, "CRPIX1", &crpix1, NULL, &status); fits_read_key_dbl(fptr, "CRPIX2", &crpix2, NULL, &status); fits_read_key_lng(fptr, "NAXIS1", &naxis1, NULL, &status); fits_read_key_lng(fptr, "NAXIS2", &naxis2, NULL, &status); fits_read_key_dbl(fptr, "FLXSCALE", &fluxscale, NULL, &status); // get the sky value from the MyImage if not present in the header of the FITS file // (in case the user did not run the calibration step) int preSky = status; fits_read_key_dbl(fptr, "SKYVALUE", &sky, NULL, &status); int postSky = status; if (!preSky && postSky) { sky = skyValue; if (sky != 0.) status = 0; else status = 1; } fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (fluxscale == 0.) { emit messageAvailable(name + ": FLXSCALE = 0 in resampled FITS header. Relative photometry failed or not propagated correctly during scamp run", "error"); emit critical(); return false; } if (status) return false; else return true; } void MyImage::initFITS(fitsfile **fptr, QString loadFileName, int *status) { if (loadFileName.isNull() || loadFileName.isEmpty()) { *status = 1; emit messageAvailable(name+"MyImage::initFITS(): file name empty or not initialized!", "error"); return; } // Bypassing a memory leak in cfitsio QFile file(loadFileName); if (!file.exists()) { emit messageAvailable(name+" MyImage::initFITS(): File does not exist at current location!", "error"); *status = 104; return; } fits_open_file(fptr, loadFileName.toUtf8().data(), READONLY, status); fits_get_num_hdus(*fptr, &numExt, status); if (numExt > 1) { QMessageBox msgBox; msgBox.setText(name+" is a multi-extension FITS file, which is currently not supported."); msgBox.exec(); *status = 1; } } void MyImage::readHeader(fitsfile **fptr, int *status) { if (*status) return; // Read the entire header. This should always work! fits_hdr2str(*fptr, 0, NULL, 0, &fullheader, &numHeaderKeys, status); fullheaderAllocated = true; if (*status) return; fullHeaderString = QString::fromUtf8(fullheader); // Map the header onto a QVector int cardLength = 80; long length = fullHeaderString.length(); if (length<80) return; header.clear(); for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&fullHeaderString, i, cardLength); QString string = subString.toString(); header.push_back(string); } } void MyImage::readData(fitsfile **fptr, int *status) { if (*status) return; long naxis[2]; // Get image geometry fits_get_img_size(*fptr, 2, naxis, status); // Read the data block naxis1 = naxis[0]; naxis2 = naxis[1]; long nelements = naxis1*naxis2; float *buffer = new float[nelements]; float nullval = 0.; int anynull; long fpixel = 1; fits_read_img(*fptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, status); if (! *status) { dataCurrent.resize(nelements); for (long i=0; istatusString+".fits"; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); readHeader(&fptr, &status); readData(&fptr, &status); #pragma omp critical { initWCS(); } initTHELIheader(&status); checkTHELIheader(&status); cornersToRaDec(); fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (!status) headerInfoProvided = true; else headerInfoProvided = false; if (status) return false; else return true; } // for weights only, when having to read the globalweights bool MyImage::loadDataThreadSafe(QString loadFileName) { int status = 0; #pragma omp critical { if (loadFileName.isEmpty()) loadFileName = path + "/" + chipName+processingStatus->statusString+".fits"; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); readHeader(&fptr, &status); readData(&fptr, &status); initWCS(); initTHELIheader(&status); checkTHELIheader(&status); cornersToRaDec(); fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (!status) headerInfoProvided = true; else headerInfoProvided = false; } if (status) return false; else return true; } // Setup the WCS void MyImage::initWCS() { // CHECK: This line must be commented so that the redshift module works. // For a reason I don't understand 'successProcessing' is wrong for the spectra when loaded. // if (!successProcessing) return; emit setWCSLock(true); // It appears that not everything in the wcslib is threadsafe int nreject; int nwcs; int check = wcspih(fullheader, numHeaderKeys, 0, 0, &nreject, &nwcs, &wcs); if (check > 1) { emit messageAvailable("MyImage::initWCS(): " + baseName + ": wcspih() returned" + QString::number(check), "error" ); emit critical(); successProcessing = false; wcsInit = false; emit setWCSLock(false); return; } if (nwcs == 0 || check == 1) { // OK state, e.g. for master calibrators which don't have a valid WCS if (*verbosity > 2) emit messageAvailable(chipName + " : No WCS representation found", "image"); wcsInit = false; emit setWCSLock(false); return; } int wcsCheck = wcsset(wcs); if (wcsCheck > 0) { QString wcsError = ""; if (wcsCheck == 1) wcsError = "Null wcsprm pointer passed"; // Should be caught by 'if' conditions above if (wcsCheck == 2) wcsError = "Memory allocation failed"; if (wcsCheck == 3) wcsError = "Linear transformation matrix is singular"; if (wcsCheck == 4) wcsError = "Inconsistent or unrecognized coordinate axis types"; if (wcsCheck == 5) wcsError = "Invalid parameter value"; if (wcsCheck == 6) wcsError = "Invalid coordinate transformation parameters"; if (wcsCheck == 7) wcsError = "Ill-conditioned coordinate transformation parameters"; emit messageAvailable("MyImage::initWCS(): wcsset() error : " + wcsError, "error"); emit critical(); successProcessing = false; wcsInit = false; emit setWCSLock(false); return; } wcsInit = true; plateScale = sqrt(wcs->cd[0] * wcs->cd[0] + wcs->cd[2] * wcs->cd[2]) * 3600.; // in arcsec; technically, this is the increment in the x-axis if (plateScale == 0.) plateScale = 1.0; if (*verbosity > 2) { emit messageAvailable(chipName + " : RA / DEC = " + QString::number(wcs->crval[0], 'f', 6) + " " + QString::number(wcs->crval[1], 'f', 6), "image"); } emit setWCSLock(false); } // If header data are needed, but not (yet) the data block. // E.g. if the GUI is started, and the first task is to download the reference catalog or to update the zero-th order solution void MyImage::loadHeader(QString loadFileName) { if (headerInfoProvided) return; if (loadFileName.isEmpty()) loadFileName = path+pathExtension+"/"+baseName+".fits"; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); readHeader(&fptr, &status); #pragma omp critical { initWCS(); } initTHELIheader(&status); checkTHELIheader(&status); cornersToRaDec(); radius = sqrt(naxis1*naxis1 + naxis2*naxis2)/2. * plateScale / 3600; // image radius in degrees. Must be determined after initWCS and initTHELIheader when naxis_i/j are known fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (!status) headerInfoProvided = true; else headerInfoProvided = false; } void MyImage::getMJD() { if (hasMJDread) return; fitsfile *fptr = nullptr; QString fileName = path+pathExtension+"/"+chipName+processingStatus->statusString+".fits"; int status = 0; fits_open_file(&fptr, fileName.toUtf8().data(), READONLY, &status); fits_read_key_dbl(fptr, "MJD-OBS", &mjdobs, NULL, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (status) hasMJDread = false; else hasMJDread = true; } void MyImage::initTHELIheader(int *status) { if (*status) return; for (auto &it : header) { extractKeywordLong(it, "NAXIS1", naxis1); extractKeywordLong(it, "NAXIS2", naxis2); extractKeywordDouble(it, "MJD-OBS", mjdobs); extractKeywordString(it, "FILTER", filter); extractKeywordString(it, "DATE-OBS", dateobs); extractKeywordFloat(it, "EXPTIME", exptime); extractKeywordFloat(it, "GAINCORR", gainNormalization); extractKeywordFloat(it, "SKYVALUE", skyValue); extractKeywordInt(it, "BITPIX", bitpix); extractKeywordFloat(it, "SKYVALUE", skyValue); extractKeywordFloat(it, "AIRMASS", airmass); extractKeywordFloat(it, "GEOLON", geolon); extractKeywordFloat(it, "GEOLAT", geolat); extractKeywordFloat(it, "FWHM", fwhm); extractKeywordFloat(it, "FWHMEST", fwhm_est); extractKeywordFloat(it, "GAIN", gain); extractKeywordFloat(it, "ELLIP", ellipticity); extractKeywordFloat(it, "ELLIPEST", ellipticity_est); extractKeywordFloat(it, "RZP", RZP); extractKeywordFloat(it, "SATURATE", saturationValue); } if (mjdobs != 0.0) hasMJDread = true; else hasMJDread = false; filter = filter.simplified(); dim = naxis1*naxis2; if (skyValue != -1e9) modeDetermined = true; else modeDetermined = false; metadataTransferred = true; } void MyImage::checkTHELIheader(int *status) { if (*status) return; if (fullHeaderString.contains("NAXIS1 =") && fullHeaderString.contains("NAXIS2 =") && fullHeaderString.contains("CRPIX1 =") && fullHeaderString.contains("CRPIX2 =") && fullHeaderString.contains("CRVAL1 =") && fullHeaderString.contains("CRVAL2 =") && fullHeaderString.contains("CD1_1 =") && fullHeaderString.contains("CD1_2 =") && fullHeaderString.contains("CD2_1 =") && fullHeaderString.contains("CD2_2 =") && fullHeaderString.contains("EQUINOX =") && fullHeaderString.contains("EXPTIME =") && fullHeaderString.contains("FILTER =") && fullHeaderString.contains("GAIN =") && fullHeaderString.contains("OBJECT =") && fullHeaderString.contains("MJD-OBS =")) { hasTHELIheader = true; } else { hasTHELIheader = false; } } void MyImage::extractKeywordDouble(QString card, QString key, double &value) { // Make keys unique (e.g. EXPTIME vs TEXPTIME) by constructing full keyword key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toDouble(); } void MyImage::extractKeywordFloat(QString card, QString key, float &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toFloat(); } void MyImage::extractKeywordLong(QString card, QString key, long &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toLong(); } void MyImage::extractKeywordInt(QString card, QString key, int &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toInt(); } void MyImage::extractKeywordString(QString card, QString key, QString &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'"); } void MyImage::propagateHeader(fitsfile *fptr, QVector header) { if (header.isEmpty()) return; int status = 0; // DO NOT COPY BITPIX, NAXIS, NAXIS1/2, EXTEND keywords for (int i=0; i= naxis1) coord = naxis1 - 1; } else { if (coord >= naxis2) coord = naxis2 - 1; } } // Make sure a vector with xmin xmax ymin ymax stays within the image boundaries void MyImage::stayWithinBounds(QVector &vertices) { if (vertices[0] < 0) vertices[0] = 0; if (vertices[1] > naxis1-1) vertices[1] = naxis1-1; if (vertices[2] < 0) vertices[2] = 0; if (vertices[3] > naxis2-1) vertices[3] = naxis2-1; } // used in swarpfilter (using arrays instead of vectors, for performance reasons; unnecessary data copying) void MyImage::loadDataSection(long xmin, long xmax, long ymin, long ymax, float *dataSect) { QString fileName = path + "/" + name; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, fileName, &status); fits_read_key_lng(fptr, "NAXIS1", &naxis1, NULL, &status); fits_read_key_lng(fptr, "NAXIS2", &naxis2, NULL, &status); long xmin_old = xmin; long xmax_old = xmax; long ymin_old = ymin; long ymax_old = ymax; stayWithinBounds(xmin, "x"); stayWithinBounds(xmax, "x"); stayWithinBounds(ymin, "y"); stayWithinBounds(ymax, "y"); if (xmin != xmin_old || xmax != xmax_old || ymin != ymin_old || ymax != ymax_old) { emit messageAvailable("MyImage::loadDataSection() / swarpfilter: image size was modified!", "error"); return; } float nullval = 0.; int anynull = 0; long fpixel[2] = {xmin+1, ymin+1}; // cfitsio starts counting at 1, at least here long lpixel[2] = {xmax+1, ymax+1}; // cfitsio starts counting at 1, at least here long strides[2] = {1, 1}; fits_read_subset(fptr, TFLOAT, fpixel, lpixel, strides, &nullval, dataSect, &anynull, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } THELI-3.1.3/src/myimage/memoryoperations.cc000066400000000000000000000564111417631501300205350ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../processingStatus/processingStatus.h" #include #include #include #include #include // same as pushdown(), without file movement void MyImage::makeMemoryBackup() { if (activeState != ACTIVE) return; // Don't change location of deactivated images // TODO: implement a finer granularity memory check (sufficient RAM available?) if (!minimizeMemoryUsage) { dataBackupL3 = dataBackupL2; dataBackupL2 = dataBackupL1; } dataBackupL1 = dataCurrent; statusBackupL3 = statusBackupL2; statusBackupL2 = statusBackupL1; statusBackupL1 = processingStatus->statusString; emit modelUpdateNeeded(chipName); // implement: // processingStatus->statusString = statusCurrentNew; } // UNUSED? void MyImage::makeDriveBackup(QString backupDirName, QString statusOld) { if (!successProcessing) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images // Current and backup paths QString currentPath = path; QString backupPath = path+"/"+backupDirName+"/"; QString oldName = chipName+statusOld+".fits"; QFile image(currentPath+"/"+oldName); // Do nothing if the image does not exist on drive (i.e. is in memory only) if (!image.exists()) return; moveFile(oldName, currentPath, backupPath); } void MyImage::makeBackgroundBackup() { if (activeState != ACTIVE) return; // Don't change location of deactivated images // make backup file (if the FITS file exists) mkAbsDir(pathBackupL1); moveFile(baseNameBackupL1+".fits", path, pathBackupL1, true); backupL1OnDrive = true; emit modelUpdateNeeded(chipName); } // Push data one step into the backup structure void MyImage::pushDown(QString backupDir) { if (activeState != ACTIVE) return; // Don't change location of deactivated images // MEMORY pushDownToL3(); pushDownToL2(); pushDownToL1(backupDir); // DRIVE // make backup file (if the FITS file exists) mkAbsDir(pathBackupL1); moveFile(baseNameBackupL1+".fits", path, pathBackupL1, true); // backupL1OnDrive = true; emit modelUpdateNeeded(chipName); } // Push dataCurrent to backupL1 void MyImage::pushDownToL1(QString backupDir) { if (activeState != ACTIVE) return; // Don't change location of deactivated images // MEMORY dataBackupL1 = dataCurrent; backupL1InMemory = imageInMemory; backupL1OnDrive = imageOnDrive; statusBackupL1 = processingStatus->statusString; dataBackupL1_deletable = dataCurrent_deletable; pathBackupL1 = path+"/"+backupDir; baseNameBackupL1 = baseName; saturationValueL1 = saturationValue; } // Push backupL1 to backupL2 void MyImage::pushDownToL2() { if (activeState != ACTIVE) return; // Don't change location of deactivated images if (!minimizeMemoryUsage) { dataBackupL2 = dataBackupL1; backupL2InMemory = backupL1InMemory; backupL2OnDrive = backupL1OnDrive; statusBackupL2 = statusBackupL1; pathBackupL2 = pathBackupL1; baseNameBackupL2 = baseNameBackupL1; dataBackupL2_deletable = dataBackupL1_deletable; saturationValueL2 = saturationValueL1; } } // Push backupL2 to backupL3 void MyImage::pushDownToL3() { if (activeState != ACTIVE) return; // Don't change location of deactivated images if (!minimizeMemoryUsage) { dataBackupL3 = dataBackupL2; backupL3InMemory = backupL2InMemory; backupL3OnDrive = backupL2OnDrive; statusBackupL3 = statusBackupL2; pathBackupL3 = pathBackupL2; baseNameBackupL3 = baseNameBackupL2; dataBackupL3_deletable = dataBackupL2_deletable; saturationValueL3 = saturationValueL2; } } // Pull data up one step from the backup structure // UNUSED void MyImage::pullUp() { if (activeState != ACTIVE) return; // Don't change location of deactivated images // DRIVE deleteFile(baseName+".fits", path); // restore backup FITS file moveFile(baseNameBackupL1+".fits", pathBackupL1, path, true); // MEMORY pullUpFromL1(); pullUpFromL2(); pullUpFromL3(); emit modelUpdateNeeded(chipName); } // Pull data up one step from the backup structure bool MyImage::makeL1Current() { if (activeState != ACTIVE) return true; // Don't change location of deactivated images; don't trigger error bool success = true; // DRIVE // The following construct gives a compiler warning with gcc7 // success *= deleteFile(baseName+".fits", path); success = success && deleteFile(baseName+".fits", path); // restore backup FITS file success = success && moveFile(baseNameBackupL1+".fits", pathBackupL1, path, true); // L1 to L0 dataCurrent = dataBackupL1; processingStatus->statusString = statusBackupL1; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL1; imageInMemory = backupL1InMemory; imageOnDrive = backupL1OnDrive; saturationValue = saturationValueL1; // MEMORY pullUpFromL2(); pullUpFromL3(); wipeL3(); emit modelUpdateNeeded(chipName); return success; } // Make L2 current bool MyImage::makeL2Current() { if (activeState != ACTIVE) return true; // Don't change location of deactivated images; don't trigger error bool success = true; // DRIVE success = success && deleteFile(baseName+".fits", path); // restore backup FITS file success = success && moveFile(baseNameBackupL2+".fits", pathBackupL2, path, true); // L2 to L0 dataCurrent = dataBackupL2; processingStatus->statusString = statusBackupL2; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL2; imageInMemory = backupL2InMemory; imageOnDrive = backupL2OnDrive; saturationValue = saturationValueL2; // L3 to L2 pullUpFromL3(); // wipe L1 and L3 wipeL1(); wipeL3(); emit modelUpdateNeeded(chipName); return success; } // make L3 current bool MyImage::makeL3Current() { if (activeState != ACTIVE) return true; // Don't change location of deactivated images; don't trigger error bool success = true; // DRIVE success = success && deleteFile(baseName+".fits", path); // restore backup FITS file success = success && moveFile(baseNameBackupL3+".fits", pathBackupL3, path, true); // L3 to L0 dataCurrent = dataBackupL3; processingStatus->statusString = statusBackupL3; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL3; imageInMemory = backupL3InMemory; imageOnDrive = backupL3OnDrive; saturationValue = saturationValueL3; // wipe L1 and L2 wipeL1(); wipeL2(); emit modelUpdateNeeded(chipName); return success; } void MyImage::pullUpFromL3() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL2 = dataBackupL3; statusBackupL2 = statusBackupL3; pathBackupL2 = pathBackupL3; dataBackupL2_deletable = dataBackupL3_deletable; baseNameBackupL2 = baseNameBackupL3; backupL2InMemory = backupL3InMemory; dataBackupL3_deletable = true; dataBackupL3.clear(); dataBackupL3.squeeze(); saturationValueL2 = saturationValueL3; } void MyImage::pullUpFromL2() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL1 = dataBackupL2; statusBackupL1 = statusBackupL2; pathBackupL1 = pathBackupL2; dataBackupL1_deletable = dataBackupL2_deletable; baseNameBackupL1 = baseNameBackupL2; backupL1InMemory = backupL2InMemory; saturationValueL1 = saturationValueL2; } void MyImage::pullUpFromL1() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataCurrent = dataBackupL1; processingStatus->statusString = statusBackupL1; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL1; imageInMemory = backupL1InMemory; saturationValue = saturationValueL1; } void MyImage::wipeL1() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL1.clear(); dataBackupL1.squeeze(); statusBackupL1 = ""; pathBackupL1 = ""; dataBackupL1_deletable = true; baseNameBackupL1 = ""; backupL1InMemory = false; } void MyImage::wipeL2() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL2.clear(); dataBackupL2.squeeze(); statusBackupL2 = ""; pathBackupL2 = ""; dataBackupL2_deletable = true; baseNameBackupL2 = ""; backupL2InMemory = false; } void MyImage::wipeL3() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL3.clear(); dataBackupL3.squeeze(); statusBackupL3 = ""; pathBackupL3 = ""; dataBackupL3_deletable = true; baseNameBackupL3 = ""; backupL3InMemory = false; } // For some tasks (e.g. source cat creation) we do not need to push down data into the backup levels void MyImage::setupDataInMemorySimple(bool determineMode) { if (activeState != ACTIVE) return; // Don't change location of deactivated images // Load the image if not in yet memory readImage(determineMode); emit modelUpdateNeeded(chipName); } // CHECK: Last argument probably not needed void MyImage::setupData(bool isTaskRepeated, bool createBackup, bool determineMode, QString backupDir) { if (!successProcessing) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images // Protect dataCurrent dataCurrent_deletable = false; // if (createBackup && backupDir.isEmpty()) emit messageAvailable("MyImage::setupData(): Cannot restore backup data from backup dir!", "error"); // CASE 1: The task has not been executed before if (!isTaskRepeated) { readImage(determineMode); // Push down data by one level (at all levels) if required if (createBackup) pushDown(backupDir); } // CASE 2: The task has been executed before and we re-do it: Restore level 1 backup if (isTaskRepeated) { // Restoring from memory if (backupL1InMemory) { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from RAM (backup level L1)", "image"); pullUpFromL1(); } // Restoring from drive else { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from backup FITS in "+pathBackupL1, "image"); // Right after launch, nothing is initialized and we must do that first using the full approach. Otherwise, we just read the data array. if (!headerInfoProvided) readImageBackupL1Launch(); else readImageBackupL1(); imageInMemory = true; backupL1InMemory = true; } } emit modelUpdateNeeded(chipName); } // If a task is repeated, replace dataCurrent with the backup copy. // Otherwise continue with data current, and push down the backup data one level void MyImage::setupBackgroundData(const bool &isTaskRepeated, const QString &backupDir) { if (!successProcessing) return; if (backgroundPushedDown) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images dataCurrent_deletable = false; dataBackupL1_deletable = false; // CASE 1: The task has not been executed before if (!isTaskRepeated) { // Nothing is in backupL1 yet, either after restart, or because RAM is low. // No push-down has happened yet if (!backgroundPushedDown) { if (!minimizeMemoryUsage) { pushDownToL3(); pushDownToL2(); } readImage(true); // if not yet in memory pushDownToL1(backupDir); // Create a safe copy of the non-subtracted data dataBackupL1_deletable = false; // set to 'true' in pushDownToL1(), but we must protect it backgroundPushedDown = true; } } // CASE 2: The task has been executed before (we have PAB images present in dataCurrent and PA images in backupL1) else { // Restoring from drive if not yet in memory if (!backupL1InMemory) { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from backup FITS in "+pathBackupL1, "image"); if (!headerInfoProvided) readImageBackupL1Launch(); // Right after launch, nothing is initialized and we must do that first using the full approach. else readImageBackupL1(); // Otherwise, we just read the data array. backgroundPushedDown = true; } } emit modelUpdateNeeded(chipName); } void MyImage::setupBackgroundData_newParallel(const bool &isTaskRepeated, const QString &backupDir) { if (!successProcessing) return; if (backgroundPushedDown) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images omp_set_lock(&backgroundLock); // Must not be done simultaneously dataCurrent_deletable = false; dataBackupL1_deletable = false; // CASE 1: The task has not been executed before if (!isTaskRepeated) { // Nothing is in backupL1 yet, either after restart, or because RAM is low. // No push-down has happened yet if (!backgroundPushedDown) { if (!minimizeMemoryUsage) { pushDownToL3(); pushDownToL2(); } readImage(true); // if not yet in memory pushDownToL1(backupDir); // Create a safe copy of the non-subtracted data dataBackupL1_deletable = false; // set to 'true' in pushDownToL1() backgroundPushedDown = true; } } // CASE 2: The task has been executed before (we have PAB images present in dataCurrent and PA images in backupL1) else { // Restoring from drive if not yet in memory if (!backupL1InMemory) { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from backup FITS in "+pathBackupL1, "image"); if (!headerInfoProvided) readImageBackupL1Launch(); // Right after launch, nothing is initialized and we must do that first using the full approach. else readImageBackupL1(); // Otherwise, we just read the data array. backgroundPushedDown = true; } } emit modelUpdateNeeded(chipName); omp_unset_lock(&backgroundLock); } // If a task is repeated, replace dataCurrent with the backup copy. // Otherwise continue with data current, and push down the backup data one level void MyImage::setupCalibDataInMemory(bool createBackup, bool determineMode, bool mustRereadFromDisk) { if (!successProcessing) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images // Restore level 1 backup (in case we reprocess the data). // Either get it from memory, or read it from disk // Backup only needed for FLATS (biases, darks and flatoff are not 'processed' at this point, but flats are bias-subtracted) if (backupL1InMemory) { // we are here only for flats; bias/darks are created without backup copy // TODO: this is not very safe. it would be better if we pass the Data type (BIAS, FLAT etc) along, and then // make the case distinctions concerning this value dataCurrent = dataBackupL1; imageInMemory = backupL1InMemory; } else { // In case of flats, the pixels were bias-subtracted. If the machine has low RAM, then "backupL1inMemory == false" // but it could be that "imageInMemory == true", then readImage() does not actually restore the original pixel values. // In this case, we must force a reread to refresh dataCurrent, but only for flats) if (mustRereadFromDisk) imageInMemory = false; readImage(determineMode); // Create backup copy, unless we don't need it (e.g. swarpfilter, or for bias/dark/flatoff) if (createBackup) { // true if not specified dataBackupL1 = dataCurrent; backupL1InMemory = true; } } emit modelUpdateNeeded(chipName); } // unused void MyImage::dumpToDriveIfPossible() { if (processingFinished && !imageOnDrive && imageInMemory) { writeImage(); unprotectMemory(); } } void MyImage::freeData(QVector &data) { data.clear(); data.squeeze(); if (&data == &dataCurrent) imageInMemory = false; else if (&data == &dataWeight) weightInMemory = false; else if (&data == &dataBackupL1) backupL1InMemory = false; else if (&data == &dataBackupL2) backupL2InMemory = false; else if (&data == &dataBackupL3) backupL3InMemory = false; emit modelUpdateNeeded(chipName); } void MyImage::freeData() { dataCurrent.clear(); dataCurrent.squeeze(); imageInMemory = false; emit modelUpdateNeeded(chipName); } // this happens only inside memoryLock set in the controller // MUST USE MEMORY LOCCK! float MyImage::freeData(QString type) { bool released = false; // If the image has never been loaded, this function will crash in several places. // Why is not clear to me, perhaps because some strings and e.g. databackground are not initialized; if (type == "dataBackground" && dataBackground_deletable && dataBackground.capacity() > 0) { // TODO / CHECK: comment these if causing problems dataBackground.clear(); dataBackground.squeeze(); backgroundModelDone = false; released = true; } else if (type == "dataBackupL1" && dataBackupL1_deletable && dataBackupL1.capacity() > 0) { dataBackupL1.clear(); dataBackupL1.squeeze(); backupL1InMemory = false; released = true; } else if (type == "dataBackupL2" && dataBackupL2_deletable && dataBackupL2.capacity() > 0) { dataBackupL2.clear(); dataBackupL2.squeeze(); backupL2InMemory = false; released = true; } else if (type == "dataBackupL3" && dataBackupL3_deletable && dataBackupL3.capacity() > 0) { dataBackupL3.clear(); dataBackupL3.squeeze(); backupL3InMemory = false; released = true; } else if (type == "dataWeight" && dataWeight_deletable && dataWeight.capacity() > 0) { // weights are always writtwen to drive (for swarp) dataWeight.clear(); dataWeight.squeeze(); weightInMemory = false; released = true; } else if (type == "dataCurrent" && dataCurrent_deletable && dataCurrent.capacity() > 0) { // Must write image to drive if not yet the case if (!imageOnDrive) { writeImage(); imageOnDrive = true; } dataCurrent.clear(); dataCurrent.squeeze(); imageInMemory = false; released = true; } else if (type == "all") { // used if a project is changed; release all memory if (dataBackground.capacity() > 0) { dataBackground.clear(); dataBackground.squeeze(); backgroundModelDone = false; } if (dataBackupL1.capacity() > 0) { dataBackupL1.clear(); dataBackupL1.squeeze(); backupL1InMemory = false; } if (dataBackupL2.capacity() > 0) { dataBackupL2.clear(); dataBackupL2.squeeze(); backupL2InMemory = false; } if (dataBackupL3.capacity() > 0) { dataBackupL3.clear(); dataBackupL3.squeeze(); backupL3InMemory = false; } if (dataWeight.capacity() > 0) { // weights are always writtwen to drive (for swarp) dataWeight.clear(); dataWeight.squeeze(); weightInMemory = false; } if (dataCurrent.capacity() > 0) { dataCurrent.clear(); dataCurrent.squeeze(); imageInMemory = false; } } emit modelUpdateNeeded(chipName); if (released) return naxis1*naxis2*sizeof(float) / 1024. / 1024.; else return 0.; } void MyImage::protectMemory() { // Nothing we might change during nominal processing may be touched dataCurrent_deletable = false; dataBackground_deletable = false; dataBackupL1_deletable = false; dataWeight_deletable = false; } // After an image was written to drive (or isn't needed right away elsewhere) we can set all memory to deletable void MyImage::unprotectMemory() { // Memory is up for grabs dataCurrent_deletable = true; dataBackground_deletable = true; dataBackupL1_deletable = true; dataBackupL2_deletable = true; dataBackupL3_deletable = true; dataWeight_deletable = true; } void MyImage::unprotectMemoryWeight() { // Memory is up for grabs dataWeight_deletable = true; } // UNUSED /* // Selective deletable status void MyImage::setDeletable(QString dataX, bool deletable) { if (dataX == "dataCurrent") dataCurrent_deletable = deletable; else if (dataX == "dataBackupL1") dataBackupL1_deletable = deletable; else if (dataX == "dataBackupL2") dataBackupL2_deletable = deletable; else if (dataX == "dataBackupL3") dataBackupL3_deletable = deletable; else if (dataX == "dataWeight") dataWeight_deletable = deletable; else if (dataX == "dataBackground") dataBackground_deletable = deletable; } */ void MyImage::releaseMemoryForBackground() { if (enteredBackgroundWindow && leftBackgroundWindow) { if (!backupL1OnDrive) writeImageBackupL1(); freeData("dataBackupL1"); if (minimizeMemoryUsage) freeAll(); } } void MyImage::unprotectMemoryForBackground() { if (enteredBackgroundWindow && leftBackgroundWindow) { dataBackupL1_deletable = true; dataBackground_deletable = true; if (minimizeMemoryUsage) freeAll(); // implies that we write the FITS image before calling this function! } } void MyImage::freeAncillaryData(QVector &data) { QVector().swap(data); } void MyImage::freeAll() { emit setMemoryLock(true); freeData(dataBackupL1); freeData(dataBackupL2); freeData(dataBackupL3); freeData(dataCurrent); freeData(dataWeight); emit modelUpdateNeeded(chipName); emit setMemoryLock(false); } THELI-3.1.3/src/myimage/myimage.cc000066400000000000000000001517771417631501300165640ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../processingStatus/processingStatus.h" #include "../instrumentdata.h" #include "wcs.h" #include "wcshdr.h" #include #include #include #include #include // C'tor MyImage::MyImage(QString pathname, QString filename, QString statusString, int chipnumber, const QVector &mask, int *verbose, QObject *parent) : QObject(parent), globalMask(mask) { path = pathname; name = filename; chipNumber = chipnumber; QFileInfo fi(path+"/"+name); if (globalMask.isEmpty()) globalMaskAvailable = false; baseName = fi.completeBaseName(); rootName = baseName; rootName.truncate(rootName.lastIndexOf('_')); chipName = rootName+"_"+QString::number(chipNumber); weightName = chipName+".weight"; processingStatus = new ProcessingStatus(path, this); processingStatus->statusString = statusString; processingStatus->statusToBoolean(processingStatus->statusString); if (! QFile(path+"/"+filename).exists()) { // A new file is being created validFile = false; validMode = false; validBackground = false; validDetector = false; } else { // An existing file is being read validFile = true; validMode = true; validBackground = true; validDetector = true; weightPath = path+"/../WEIGHTS/"; } verbosity = verbose; wcs = new wcsprm(); wcsInit = true; omp_init_lock(&backgroundLock); omp_init_lock(&objectLock); } void MyImage::checkTaskRepeatStatus(QString taskBasename) { isTaskRepeated = false; if (taskBasename == "HDUreformat" && processingStatus->HDUreformat) isTaskRepeated = true; else if (taskBasename == "Processscience" && processingStatus->Processscience) isTaskRepeated = true; else if (taskBasename == "Chopnod" && processingStatus->Chopnod) isTaskRepeated = true; else if (taskBasename == "Background" && processingStatus->Background) isTaskRepeated = true; else if (taskBasename == "Collapse" && processingStatus->Collapse) isTaskRepeated = true; else if (taskBasename == "Starflat" && processingStatus->Starflat) isTaskRepeated = true; else if (taskBasename == "Skysub" && processingStatus->Skysub) isTaskRepeated = true; } MyImage::MyImage(QString fullPathName, const QVector &mask, int *verbose, QObject *parent) : QObject(parent), globalMask(mask) { QFileInfo fi(fullPathName); path = fi.absolutePath(); name = fi.fileName(); chipNumber = 1; baseName = fi.completeBaseName(); rootName = baseName; rootName.truncate(rootName.lastIndexOf('_')); chipName = rootName+"_"+QString::number(chipNumber); weightName = baseName+".weight"; if (globalMask.isEmpty()) globalMaskAvailable = false; processingStatus = new ProcessingStatus(path); processingStatus->statusString = ""; processingStatus->statusToBoolean(processingStatus->statusString); if (! QFile(fullPathName).exists()) { // A new file is being created validFile = false; validMode = false; validBackground = false; validDetector = false; } else { // An existing file is being read validFile = true; validMode = true; validBackground = true; validDetector = true; // Create the FITS instance, but do not open and read it yet. weightPath = path; } verbosity = verbose; wcs = new wcsprm(); wcsInit = true; omp_init_lock(&backgroundLock); omp_init_lock(&objectLock); } MyImage::~MyImage() { for (auto &object : objectList) { delete object; object = nullptr; } if (wcsInit) wcsfree(wcs); if (wcsInit) { delete wcs; // valgrind does not like that wcs = nullptr; } int status = 0; if (fullheaderAllocated) fits_free_memory(fullheader, &status); delete processingStatus; processingStatus = nullptr; omp_destroy_lock(&backgroundLock); omp_destroy_lock(&objectLock); } void MyImage::setObjectLock(bool locked) { if (locked) omp_set_lock(&objectLock); else omp_unset_lock(&objectLock); } void MyImage::setBackgroundLock(bool locked) { if (locked) omp_set_lock(&backgroundLock); else omp_unset_lock(&backgroundLock); } void MyImage::updateProcInfo(QString text) { if (procInfo.isEmpty()) procInfo.append(text); else procInfo.append(", "+text); } void MyImage::showProcInfo() { if (*verbosity > 1) emit messageAvailable(chipName + " : " + procInfo, "image"); } void MyImage::checkCorrectMaskSize(const instrumentDataType *instData) { if (instData->name.contains("DUMMY")) return; long n_mask = globalMask.length(); long n_data = naxis1*naxis2; if (n_mask > 0 && n_mask != n_data) { QString part1 = "Data: XDIM="+QString::number(naxis1) + " YDIM="+QString::number(naxis2) +"\n" + "Config: XSIZE="+QString::number(instData->sizex[chipNumber]) + " YSIZE="+QString::number(instData->sizey[chipNumber]) +"\n"; emit messageAvailable("Inconsistent image size detected between data and instrument configuration" " (overscan and / or data section) in\n"+instData->nameFullPath+"\n"+part1, "error"); emit critical(); successProcessing = false; } } void MyImage::readImage(bool determineMode) { dataCurrent_deletable = false; dataWeight_deletable = false; // Leave if image is already loaded if (imageInMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(chipName+" : Already in memory", "image"); return; } else { if (loadData()) { getMode(determineMode); imageOnDrive = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(chipName+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImage(): Could not load " + baseName + ".fits", "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } } // Only needed for initialising the global weights void MyImage::readImageThreadSafe(bool determineMode) { dataCurrent_deletable = false; dataWeight_deletable = false; // Leave if image is already loaded if (imageInMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(chipName+" : Already in memory", "image"); return; } else { if (loadDataThreadSafe()) { getMode(determineMode); imageOnDrive = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(chipName+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImage(): Could not load " + baseName + ".fits", "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } } // Used by iview when loading directly from FITS files, by swarpfilter when reading weights, // and by color picture when cropping images void MyImage::readImage(QString loadFileName) { dataCurrent_deletable = false; dataWeight_deletable = false; // Leave if image is already loaded if (imageInMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(chipName+" : Already in memory", "image"); return; } else { if (loadData(loadFileName)) { imageOnDrive = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(chipName+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImage(): Could not load " + baseName + ".fits", "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } } bool MyImage::isActive() { if (activeState == MyImage::ACTIVE) return true; else return false; } // When having to read from a backup file right after launch (task repeated) void MyImage::readImageBackupL1Launch() { dataCurrent_deletable = false; dataWeight_deletable = false; dataBackupL1_deletable = false; QString loadFileName = pathBackupL1 + "/" + baseNameBackupL1 + ".fits"; if (loadData(loadFileName)) { bool determineMode = true; getMode(determineMode); dataBackupL1 = dataCurrent; backupL1OnDrive = true; backupL1InMemory = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(baseNameBackupL1+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImageBackupL1Launch(): Could not load " + baseNameBackupL1, "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } // when MyImage has been read before and all members are setup correctly, just the pixel data are missing. // This function is used if the pixel data were discarded due to memory constraints, and now they are needed again void MyImage::readImageBackupL1() { dataCurrent_deletable = false; dataBackupL1_deletable = false; // Leave if image is already loaded if (backupL1InMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(baseNameBackupL1+" : Already in memory", "image"); return; } else { QString backupName = pathBackupL1 + "/" + baseNameBackupL1 + ".fits"; QFile backupFile(backupName); if (!backupFile.exists()) { emit messageAvailable(baseName + " : Could not read data backup file " + pathBackupL1 + "/" + baseNameBackupL1 + " (does not exist)!", "error"); emit critical(); successProcessing = false; return; } int status = 0; long nelements = naxis1*naxis2; float *buffer = new float[nelements]; float nullval = 0.; int anynull; long fpixel = 1; fitsfile *fptr = nullptr; fits_open_file(&fptr, backupName.toUtf8().data(), READONLY, &status); fits_read_img(fptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); dataBackupL1.resize(nelements); for (long i=0; i= 2) emit messageAvailable(file.fileName() + ": " + file.errorString() + ", image deactivated", "warning"); setActiveState(MyImage::NOASTROM); return false; } } else { // mode == "inHeadersDir" file.setFileName(path+"/headers/"+rootName+"_"+QString::number(chip+1)+".head"); if (!file.open(QIODevice::ReadOnly)) { // emit messageAvailable("MyImage::scanAstromHeader(): " + file.fileName() + " " + file.errorString(), "error"); // emit critical(); emit messageAvailable(baseName + ": .head not found, image deactivated", "warning"); if (*verbosity >= 2) emit messageAvailable(file.fileName() + " " + file.errorString() + ", image deactivated", "warning"); setActiveState(MyImage::NOASTROM); // emit critical(); return false; } } double cd11_orig = wcs->cd[0]; double cd12_orig = wcs->cd[1]; double cd21_orig = wcs->cd[2]; double cd22_orig = wcs->cd[3]; QTextStream in(&file); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty()) continue; QStringList list = line.split("="); if (list.length() < 2) continue; QString value = list.at(1).simplified().split(" ").at(0); /*if (line.contains("CRVAL1")) wcs->crval[0] = list[2].toDouble(); if (line.contains("CRVAL2")) wcs->crval[1] = list[2].toDouble(); if (line.contains("CRPIX1")) wcs->crpix[0] = list[2].toFloat(); if (line.contains("CRPIX2")) wcs->crpix[1] = list[2].toFloat(); if (line.contains("CD1_1")) wcs->cd[0] = list[2].toDouble(); if (line.contains("CD1_2")) wcs->cd[1] = list[2].toDouble(); if (line.contains("CD2_1")) wcs->cd[2] = list[2].toDouble(); if (line.contains("CD2_2")) wcs->cd[3] = list[2].toDouble(); if (line.contains("FLXSCALE")) FLXSCALE = list[2].toFloat(); if (line.contains("RZP")) RZP = list[2].toFloat(); */ if (line.contains("CRVAL1")) wcs->crval[0] = value.toDouble(); if (line.contains("CRVAL2")) wcs->crval[1] = value.toDouble(); if (line.contains("CRPIX1")) wcs->crpix[0] = value.toFloat(); if (line.contains("CRPIX2")) wcs->crpix[1] = value.toFloat(); if (line.contains("CD1_1")) wcs->cd[0] = value.toDouble(); if (line.contains("CD1_2")) wcs->cd[1] = value.toDouble(); if (line.contains("CD2_1")) wcs->cd[2] = value.toDouble(); if (line.contains("CD2_2")) wcs->cd[3] = value.toDouble(); if (line.contains("FLXSCALE")) FLXSCALE = value.toFloat(); if (line.contains("RZP")) RZP = value.toFloat(); } file.close(); // Do not update the WCS matrix if it is significantly flawed if (sanityCheckWCS(wcs).isEmpty()) { wcs->flag = 0; // Trigger recomputation cornersToRaDec(); updateCRVALCRPIXCDinHeader(); emit WCSupdated(); return true; } else { // Restore original values wcs->cd[0] = cd11_orig; wcs->cd[1] = cd12_orig; wcs->cd[2] = cd21_orig; wcs->cd[3] = cd22_orig; cornersToRaDec(); return false; } } void MyImage::checkWCSsanity() { // Do not update the WCS matrix if it is significantly flawed if (sanityCheckWCS(wcs).isEmpty()) return; else { wcs->cd[0] = -1.*plateScale/3600.; wcs->cd[1] = 0.; wcs->cd[2] = 0.; wcs->cd[3] = plateScale/3600.; wcs->flag = 0; updateCRVALCDinHeader(); updateCRVALCDinHeaderOnDrive(); emit messageAvailable("Singular or skewed CD matrix detected, reset to default values!", "warning"); emit warning(); } } void MyImage::backupOrigHeader(int chip) { QDir dir(path+ "/.origheader_backup/"); dir.mkpath(path+ "/.origheader_backup/"); // DO NOT OVERWRITE EXISTING BACKUP COPY QFile file(path+"/.origheader_backup/"+rootName+"_"+QString::number(chip+1)+".origastrom.head"); if (file.exists()) return; // Backup copy does not exist, create it if(!file.open(QIODevice::WriteOnly)) { emit messageAvailable("MyImage::backupOrigHeader(): " + file.fileName() + " " + file.errorString(), "error"); emit critical(); return; } QTextStream stream(&file); fitsfile *fptr; int status = 0; int nkeys = 0; int keypos = 0; char card[FLEN_CARD]; // Must read from pathBackupL1 QString filename = pathBackupL1+"/"+baseNameBackupL1+".fits"; // QString filename = path+"/"+baseName+".fits"; fits_open_file(&fptr, filename.toUtf8().data(), READWRITE, &status); fits_get_hdrpos(fptr, &nkeys, &keypos, &status); // get number of keywords for (int i=1; i<=nkeys; ++i) { fits_read_record(fptr, i, card, &status); stream << card << "\n"; } if (status == END_OF_FILE) status = 0; else { printCfitsioError(__func__, status); } fits_close_file(fptr, &status); file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } void MyImage::replaceCardInFullHeaderString(QString keyname, double value) { QString card = keyname; card.resize(8, ' '); card.append("= "); card.append(QString::number(value, 'g', 12)); card.resize(80, ' '); long dim = strlen(fullheader); for (long i=0; i 1) emit messageAvailable(chipName + " : " + skyvalue, "image"); skyvalue.resize(80,' '); // header is empty when running equalizeBayerFlat if (!doesHeaderContain("SKYVALUE=") && !header.isEmpty()) { header.insert(header.end()-1, skyvalue); } } bool MyImage::doesHeaderContain(QString keyword) { for (auto &it : header) { if (it.contains(keyword)) return true; } return false; } void MyImage::updateHeaderValue(QString keyName, float keyValue, char format) { if (!successProcessing) return; QString card = keyName; card.resize(8, ' '); card.append("= "); QString keyword = card; card.append(QString::number(keyValue, format, 6)); card.resize(80, ' '); if (!doesHeaderContain(keyword) && !header.isEmpty()) { header.insert(header.end()-1, card); } else { for (auto &it : header) { if (it.contains(keyword)) { // Replace old entry it = card; break; } } } } void MyImage::updateHeaderValue(QString keyName, double keyValue, char format) { if (!successProcessing) return; QString card = keyName; card.resize(8, ' '); card.append("= "); QString keyword = card; card.append(QString::number(keyValue, format, 12)); card.resize(80, ' '); if (!doesHeaderContain(keyword) && !header.isEmpty()) { header.insert(header.end()-1, card); } else { for (auto &it : header) { if (it.contains(keyword)) { it = card; // Replace old keyword break; } } } } void MyImage::updateHeaderValue(QString keyName, QString keyValue) { if (!successProcessing) return; QString card = keyName; card.resize(8, ' '); card.append("= "); QString keyword = card; card.append(keyValue); card.resize(80, ' '); if (!doesHeaderContain(keyword) && !header.isEmpty()) { header.insert(header.end()-1, card); } else { for (auto &it : header) { if (it.contains(keyword)) { // Replace old entry it = card; break; } } } } void MyImage::updateHeaderSaturation() { updateHeaderValue("SATURATE", saturationValue); } void MyImage::updateHeaderValueInFITS(QString keyName, QString keyValue) { if (!successProcessing) return; // Don't do anything if file doesn't exist on drive QFile file(path+"/"+name); if (!file.exists()) return; int status = 0; fitsfile *fptr = nullptr; fits_open_file(&fptr, (path+"/"+name).toUtf8().data(), READWRITE, &status); fits_update_key_str(fptr, keyName.toUtf8().data(), keyValue.toUtf8().data(), nullptr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } double MyImage::getPlateScale() { if (!wcsInit) { if (*verbosity > 2) emit messageAvailable(chipName + " : No WCS. PlateScale set to 1.0", "info"); return 1.0; } // replace with sth more sophisticated plateScale = sqrt(wcs->cd[0] * wcs->cd[0] + wcs->cd[2] * wcs->cd[2]) * 3600.; if (plateScale == 0.) plateScale = 1.0; return plateScale; } void MyImage::getMode(bool determineMode) { if (!successProcessing) return; // Get the mode only if requested, and measure it only if it hasn't been measured already // (in which case it is available as the SKYVALUE header keyword) if (determineMode && !modeDetermined) { if (!imageInMemory) loadData(); skyValue = modeMask(dataCurrent, "stable", globalMask)[0]; modeDetermined = true; QString skyvalue = "SKYVALUE= "+QString::number(skyValue); if (*verbosity > 1) emit messageAvailable(chipName + " : " + skyvalue, "image"); skyvalue.resize(80,' '); if (!header.isEmpty()) { if (!doesHeaderContain("SKYVALUE=")) { header.insert(header.end()-1, skyvalue); } } else { emit messageAvailable("MyImage::getMode():" + baseName + " : header vector is empty.", "error"); successProcessing = false; } } } // Flag the image if its mode is outside the acceptable range void MyImage::setModeFlag(QString min, QString max) { if (!successProcessing) return; if (min.isEmpty() && max.isEmpty()) return; if (!modeDetermined) { // TODO: implement mode() for integer FITS files, and measure it here (raw data, e.g. darks or flats) return; } else { validMode = true; if (!min.isEmpty() && skyValue < min.toFloat()) validMode = false; if (!max.isEmpty() && skyValue > max.toFloat()) validMode = false; if (!validMode) { if (*verbosity > 1) emit messageAvailable(chipName + " : Mode = " + QString::number(skyValue,'f',3) + " outside user-defined limits ["+min+","+max+"]", "output"); } successProcessing = true; } } // does the same as "updateHeaderValue()" void MyImage::updateKeywordInHeader(QString key, QString value) { for (auto &it : header) { if (!it.contains("=")) continue; QStringList list = it.split("="); QString keyword = list[0]; // QString value = list[1].simplified(); if (keyword.simplified() == key) { it = keyword+"= "+value; // pad with empty chars until 80 chars long while (it.length() < 80) { it.append(' '); } return; } } } // Here, 'biasData' may also refer to a dark or flatoff image //void MyImage::subtractBias(MyImage *&biasImage, QString dataType) void MyImage::subtractBias(const MyImage *biasImage, QString dataType) { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the bias was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { pixel -= biasImage->dataCurrent.at(i); // pixel -= 0.; // testing memory accumulation ++i; } saturationValue -= biasImage->skyValue; updateHeaderValue("SATURATE", saturationValue); QString mode = ""; if (dataType == "BIAS") mode = "bias subtracted"; else if (dataType == "DARK") mode = "dark subtracted"; else if (dataType == "FLATOFF") mode = "flatoff subtracted"; else { // nothing } if (*verbosity > 1) emit messageAvailable(chipName + " : "+mode, "image"); successProcessing = true; } // UNUSED, for memory testing // Here, 'biasData' may also refer to a dark or flatoff image void MyImage::subtractBias(QVector const &dataCorr, QString dataType) { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the bias was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { pixel -= dataCorr.at(i); ++i; } QString mode = ""; if (dataType == "BIAS") mode = "bias subtracted"; else if (dataType == "DARK") mode = "dark subtracted"; else if (dataType == "FLATOFF") mode = "flatoff subtracted"; else { // nothing } if (*verbosity > 1) emit messageAvailable(chipName + " : "+mode, "image"); successProcessing = true; } // UNUSED, for memory testing // Here, 'biasData' may also refer to a dark or flatoff image /* void MyImage::subtractBias() { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the bias was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { pixel -= 0.; ++i; } } */ void MyImage::divideFlat(const MyImage *flatImage) { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the flat was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { // Divide by flat, and correct for gain differences pixel /= (flatImage->dataCurrent.at(i) * flatImage->gainNormalization); // NaN pixels slow down SourceExtractor enourmously (and make it fail). // we can probably get rid of this once we have completely thrown out SourceExtractor if (std::isnan(pixel) || std::isinf(pixel)) pixel = 0.; ++i; } saturationValue /= flatImage->gainNormalization; updateHeaderValue("SATURATE", saturationValue); if (*verbosity > 1) emit messageAvailable(chipName + " : Flat fielded", "image"); successProcessing = true; } void MyImage::applyBackgroundModel(const MyImage *backgroundImage, QString mode, bool rescaleFlag) { if (!successProcessing) return; long i = 0; if (mode == "Subtract model" ) { float rescale = 1.0; if (rescaleFlag) rescale = skyValue / backgroundImage->skyValue; for (auto &pixel : dataCurrent) { if (backgroundImage->dataCurrent.at(i) != 0.) { pixel = dataBackupL1.at(i) - backgroundImage->dataCurrent.at(i) * rescale; } else { pixel = 0.; } ++i; } saturationValue -= backgroundImage->skyValue * rescale; updateHeaderValue("SATURATE", saturationValue); QString img = " IMG = "+QString::number(skyValue, 'f', 3) + ";"; QString back = " BACK = "+QString::number(backgroundImage->skyValue, 'f', 3) + ";"; QString fac = " rescale = "+QString::number(rescale, 'f', 3); if (*verbosity > 1) emit messageAvailable(chipName + " : Background model subtracted;"+img+back+fac, "image"); } else if (mode == "Divide model") { // rescaling switched off. Background image is always normalized to its own mode for (auto &pixel : dataCurrent) { if (backgroundImage->dataCurrent.at(i) != 0) { pixel = dataBackupL1.at(i) / (backgroundImage->dataCurrent.at(i) / backgroundImage->skyValue); } else { pixel = backgroundImage->skyValue; } ++i; } // No normalization of saturation keyword required // saturationValue /= backgroundImage->skyValue; updateHeaderValue("SATURATE", saturationValue); QString img = " IMG = "+QString::number(skyValue, 'f', 3) + ";"; QString back = " BACK = "+QString::number(backgroundImage->skyValue, 'f', 3) + ";"; if (*verbosity > 1) emit messageAvailable(chipName + " : Divided by normalized background model;"+img+back, "image"); } successProcessing = true; } // Normalize Flat to one. Gain differences are corrected separately. void MyImage::normalizeFlat() { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Normalizing flat field, dividing by "+QString::number(skyValue, 'f', 3), "image"); for (auto &pixel : dataCurrent) { pixel /= skyValue; } successProcessing = true; } // Normalize Flat to one. Gain differences are corrected separately. void MyImage::illuminationCorrection(int chip, QString thelidir, QString instName, QString filter) { if (!successProcessing) return; // It is ok to look up and read the illum correction files in MyImage (instead of Controller) // because it is applied to the master flat, and therefore executed only once. // If we applied it to every science frame, then it would be better to implement it in Controller // so it gets executed only once // TODO: must provide in distribution? QString illumcorrPath = thelidir+"/ExtCal/"+instName+"/illumcorr/"; QString illumcorrFileName = "illumcorr_"+filter+"_"+QString::number(chip)+".fits"; if (QFile(illumcorrPath+illumcorrFileName).exists()) { if (*verbosity > 1) emit messageAvailable(chipName + " : External illumination correction :
" + illumcorrPath+illumcorrFileName, "image"); QVector dummyMask; dummyMask.clear(); MyImage *illumCorrFlat = new MyImage(illumcorrPath, illumcorrFileName, "", chip+1, dummyMask, verbosity); illumCorrFlat->readImage(); if (naxis1 != illumCorrFlat->naxis1 || naxis2 != illumCorrFlat->naxis2 ) { emit messageAvailable("MyImage::illuminationCorrection(): " + baseName + " : illumination correction image does not have the same size as the master flat!", "error"); emit critical(); successProcessing = false; } else { long i = 0; for (auto &pixel : dataCurrent) { pixel *= illumCorrFlat->dataCurrent.at(i); ++i; } successProcessing = true; } delete illumCorrFlat; illumCorrFlat = nullptr; } } void MyImage::collapseCorrection(QString threshold, QString direction) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Collapse correction along " + direction, "image"); if (direction == "x") { static_cast (collapse_x(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else if (direction == "y") { static_cast (collapse_y(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else if (direction == "xy") { static_cast (collapse_x(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); static_cast (collapse_y(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else if (direction == "yx") { static_cast (collapse_y(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); static_cast (collapse_x(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else { static_cast (collapse_quad(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, direction, "2Dsubtract")); } } QVector MyImage::extractPixelValues(long xmin, long xmax, long ymin, long ymax) { // CHECK: if not in memory then load from drive if (xmin < 0) xmin = 0; if (xmax >= naxis1-1) xmax = naxis1-1; if (ymin < 0) ymin = 0; if (ymax >= naxis2-1) ymax = naxis2-1; long nsub = xmax - xmin + 1; long msub = ymax - ymin + 1; QVector section; /* section.reserve(nsub*msub); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { section.append(dataCurrent[i+naxis1*j]); } } */ section.resize(nsub*msub); long k = 0; for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { section[k] = dataCurrent.at(i+naxis1*j); ++k; } } return section; } void MyImage::makeCutout(long xmin, long xmax, long ymin, long ymax) { long nsub = xmax - xmin + 1; long msub = ymax - ymin + 1; QVector dataCut; /* dataCut.reserve(nsub*msub); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { dataCut.append(dataCurrent[i+naxis1*j]); } } */ long k = 0; dataCut.resize(nsub*msub); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { dataCut[k] = dataCurrent.at(i+naxis1*j); ++k; } } naxis1 = nsub; naxis2 = msub; if (wcsInit) { wcs->crpix[0] = wcs->crpix[0] - xmin + 1; wcs->crpix[1] = wcs->crpix[1] - ymin + 1; wcs->flag = 0; } dataCurrent.swap(dataCut); } // UNUSED float MyImage::polynomialSum(float x, QVector coefficients) { // Coefficients contains the coeffs of a polynomial, starting with the lowest term // e.g., for p(x) = c0 + c1*x + c2*x*x we have coefficients = [c0, c1, c2] float sum = 0.; int k = 0; for (auto & it : coefficients) { sum += it * pow(x, k); ++k; } return sum; } void MyImage::removeSourceCatalogs() { QString catName = path+"/cat/"+chipName+".cat"; QFile catFile1(catName); if (catFile1.exists()) catFile1.remove(); catName = path+"/cat/"+chipName+".anet"; QFile catFile2(catName); if (catFile2.exists()) catFile2.remove(); } // This routine is used when reading an external image // (and possibly its existing weight in the same directory, such as a pair of coadd.fits and coadd.weight.fits) // So far only used for creating astrometric reference catalogs void MyImage::setupCoaddMode() { readImage(path+"/"+name); // Setup an empty dummy globalMask // globalMask = QVector(); globalMaskAvailable = false; // Load a matching weight image, if one exists // weightName.append(".fits"); weightName = baseName + ".weight.fits"; QFile file(path+"/"+weightName); if (!file.exists()) return; QVector dummyMask; dummyMask.clear(); MyImage *myWeight = new MyImage(path, weightName, "", 1, dummyMask, verbosity); myWeight->readImage(); dataWeight.swap(myWeight->dataCurrent); delete myWeight; myWeight = nullptr; } void MyImage::updateZeroOrderOnDrive(QString updateMode) { if (!successProcessing) return; if (!imageOnDrive) return; // Must write file to disk (scamp reads the header information) if it does not exist yet // QFile file(path+ "/" + baseName + ".fits"); // if (!file.exists()) writeImage(path+ "/" + baseName + ".fits"); int status = 0; char zerohead[80] = {0}; QString zeroheadString = ""; fitsfile *fptr = nullptr; fits_open_file(&fptr, (path+"/"+chipName+processingStatus->statusString+".fits").toUtf8().data(), READWRITE, &status); fits_read_key_str(fptr, "ZEROHEAD", zerohead, nullptr, &status); if (status > 0) { // Add the key if it doesn't exist // Not used for anything, just informative fits_update_key_str(fptr, "ZEROHEAD", "NO", "Astrometric header update", &status); // reset the update flag zeroheadString = "NO"; status = 0; } else zeroheadString.fromLatin1(zerohead); fits_update_key_dbl(fptr, "CRVAL1", wcs->crval[0], 9, nullptr, &status); fits_update_key_dbl(fptr, "CRVAL2", wcs->crval[1], 9, nullptr, &status); fits_update_key_flt(fptr, "CRPIX1", wcs->crpix[0], 3, nullptr, &status); fits_update_key_flt(fptr, "CRPIX2", wcs->crpix[1], 3, nullptr, &status); fits_update_key_dbl(fptr, "CD1_1", wcs->cd[0], 9, nullptr, &status); fits_update_key_dbl(fptr, "CD1_2", wcs->cd[1], 9, nullptr, &status); fits_update_key_dbl(fptr, "CD2_1", wcs->cd[2], 9, nullptr, &status); fits_update_key_dbl(fptr, "CD2_2", wcs->cd[3], 9, nullptr, &status); if (std::isnan(RZP)) { RZP = 0.; FLXSCALE = 0.0; emit messageAvailable(chipName + " : Scamp could not determine the relative zeropoint. Set to 0!", "error"); emit critical(); } fits_update_key_flt(fptr, "RZP", RZP, 5, nullptr, &status); fits_update_key_flt(fptr, "FLXSCALE", FLXSCALE, 5, nullptr, &status); if (updateMode == "restore") { fits_update_key_str(fptr, "ZEROHEAD", "NO", "Astrometric header update", &status); // reset the update flag } else { // updateMode == "update" fits_update_key_str(fptr, "ZEROHEAD", "YES", "Astrometric header update", &status); // reset the update flag } fits_close_file(fptr, &status); printCfitsioError(__func__, status); } /* void MyImage::updateZeroOrderInMemory() { if (!successProcessing) return; // Update the data in memory // WCSLIB threading issue (probably solved by wcsLock in initWCS() // Can be removed if we don't see this again if (wcs->naxis != 2) { emit messageAvailable(chipName + " : MyImage::updateZeroOrder(): Incompatible NAXIS WCS dimension: " + QString::number(wcs->naxis) + ", attempting reload (actually, this is a bug!)", "warning"); imageInMemory = false; readImage(false); if (wcs->naxis != 2) { emit messageAvailable(chipName + " : Reload failed!", "error"); return; } else { emit messageAvailable(chipName + " : Reload success!", "note"); } } cornersToRaDec(); } */ // Update the 'header' QVector passed onto any newly written FITS file void MyImage::updateCRVALinHeader() { updateHeaderValue("CRVAL1", wcs->crval[0]); updateHeaderValue("CRVAL2", wcs->crval[1]); } // Update the 'header' QVector passed onto any FITS file written in the future void MyImage::updateCRVALCDinHeader() { updateHeaderValue("CRVAL1", wcs->crval[0]); updateHeaderValue("CRVAL2", wcs->crval[1]); updateHeaderValue("CD1_1", wcs->cd[0], 'e'); updateHeaderValue("CD1_2", wcs->cd[1], 'e'); updateHeaderValue("CD2_1", wcs->cd[2], 'e'); updateHeaderValue("CD2_2", wcs->cd[3], 'e'); } // Update the 'header' QVector passed onto any FITS file written in the future void MyImage::updateCRVALCRPIXCDinHeader() { updateHeaderValue("CRVAL1", wcs->crval[0]); updateHeaderValue("CRVAL2", wcs->crval[1]); updateHeaderValue("CRPIX1", wcs->crpix[0]); updateHeaderValue("CRPIX2", wcs->crpix[1]); updateHeaderValue("CD1_1", wcs->cd[0], 'e'); updateHeaderValue("CD1_2", wcs->cd[1], 'e'); updateHeaderValue("CD2_1", wcs->cd[2], 'e'); updateHeaderValue("CD2_2", wcs->cd[3], 'e'); } void MyImage::updateCRVALinHeaderOnDrive() { // Must write file to drive (scamp reads the header information) if it does not exist yet QString outfile = path+"/"+chipName+processingStatus->statusString+".fits"; // QFile file(path+ "/" + baseName + ".fits"); QFile file(outfile); if (!file.exists()) writeImage(outfile); int status = 0; fitsfile *fptr = nullptr; fits_open_file(&fptr, (outfile).toUtf8().data(), READWRITE, &status); fits_update_key_dbl(fptr, "CRVAL1", wcs->crval[0], 6, nullptr, &status); fits_update_key_dbl(fptr, "CRVAL2", wcs->crval[1], 6, nullptr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } void MyImage::updateCRVALCDinHeaderOnDrive() { // Must write file to disk (scamp reads the header information) if it does not exist yet QString outfile = path+"/"+chipName+processingStatus->statusString+".fits"; QFile file(outfile); if (!file.exists()) writeImage(outfile); int status = 0; fitsfile *fptr = nullptr; fits_open_file(&fptr, (outfile).toUtf8().data(), READWRITE, &status); fits_update_key_dbl(fptr, "CRVAL1", wcs->crval[0], 6, nullptr, &status); fits_update_key_dbl(fptr, "CRVAL2", wcs->crval[1], 6, nullptr, &status); fits_update_key_flt(fptr, "CD1_1", wcs->cd[0], 6, nullptr, &status); fits_update_key_flt(fptr, "CD1_2", wcs->cd[1], 6, nullptr, &status); fits_update_key_flt(fptr, "CD2_1", wcs->cd[2], 6, nullptr, &status); fits_update_key_flt(fptr, "CD2_2", wcs->cd[3], 6, nullptr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } void MyImage::updateInactivePath() { if (activeState == MyImage::ACTIVE) pathExtension = ""; else if (activeState == MyImage::INACTIVE) pathExtension = "/inactive/"; else if (activeState == MyImage::BADSTATS) pathExtension = "/inactive/badStatistics/"; else if (activeState == MyImage::BADBACK) pathExtension = "/inactive/badBackground/"; else if (activeState == MyImage::NOASTROM) pathExtension = "/inactive/noAstrometry/"; else if (activeState == MyImage::LOWDETECTION) pathExtension = "/inactive/lowDetections/"; else if (activeState == MyImage::DELETED) pathExtension = "/inactive/"; } void MyImage::applyMask() { // Leave if the chip has no mask (save some CPU cycles) if (!globalMaskAvailable) return; if (globalMask.length() != dataCurrent.length()) { emit messageAvailable("MyImage::applyMask(): " + baseName + " : inconsistent sizes of mask and image", "error"); emit critical(); return; } long i=0; for (auto &it : dataCurrent) { if (globalMask[i]) it = maskValue; ++i; } } QString MyImage::getKeyword(QString key) { QString value; key.resize(8,' '); for (auto &it : header) { if (it.contains(key)) { value = it.split("=")[1].split("/")[0].simplified().remove("'"); break; } } return value; } void MyImage::messageAvailableReceived(QString message, QString type) { if (type == "error" || type == "stop") { emit messageAvailable(message, type); emit critical(); } else { if (*verbosity > 1) emit messageAvailable(message, type); } } void MyImage::anetOutputReceived(QString message, QString type) { if (type == "error" || type == "stop") { emit messageAvailable(message, type); emit critical(); } else { if (*verbosity >= 1) emit messageAvailable(message, type); } } QVector MyImage::extractCDmatrix() { QVector cd; cd.push_back(getKeyword("CD1_1").toDouble()); cd.push_back(getKeyword("CD1_2").toDouble()); cd.push_back(getKeyword("CD2_1").toDouble()); cd.push_back(getKeyword("CD2_2").toDouble()); return cd; } // TODO: update to use wcslib functions void MyImage::checkBrightStars(const QList> &brightStarList, float safetyDistance, float plateScale) { if (!successProcessing) return; hasBrightStars = false; // Loop over all bright stars and check whether they are inside the chip for (auto &it : brightStarList) { QVector raVec; QVector decVec; // order is important! we don't want a line crossing in the polygon line raVec << alpha_ll << alpha_lr << alpha_ur << alpha_ul; decVec << delta_ll << delta_lr << delta_ur << delta_ul; double alpha = it.at(0); double delta = it.at(1); if (pnpoly_T(raVec, decVec, alpha, delta)) { hasBrightStars = true; return; } } // if we are still here, then check for bright stars outside the chip // within the minimum safety distance safetyDistance *= (60. / plateScale); // convert to pixel for (auto &it : brightStarList) { double xstar; double ystar; double alpha = it.at(0); double delta = it.at(1); sky2xy(alpha, delta, xstar, ystar); if (xstar > -1*safetyDistance && xstar < naxis1+safetyDistance && ystar > -1*safetyDistance && ystar < naxis2+safetyDistance) { hasBrightStars = true; return; } } } bool MyImage::containsRaDec(QString alphaStr, QString deltaStr) { loadHeader(); // if not yet provided, e.g. UI was just started and we are doing a coadd // Convert to decimal if required if (alphaStr.contains(":")) alphaStr = hmsToDecimal(alphaStr); if (deltaStr.contains(":")) deltaStr = dmsToDecimal(deltaStr); double x = 0.; double y = 0.; sky2xy(alphaStr.toDouble(), deltaStr.toDouble(), x, y); if (x > 0. && x < naxis1-1 && y > 0. && y < naxis2-1) return true; else return false; /* * pnpoly() does not work if the image crosses the RA=0|360 boundary. Must use wcslib (see code above) double alpha_ul; double alpha_ur; double alpha_ll; double alpha_lr; double delta_ul; double delta_ur; double delta_ll; double delta_lr; xy2sky(1, 1, alpha_ll, delta_ll); xy2sky(naxis1, 1, alpha_lr, delta_lr); xy2sky(1, naxis2, alpha_ul, delta_ul); xy2sky(naxis1, naxis2, alpha_ur, delta_ur); // Check if the sky coordinates are contained in this picture frame QVector raVec; QVector decVec; // order is important! we don't want a line crossing in the polygon line raVec << alpha_ll << alpha_lr << alpha_ur << alpha_ul; decVec << delta_ll << delta_lr << delta_ur << delta_ul; // Convert to decimal if required if (alphaStr.contains(":")) alphaStr = hmsToDecimal(alphaStr); if (deltaStr.contains(":")) deltaStr = dmsToDecimal(deltaStr); return pnpoly_T(raVec, decVec, alphaStr.toDouble(), deltaStr.toDouble()); */ } bool MyImage::containsRaDec(double alpha, double delta) { loadHeader(); // if not yet provided, e.g. UI was just started and we are doing a coadd double x = 0.; double y = 0.; sky2xy(alpha, delta, x, y); if (x > 0. && x < naxis1-1 && y > 0. && y < naxis2-1) return true; else return false; /* double alpha_ul; double alpha_ur; double alpha_ll; double alpha_lr; double delta_ul; double delta_ur; double delta_ll; double delta_lr; // Convert the cartesian image vertices to RA/DEC loadHeader(); // if not yet provided, e.g. UI was just started and we are doing a coadd xy2sky(1, 1, alpha_ll, delta_ll); xy2sky(naxis1, 1, alpha_lr, delta_lr); xy2sky(1, naxis2, alpha_ul, delta_ul); xy2sky(naxis1, naxis2, alpha_ur, delta_ur); // Check if the sky coordinates are contained in this picture frame QVector raVec; QVector decVec; // order is important! we don't want a line crossing in the polygon line raVec << alpha_ll << alpha_lr << alpha_ur << alpha_ul; decVec << delta_ll << delta_lr << delta_ur << delta_ul; return pnpoly_T(raVec, decVec, alpha, delta); */ } void MyImage::cornersToRaDec() { xy2sky(0., 0., alpha_ll, delta_ll); xy2sky(naxis1-1., 0., alpha_lr, delta_lr); xy2sky(0., naxis2-1., alpha_ul, delta_ul); xy2sky(naxis1-1., naxis2-1., alpha_ur, delta_ur); xy2sky(naxis1/2.-1., naxis2/2.-1., alpha_ctr, delta_ctr); } // UNUSED /* QVector MyImage::retainUnmaskedDataThresholded(float minVal, float maxVal, int sampleDensity) { if (sampleDensity == 0) sampleDensity = 1; QVector dataThresholded; long n = dataCurrent.length(); dataThresholded.reserve(n/sampleDensity); if (!globalMask.isEmpty()) { for (long i=0; i minVal && it < maxVal && !globalMask[i]) { dataThresholded.append(it); } } } else { for (long i=0; i minVal && it < maxVal) { dataThresholded.append(it); } } } return dataThresholded; } QVector MyImage::retainUnmaskedData(int sampleDensity) { if (sampleDensity == 0) sampleDensity = 1; QVector dataThresholded; long n = dataCurrent.length(); dataThresholded.reserve(n/sampleDensity); if (!globalMask.isEmpty()) { for (long i=0; istatusString != processingStatus->whatIsStatusOnDrive()) { // } } */ // Move the image accordingly QString currentPath = path + pathExtension; // The path where the image is currently located (if on disk) updateInactivePath(); // Update pathextension according to the set state QString newPath = path + pathExtension; // The path where the image should go if (!imageOnDrive) return; moveFile(baseName+".fits", currentPath, newPath); } void MyImage::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("MyImage::"+funcName+":
" + baseName + " : " + errorCodes->errorKeyMap.value(status), "error"); emit critical(); successProcessing = false; } } THELI-3.1.3/src/myimage/myimage.h000066400000000000000000000567321417631501300164210ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYIMAGE_H #define MYIMAGE_H #include "../tools/detectedobject.h" #include "../threading/sourceextractorworker.h" #include "../threading/anetworker.h" #include "../processingStatus/processingStatus.h" #include "../instrumentdata.h" #include "fitsio2.h" #include #include #include #include // This class keeps track of an individual image, its memory/disk state, // processing status, previous processing states, file name, FITS file handles, // associated weight and mask images, geometry, filter, exposure time, seeing // and RZP class MyImage : public QObject { Q_OBJECT private: void stayWithinBounds(QVector &vertices); void stayWithinBounds(long &coord, QString axis); float polynomialSum(float x, QVector coefficients); // ================= BACKGROUND MODELING =========================== long nGridPoints = 0; // Number of grid points int gridStep = 0; // Linear distance between grid points int filterSize = 0; // spatial scale on which the image should be filtered int subSample = 1; // GSL The factor by which the grid should be subSampled; at least twice the kernel width int n_grid = 0; // number of grid points along naxis1 int m_grid = 0; // number of grid points along naxis2 int pad_l = 0; // number of pad pixels left edge; same as padWidth w int pad_b = 0; // number of pad pixels bottom edge; same as padWidth w int pad_r = 0; // number of pad pixels right edge; same as padWidth w unless +1 to make even dimension int pad_t = 0; // number of pad pixels top edge; same as padWidth w unless +1 to make even dimension long n_pad = 0; // NAXIS1 of the padded image long m_pad = 0; // NAXIS2 of the padded image QString splineMode = "smooth"; // "smooth" or "interpolate" QString padMode = "normal"; // Whether the image is padded "normal" or "dyadic" QVector backStatsGrid; // the statistics for the grid (background value for each grid point) QVector rmsStatsGrid; // the statistics for the grid (rms value for each grid point) QVector> grid; // the grid on which we calculate statistics QVector padDims; // contains left, bottom, right, top pad dimensions, and then overall n_pad and m_pad int numExt = 1; // Number of etensions in a FITS file void planGrid(); void getGridStatistics(); void filterGridStatistics(); void fitBackgroundGSL(); void getPadDimensions(); void padImage(); void padCorner(int width, QString corner, long ipadmin, long ipadmax, long jpadmin, long jpadmax); void padEdgeLR(int width, QString edge, long ipadmin, long ipadmax, long jpadmin, long jpadmax); void padEdgeBT(int width, QString edge, long ipadmin, long ipadmax, long jpadmin, long jpadmax); int padCorr(int i, int w, int max); void replaceBlankGridStatistics(); void clearBackgroundMemory(); // void backgroundModel(int filtersize, QString splinemode); public function // ================================================================= // ================== Image segmentation =========================== void thresholdImage(); bool insideImage(QPoint p); void floodFill(const QPoint startPoint, QList &objectPixelIndices, long &objID, QVector &dataSegmentation, const long DMIN); QVector directConvolve(const QVector &data); void writeObjectMask(QString fileName); // ================================================================= QVector locateSkyNode(const double alpha, const double delta, const double radius); void printCfitsioError(QString funcName, int status); void median2D(const QVector &data_in, QVector &data_out, int filtersize); void pushDownToL3(); void pushDownToL2(); void pushDownToL1(QString backupDir); void pullUpFromL1(); void pullUpFromL2(); void pullUpFromL3(); void wipeL1(); void wipeL2(); void wipeL3(); void readImageBackupL1(); void replaceCardInFullHeaderString(QString keyname, double value); void readHeader(fitsfile **fptr, int *status); void extractKeywordDouble(QString card, QString key, double &value); void extractKeywordFloat(QString card, QString key, float &value); void extractKeywordLong(QString card, QString key, long &value); void extractKeywordInt(QString card, QString key, int &value); void extractKeywordString(QString card, QString key, QString &value); void initTHELIheader(int *status); void checkTHELIheader(int *status); void propagateHeader(fitsfile *fptr, QVector header); bool write(QString fileName, const QVector &data, const float exptime, const QString filter, const QVector header); void writeConstImage(QString fileName, const float constValue, const QVector header); bool writeDebayer(QString fileName, const float exptime, const QString filter, const QVector header); void writeSegmentation(QString fileName); void readDataWeight(fitsfile **fptr, int *status); bool doesHeaderContain(QString keyword); public: explicit MyImage(QString pathname, QString filename, QString statusString, int chipnumber, const QVector &mask, int *verbose, QObject *parent = nullptr); explicit MyImage(QString fullPathName, const QVector &mask, int *verbose, QObject *parent = nullptr); explicit MyImage(QObject *parent = nullptr); // A series of flags telling the status of a MyImage enum active_type { ACTIVE, // The image is active (will be used in coaddition and all processing steps) INACTIVE, // Image is inactive (for whatever reason, parked in inactive/) BADSTATS, // Image was flagged as having bad seeing/ throughput etc (parked in inactive/badStatistics/) BADBACK, // Image was flagged because the background could not be modeled (parked in inactive/badBackground/) NOASTROM, // Image was flagged because astrometric information could not be found LOWDETECTION, // Image was flagged because it has insufficiently many source detections for astrometry DELETED, // Image was manually deleted by the user (cannot be found anymore on disk) }; active_type activeState = ACTIVE; active_type oldState = activeState; // needed by memoryViewer; ~MyImage(); struct wcsprm *wcs; bool wcsInit = false; char *fullheader = nullptr; ProcessingStatus *processingStatus; int maxCPU = 1; // In case we work on a single image, e.g. for abszeropoint, we can speed up calculations QList> skyPolyfitNodes; QVector apertures; QThread *workerThread = nullptr; SourceExtractorWorker *sourceExtractorWorker = nullptr; AnetWorker *anetWorker = nullptr; // bool lockForInitWCSneeded = true; // Defining data QString path = ""; QString pathBackupL1 = ""; QString pathBackupL2 = ""; QString pathBackupL3 = ""; QString pathExtension = ""; QString weightPath = path+"../WEIGHTS/"; QString weightName = ""; QString name = ""; QString baseName = ""; // "image_1AB" in case of image_1AB.fits QString rootName = ""; // "image" in case of image_1AB.fits QString chipName = ""; // "image_1" in case of image_1AB.fits QString filter = ""; QString statusBackupL1 = ""; QString statusBackupL2 = ""; QString statusBackupL3 = ""; QString baseNameBackupL1 = ""; QString baseNameBackupL2 = ""; QString baseNameBackupL3 = ""; bool metadataTransferred = false; int groupNumber = -1; // The association of images this image belongs to (an overlapping group on sky) bool minimizeMemoryUsage = false; bool headerInfoProvided = false; bool processingFinished = false; // Reset to false every time a process starts; If finised, external jobs use this flag to force a // dump to drive to be able to release memory bool isTaskRepeated = false; bool fullheaderAllocated = false; int numHeaderKeys = 0; QString fullHeaderString = ""; bool hasTHELIheader = false; bool addGainNormalization = false; QList objectList; QVector header; QString sourceExtractorCommand; QString anetCommand; // Static image characteristics // Once running, the chipNumber always starts with 1, // contrary to the 'chip' variable which starts at 0 int chipNumber = 0; long naxis1 = 0; long naxis2 = 0; float matchingTolerance = 2./3600.; // default matching tolerance = 2 arcsec; long dim = 0; // Status flags bool imageInMemory = false; bool backupL1InMemory = false; bool backupL2InMemory = false; bool backupL3InMemory = false; bool backupL1OnDrive = false; bool backupL2OnDrive = false; bool backupL3OnDrive = false; bool imageOnDrive = false; bool weightInMemory = false; bool weightOnDrive = false; bool headerRead = false; bool modeDetermined = false; bool hasMJDread = false; bool validFile = true; // Is the file valid bool validMode = true; // Is the statistical mode within accepted range bool validBackground = true; // Is the image accepted to contribute to a background model (no if e.g. bright star) bool validDetector = true; // Is the detector alive // Data characteristics QString dateobs = ""; double crval1 = 0.; double crval2 = 0.; double mjdobs = 0; float geolon = 0.0; // Earth coordinates float geolat = 0.; // Earth coordinates float fwhm = -1.0; // FWHM estimate based on GAIA point sources float fwhm_est = -1.0; // median FWHM of all detected sources in an image float RZP = 0; // SCAMP output float exptime = 0; float airmass = 1.0; float ellipticity = -1.0; // estimate based on GAIA point sources float ellipticity_est = -1.0; // median ellipticity based on all detected sources float FLXSCALE = 0.; // SCAMP output float skyValue = -1e9; // previously set to zero float skySigma = -1; float gain = 1.0; // Read from raw fits header; fallback: taken from instrument config file float plateScale = 0.; // in arcsec float radius = 0.; // image radius in degrees float gainNormalization = 1.0; int bitpix = -32; // Processing stages QVector dataCurrent; // Contains the current state of processing. Processing is done on it, will then be pushed down into first backup level QVector dataBackupL1; // First backup level QVector dataBackupL2; // Second backup level QVector dataBackupL3; // Third backup level QVector dataMeasure; // temporary (for object detection) const QVector &globalMask; // Global mask (e.g. vignetting, permanently bad pixels; same for all images) QVector objectMask; // Object mask (used for background modeling and sky subtraction) bool backgroundPushedDown = false; // Used to detect whether a backup copy was made already during twopass background correction bool globalMaskAvailable = true; // Unless we load an external image, e.g. for absolute zeropoint // Memory stages (to decide what can be deleted and what not) bool dataWeight_deletable = false; bool dataCurrent_deletable = false; bool dataBackupL1_deletable = false; bool dataBackupL2_deletable = true; // should always be true (apart from when we populate it) bool dataBackupL3_deletable = true; // should always be true (apart from when we populate it) bool dataBackground_deletable = false; bool successProcessing = true; // A flag that is updated everytime we do something to the image int backgroundBlock = 0; QString procInfo = ""; float meanExposureBackground = 0.; // Flags to decide whether the image is used in a current background calculation or not bool useForBackground = false; // Overall flag bool useForBackgroundSequence = false; // Whether the image can be used from a 'LIRIS-style' sequence splitting bool useForBackgroundWindowed = false; // Whether the image can be used because it falls within the current group, statically or dynamically bool useForBackgroundStars = false; // Whether the image can be used because it does not contain bright sources bool hasBrightStars = false; int *verbosity; omp_lock_t backgroundLock; omp_lock_t objectLock; // The image corners in RA/DEC (e.g. to check whether a bright star is inside or outside) double alpha_ul = 0.; double alpha_ur = 0.; double alpha_ll = 0.; double alpha_lr = 0.; double delta_ul = 0.; double delta_ur = 0.; double delta_ll = 0.; double delta_lr = 0.; double alpha_ctr = 0.; // Image center coords double delta_ctr = 0.; // Transformations for binned mosaics double tcd11 = 0.; double tcd12 = 0.; double tcd21 = 0.; double tcd22 = 0.; double tcrpix1 = 0.; double tcrpix2 = 0.; // Associated data QVector dataWeight; QVector dataWeightSmooth; QVector dataTIFF; // QVector mask; float maskValue = 0.; float saturationValue = 1.e9; float saturationValueL1 = 1.e9; float saturationValueL2 = 1.e9; float saturationValueL3 = 1.e9; bool allocatedImageFITS = false; // =============== Astrometric solution =================== QVector dataXcorr; // ================= BACKGROUND MODELING =========================== QVector dataBackground; // The background model bool backupCopyBackgroundMade = false; bool hasBrightStarsChecked = false; // ================================================================= // ================== Image segmentation =========================== QVector dataSegmentation; bool backgroundModelDone = false; bool segmentationDone = false; bool maskExpansionDone = false; bool objectMaskDone = false; bool objectMaskDonePass1 = false; bool objectMaskDonePass2 = false; bool leftBackgroundWindow = false; // used to mark the memory for deletion bool enteredBackgroundWindow = false; // ================================================================= // QVector retainUnmaskedData(int sampleDensity = 1); // QVector retainUnmaskedDataThresholded(float minVal, float maxVal, int sampleDensity = 1); // void subtractPolynomialSkyFit(gsl_vector *c, int order); void add(float value); void addExludedRegionToMask(long imin, long imax, long jmin, long jmax); void appendToScampCatalogInternal(fitsfile *fptr, QString minFWHM_string, QString maxFlag_string, bool empty = false); void appendToScampCatalogSourceExtractor(fitsfile *fptr); void applyBackgroundModel(const MyImage *backgroundImage, QString mode, bool rescaleFlag); void applyMask(); void applyPolygons(); void backgroundModel(int filtersize, QString splinemode); void backupOrigHeader(int chip); void buildAnetCommand(); void buildAnetCommand(QString pixscale_maxerr); void buildSourceExtractorCommand(); void calcMedianSeeingEllipticity(); void calcMedianSeeingEllipticitySex(QString catName = "", int extnum = 0); void checkBrightStars(const QList > &brightStarList, float safetyDistance, float plateScale); void checkCorrectMaskSize(const instrumentDataType *instData); void checkTaskRepeatStatus(QString taskBasename); void checkWCSsanity(); void collapseCorrection(QString threshold, QString direction); QVector collectObjectParameter(QString paramName); void collectSeeingParameters(QVector > &outputParams, QVector &outputMag, int goodChip); bool containsRaDec(QString alphaStr, QString deltaStr); bool containsRaDec(double alpha, double delta); void cornersToRaDec(); void cosmicsFilter(QString aggressiveness); void createSourceExtractorCatalog(); void createSourceExtractorCatalog_old(); void divide(float value); void divideFlat(const MyImage *flatImage); void dumpToDriveIfPossible(); void emitModelUpdateNeeded(); void estimateMatchingTolerance(); void evaluateSkyNodes(const QVector alpha, const QVector delta, const QVector radius); QString extractAnetOutput(); QVector extractCDmatrix(); QVector extractPixelValues(long xmin, long xmax, long ymin, long ymax); void filterSourceExtractorCatalog(QString minFWHM, QString maxFlag); void freeAll(); void freeAncillaryData(QVector &data); void freeData(); float freeData(QString type); void freeData(QVector &data); void freeWeight(); QString getKeyword(QString key); void getMJD(); void getMeanBackground(); void getMode(bool determineMode); double getPlateScale(); void illuminationCorrection(int chip, QString thelidir, QString instName, QString filter); bool informSwarpfilter(long &naxis1, long &naxis2, double &crpix1, double &crpix2, double &sky, double &fluxscale); void initFITS(fitsfile **fptr, QString loadFileName, int *status); void initWCS(); void initWeightfromGlobalWeight(const QList &gwList); bool isActive(); void laplaceFilter(QVector &dataFiltered); bool loadData(QString loadFileName = ""); bool loadDataThreadSafe(QString loadFileName = ""); void loadDataSection(long xmin, long xmax, long ymin, long ymax, float *dataSect); void loadHeader(QString loadFileName = ""); void makeBackgroundBackup(); void makeCutout(long xmin, long xmax, long ymin, long ymax); void makeDriveBackup(QString backupDirName, QString statusOld); bool makeL1Current(); bool makeL2Current(); bool makeL3Current(); void makeMemoryBackup(); void makeXcorrData(); void maskBloomingSpike(QString instType, QString range, QString minVal, bool requested, QString bloomMin = "", QString bloomMax = ""); void maskExpand(QString expFactor, bool writeObjectmaskImage = false); void maskSaturatedPixels(QString tolerance, bool requested); void mergeObjectWithGlobalMask(); void multiply(float value, QString mode = ""); void normalizeFlat(); void protectMemory(); void pullUp(); void pushDown(QString backupDir); void readData(fitsfile **fptr, int *status); void readFILTER(QString loadFileName = ""); void readImage(QString loadFileName); void readImage(bool determineMode = true); void readImageThreadSafe(bool determineMode = true); void readImageBackupL1Launch(); void readWeight(); void releaseAllDetectionMemory(); void releaseBackgroundMemory(QString mode = ""); void releaseBackgroundMemoryBackgroundModel(); void releaseDetectionPixelMemory(); void releaseMemoryForBackground(); void removeSourceCatalogs(); void resetObjectMasking(); void roundEdgeOfWeight(float edge, bool roundEdge); void runAnetCommand(); bool scanAstromHeader(int chip, QString mode); void segmentImage(const QString DTstring, const QString DMINstring, const bool convolution, const bool writeSegImage = false); void setActiveState(active_type state); void setBackgroundLock(bool locked); void setDeletable(); void setModeFlag(QString min, QString max); void setObjectLock(bool locked); void setupBackgroundData(const bool &isTaskRepeated, const QString &backupDir); void setupBackgroundData_newParallel(const bool &isTaskRepeated, const QString &backupDir); void setupCalibDataInMemory(bool createBackup, bool determineMode, bool mustRereadFromDisk); void setupCoaddMode(); void setupData(bool isTaskRepeated, bool createBackup, bool determineMode, QString backupDir = ""); void setupDataInMemorySimple(bool determineMode); void showProcInfo(); void sky2xy(const double alpha, const double delta, double &x, double &y); void sourceExtractorCatToAnet(); void sourceExtractorCatToIview(); void subtract(float value, QString mode = ""); void subtractBackgroundModel(); void subtractBias(); void subtractBias(QVector const &dataCurrent, QString dataType); void subtractBias(const MyImage *biasImage, QString dataType); void subtractSkyFit(int order, gsl_vector *c, bool saveSkyModel); void thresholdWeight(QString imageMin, QString imageMax); void toTIFF(int bit, float minthresh, float maxthresh, bool zscaleing = false, float grey = 0., float gamma = 1.0); void transferObjectsToMask(); void unprotectMemory(); void unprotectMemoryForBackground(); void unprotectMemoryWeight(); void updateCRVALCDinHeader(); void updateCRVALCDinHeaderOnDrive(); void updateCRVALCRPIXCDinHeader(); void updateCRVALinHeader(); void updateCRVALinHeaderOnDrive(); void updateHeaderValue(QString keyName, QString keyValue); void updateHeaderValue(QString keyName, double keyValue, char format = 'f'); void updateHeaderValue(QString keyName, float keyValue, char format = 'f'); void updateHeaderValueInFITS(QString keyName, QString keyValue); void updateInactivePath(); void updateKeywordInHeader(QString key, QString value); void updateMode(); void updateProcInfo(QString text); void updateHeaderSaturation(); void updateZeroOrderOnDrive(QString updateMode); void writeBackgroundModel(); void writeCatalog(QString minFWHM_string, QString maxFlag_string); void writeConstSkyImage(float constValue); void writeImage(QString fileName = "", QString filter = "", float exptime = -1.0, bool addGain = false); void writeImageTIFF(QString fileName = "", QString filter = "", float exptime = -1.0, bool addGain = false); void writeImageBackupL1(); void writeImageBackupL2(); void writeImageBackupL3(); void writeImageDebayer(bool addGain = false); void writeWeight(QString fileName = ""); void writeWeightSmoothed(QString fileName); void xtalk(int method, float scale, QString direction = "", int nsection = -1); void xy2sky(const double x, const double y, double &alpha, double &delta); signals: void modelUpdateNeeded(QString chipName); void messageAvailable(QString message, QString type); void setMemoryLock(bool locked); void setWCSLock(bool locked); void critical(); void warning(); void errorOccurred(); void WCSupdated(); public slots: void messageAvailableReceived(QString message, QString type); void anetOutputReceived(QString message, QString type); private slots: void errorFoundReceived(); }; #endif // MYIMAGE_H THELI-3.1.3/src/myimage/segmentation.cc000066400000000000000000001014311417631501300176070ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "instrumentdata.h" #include "../functions.h" #include "../tools/detectedobject.h" #include "myimage.h" #include #include #include void MyImage::resetObjectMasking() { // The background will always be the same, hence let's leave it in place // backgroundModelDone = false; // dataBackground.clear(); // dataBackground.squeeze(); segmentationDone = false; maskExpansionDone = false; objectMaskDone = false; objectMaskDonePass1 = false; objectMaskDonePass2 = false; for (auto object : objectList) { object->pixels_flux.clear(); object->pixels_x.clear(); object->pixels_y.clear(); object->pixels_flux.squeeze(); object->pixels_x.squeeze(); object->pixels_y.squeeze(); } objectList.clear(); objectMask.clear(); objectMask.squeeze(); } void MyImage::segmentImage(const QString DTstring, const QString DMINstring, const bool convolution, const bool writeSegImage) { if (*verbosity > 1) emit messageAvailable(chipName + " : Detecting objects ... ", "image"); // Start fresh resetObjectMasking(); if (!successProcessing) return; if (DTstring.isEmpty() || DMINstring.isEmpty()) return; // Update the rms Value if it hasn't been determined yet // This is a fallback, because we get it through background modeling already at an earlier step. if (skySigma < 0.) { emit messageAvailable("MyImage::segmentImage(): sky noise not yet estimated, re-computing", "warning"); emit critical(); skySigma = modeMask(dataCurrent, "stable", QVector())[1]; } // Noise clipping // if this doesn't work, then make controller a member of each myimage emit setMemoryLock(true); dataSegmentation.resize(naxis1*naxis2); // this crashes vor very large images (e.g. coadded omegacam data); likely internal Qvector limitation dataMeasure.clear(); // Must clear (if we run the detection twice, e.g. for sky modeling) // dataMeasure.reserve(naxis1*naxis2); dataMeasure.resize(naxis1*naxis2); emit setMemoryLock(false); // //deactivated; causes random crashes I don't understand // dataSegmentation.squeeze(); // shed excess memory // dataMeasure.squeeze(); // shed excess memory QList allObjectPixelIndices; allObjectPixelIndices.reserve(naxis1*naxis2/2); // Avoid initial memory reallocations; assume half the pixels belong to objects // Noise filter (for detection only) QVector dataConv; if (convolution) dataConv = directConvolve(dataCurrent); else dataConv = dataCurrent; float DT = DTstring.toFloat(); float threshold = DT*skySigma; float maxWeight = 1.0; // Adapt threshold concerning the weight, if available if (weightInMemory) { maxWeight = maxVec_T(dataWeight); // Could sort a sub-sample and use the 90% highest value or sth like that, more stable } long i = 0; for (auto &pixel: dataCurrent) { // subtract background model float dorig = pixel - dataBackground.at(i); float dconv = dataConv.at(i) - dataBackground.at(i); // dataMeasure.append(dorig); dataMeasure[i] = dorig; // Initialize objects in the segmentation map with a negative value (meaning it is still unprocessed) // WARNING: Using the globalMask is essential, otherwise the floodfill alg seems to run forever. Really? // With global mask if (globalMaskAvailable) { if (!weightInMemory) { if (dconv > threshold && !globalMask.at(i)) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } else { float rescale = sqrt(maxWeight/dataWeight.at(i)); if (dataWeight.at(i) > 0. && !globalMask.at(i) && dconv > threshold*rescale) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } } // Without global mask else { if (!weightInMemory) { if (dconv > threshold) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } else { float rescale = sqrt(maxWeight/dataWeight.at(i)); if (dataWeight.at(i) > 0. && dconv > threshold*rescale) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } } ++i; } if (allObjectPixelIndices.isEmpty()) { emit messageAvailable(chipName + " : No objects detected!" , "error"); emit critical(); successProcessing = false; return; } // Create segmentation map objectList.clear(); bool scanning = true; long startindex = allObjectPixelIndices[0]; long DMIN = DMINstring.toLong(); QPoint startPoint(startindex % naxis1, startindex / naxis1); long objID = 1; // Number of the first object; we start counting at 1 not 0 while (scanning) { // Flood fill the current object belonging to that pixel, and update dataSegmentation and allObjectPixelIndices floodFill(startPoint, allObjectPixelIndices, objID, dataSegmentation, DMIN); // Retrieve next non-zero pixel index from 'objectPixelIndices' if (!allObjectPixelIndices.isEmpty()) { long nextIndex = allObjectPixelIndices.first(); startPoint.setX(nextIndex % naxis1); startPoint.setY(nextIndex / naxis1); } else { scanning = false; } } segmentationDone = true; // Lastly, compute object parameters (which we need for masking) if (*verbosity > 1) emit messageAvailable(chipName + " : Measuring object parameters ... ", "image"); // #pragma omp parallel for num_threads(maxCPU) for (long i=0; iapertures = apertures; objectList[i]->computeObjectParams(); objectList[i]->remove(); } if (*verbosity > 1) emit messageAvailable(chipName + " : " + QString::number(objectList.length()) + " objects detected.", "image"); segmentationDone = true; if (writeSegImage) writeSegmentation(path + "/" + baseName+".seg.fits"); } // getting a rough first estimate on image quality; refined after astrometric solution void MyImage::calcMedianSeeingEllipticity() { QVector fwhmVec; QVector ellipticityVec; fwhmVec.reserve(objectList.length()); ellipticityVec.reserve(objectList.length()); for (auto &object : objectList) { if (object->FLAGS == 0) { fwhmVec.append(float(object->FWHM)); ellipticityVec.append(float(object->ELLIPTICITY)); } } fwhm_est = straightMedianInline(fwhmVec) * plateScale; ellipticity_est = straightMedianInline(ellipticityVec); updateHeaderValueInFITS("FWHMEST", QString::number(fwhm_est, 'f', 2)); updateHeaderValueInFITS("ELLIPEST", QString::number(ellipticity_est, 'f', 3)); } // Flood fill an individual object with the objectID and calculate object area void MyImage::floodFill(const QPoint startPoint, QList &allObjectPixelIndices, long &objID, QVector &dataSegmentation, const long DMIN) { if (!insideImage(startPoint)) return; // Did we process this point already? If so, remove it from the list of indices long index = startPoint.x() + naxis1*startPoint.y(); if (dataSegmentation[index] != -1) { allObjectPixelIndices.pop_front(); return; } // temporary storage to mark pixels for deletion (if area less than DMIN) QList currentObjectPixels; currentObjectPixels.reserve(10000); QQueue pointQueue; pointQueue.enqueue(startPoint); // This is the actual flood filling long area = 0; while (!pointQueue.isEmpty()) { QPoint p = pointQueue.first(); pointQueue.pop_front(); if (insideImage(p)) { if (dataSegmentation[p.x()+naxis1*p.y()] == -1) { dataSegmentation[p.x()+naxis1*p.y()] = objID; // queue the edges pointQueue.enqueue(QPoint(p.x() + 1, p.y())); pointQueue.enqueue(QPoint(p.x() - 1, p.y())); pointQueue.enqueue(QPoint(p.x(), p.y() + 1)); pointQueue.enqueue(QPoint(p.x(), p.y() - 1)); // queue the corners (8-connectivity) pointQueue.enqueue(QPoint(p.x()-1, p.y()-1)); pointQueue.enqueue(QPoint(p.x()+1, p.y()-1)); pointQueue.enqueue(QPoint(p.x()-1, p.y()+1)); pointQueue.enqueue(QPoint(p.x()+1, p.y()+1)); currentObjectPixels.push_back(p.x()+naxis1*p.y()); } } } area = currentObjectPixels.length(); // remove object from segmentation map if too small if (area < DMIN) { for (auto &pixel: currentObjectPixels) { dataSegmentation[pixel] = 0; } return; } // Initialize the object and add it to the list of detected sources for this image float effectiveGain = 1.0; // ADUs converted during HDU reformatting DetectedObject *newObject = new DetectedObject(currentObjectPixels, dataMeasure, dataBackground, dataWeight, globalMask, weightInMemory, naxis1, naxis2, ++objID, saturationValue, effectiveGain, *wcs); newObject->globalMaskAvailable = globalMaskAvailable; objectList.append(newObject); // Remove the current pixel we just processed, // and potentially a few more if they happen to be at the beginning of the list while (!allObjectPixelIndices.isEmpty() && !currentObjectPixels.isEmpty() && allObjectPixelIndices.first() == currentObjectPixels.first()) { allObjectPixelIndices.pop_front(); currentObjectPixels.pop_front(); } } bool MyImage::insideImage(QPoint p) { if (p.rx() >= 0 && p.rx() < naxis1 && p.ry() >= 0 && p.ry() < naxis2) return true; else return false; } // convolve with a general purpose noise filter QVector MyImage::directConvolve(const QVector &data) { float kernel[] = { 1./16., 2./16., 1./16., 2./16., 4./16., 2./16., 1./16., 2./16., 1./16.}; long n = naxis1; long m = naxis2; QVector dataConv(n*m); // direct convolution. We ignore the border long s = 1; // half the kernel size - 1 for (long j=1; j 0.) objectMask[i] = true; ++i; } objectMaskDone = true; } void MyImage::estimateMatchingTolerance() { QVector sizes; for (auto &object : objectList) { if (object->FLAGS == 0) sizes.append(object->FLUX_RADIUS); } if (sizes.isEmpty()) { matchingTolerance = 5.*plateScale/3600.; // 5 pixel if (*verbosity > 2) emit messageAvailable(chipName + " : IQ matching tolerance defaulted to "+QString::number(5.*plateScale, 'f', 1)+" arcsec (5 pixel)", "image"); emit warning(); } else { float radius = straightMedian_T(sizes); // used to be twice as large matchingTolerance = radius * plateScale / 3600.; if (*verbosity > 2) emit messageAvailable(chipName + " : IQ matching tolerance = "+QString::number(matchingTolerance*3600, 'f', 1)+" arcsec", "image"); } } // Unused QVector MyImage::collectObjectParameter(QString paramName) { QVector param; param.reserve(objectList.length()); if (paramName == "RA") { for (auto &object : objectList) { param << object->ALPHA_J2000; } } if (paramName == "DEC") { for (auto &object : objectList) { param << object->DELTA_J2000; } } if (paramName == "FWHM") { for (auto &object : objectList) { param << object->FLUX_RADIUS; } } if (paramName == "ELLIPTICITY") { for (auto &object : objectList) { param << object->ELLIPTICITY; } } return param; } void MyImage::collectSeeingParameters(QVector> &outputParams, QVector &outputMag, int goodChip) { QVector param; param.reserve(4); outputParams.clear(); // Must clear because each image will fill this data repeatedly outputMag.clear(); // Try memory access in MyImage if (!objectList.isEmpty()) { outputParams.reserve(objectList.length()); outputMag.reserve(objectList.length()); for (auto &object : objectList) { // Must recalculate RA and DEC after astrometry double raNew; double decNew; xy2sky(object->XWIN, object->YWIN, raNew, decNew); // must pass dec first for tools::match2D() method if (object->FLAGS == 0) { param << decNew << raNew << object->FWHM << object->ELLIPTICITY; outputParams << param; outputMag << object->MAG_AUTO; param.clear(); } } return; } // Not present (if GUI launched at this position, or Source Extractor was used to compute catalogs) // Try external catalog else { QString catalogName = "cat/" + rootName+".scamp"; QString fullCatalogName = path + "/" + catalogName; QFile catalog(fullCatalogName); if (!catalog.exists()) { emit messageAvailable(chipName + " : Could not find catalog for seeing measurement:
" + catalogName, "warning"); emit warning(); } int status = 0; fitsfile *fptr; fits_open_file(&fptr, fullCatalogName.toUtf8().data(), READONLY, &status); // LDAC_OBJECTS tables are found in extensions 3, 5, 7, ..., internally referred to as 2, 4, 6, ... int hduType = 0; fits_movabs_hdu(fptr, 2*(goodChip+1)+1, &hduType, &status); // fits_movnam_hdu(fptr, BINARY_TBL, tblname, extver, &status); long nrows = 0; int xwinColNum = -1; int ywinColNum = -1; int alphaColNum = -1; int deltaColNum = -1; int fwhmColNum = -1; int ellColNum = -1; int magColNum = -1; int flagColNum = -1; fits_get_num_rows(fptr, &nrows, &status); char xwinName[100] = "XWIN_IMAGE"; char ywinName[100] = "YWIN_IMAGE"; char alphaName[100] = "ALPHA_J2000"; char deltaName[100] = "DELTA_J2000"; char fwhmName[100] = "FWHM_IMAGE"; char ellName[100] = "ELLIPTICITY"; char magName[100] = "MAG_AUTO"; char flagName[100] = "FLAGS"; fits_get_colnum(fptr, CASESEN, xwinName, &xwinColNum, &status); fits_get_colnum(fptr, CASESEN, ywinName, &ywinColNum, &status); fits_get_colnum(fptr, CASESEN, alphaName, &alphaColNum, &status); fits_get_colnum(fptr, CASESEN, deltaName, &deltaColNum, &status); fits_get_colnum(fptr, CASESEN, fwhmName, &fwhmColNum, &status); fits_get_colnum(fptr, CASESEN, ellName, &ellColNum, &status); fits_get_colnum(fptr, CASESEN, magName, &magColNum, &status); fits_get_colnum(fptr, CASESEN, flagName, &flagColNum, &status); int firstrow = 1; int firstelem = 1; int anynul = 0; double *xwin = new double[nrows]; double *ywin = new double[nrows]; double *alpha = new double[nrows]; double *delta = new double[nrows]; float *fwhm = new float[nrows]; float *ell = new float[nrows]; float *mag = new float[nrows]; int *flag = new int[nrows]; QString missing = ""; fits_read_col(fptr, TDOUBLE, xwinColNum, firstrow, firstelem, nrows, NULL, xwin, &anynul, &status); if (status != 0) missing.append("XWIN_IMAGE, "); status = 0; fits_read_col(fptr, TDOUBLE, ywinColNum, firstrow, firstelem, nrows, NULL, ywin, &anynul, &status); if (status != 0) missing.append("YWIN_IMAGE, "); status = 0; fits_read_col(fptr, TDOUBLE, alphaColNum, firstrow, firstelem, nrows, NULL, alpha, &anynul, &status); if (status != 0) missing.append("ALPHA_J2000, "); status = 0; fits_read_col(fptr, TDOUBLE, deltaColNum, firstrow, firstelem, nrows, NULL, delta, &anynul, &status); if (status != 0) missing.append("DELTA_J2000, "); status = 0; fits_read_col(fptr, TFLOAT, fwhmColNum, firstrow, firstelem, nrows, NULL, fwhm, &anynul, &status); if (status != 0) missing.append("FWHM_IMAGE, "); status = 0; fits_read_col(fptr, TFLOAT, ellColNum, firstrow, firstelem, nrows, NULL, ell, &anynul, &status); if (status != 0) missing.append("ELLIPTICITY, "); status = 0; fits_read_col(fptr, TFLOAT, magColNum, firstrow, firstelem, nrows, NULL, mag, &anynul, &status); if (status != 0) missing.append("MAG_AUTO, "); status = 0; fits_read_col(fptr, TINT, flagColNum, firstrow, firstelem, nrows, NULL, flag, &anynul, &status); if (status != 0) missing.append("FLAGS, "); status = 0; fits_close_file(fptr, &status); if (!missing.isEmpty()) { emit messageAvailable(chipName + " : Could not find " + missing + " in " + catalogName, "warning"); } outputParams.reserve(nrows); outputMag.reserve(nrows); for (long i=0; i 1) emit messageAvailable(chipName + " : Expanding object mask ...", "image"); factor *= 3.; // We need an extra factor of 3 to encompass the outer isophote long n = naxis1; long m = naxis2; for (auto &it : objectMask) it = false; // Loop over all objects for (auto &object : objectList) { // skip spurious and bad detections if (object->badDetection) continue; // Do not mask expand extremely small objects (hot pixels etc) if (object->B < 1.0) continue; // Do not mask expand very large and extremely elongated objects (bad columns, saturation spikes) if (object->ELLIPTICITY > 0.9 && object->A > 50) continue; float oX = object->X; float oY = object->Y; float oAf = object->A * factor; float xextent = 3. * pow(object->A*factor, 2); // max ellipse extent in x direction float yextent = 3. * object->A * object->B * factor * factor; // max ellipse extent in y direction long imin = (oX - xextent > 0) ? int(oX - xextent) : 0; long imax = (oX + xextent < n) ? int(oX + xextent) : n-1; long jmin = (oY - yextent > 0) ? int(oY - yextent) : 0; long jmax = (oY + yextent < m) ? int(oY + yextent) : m-1; // Loop over the rectangular subset of pixels that encompass the object for (long j=jmin; j<=jmax; ++j) { float dy = oY - j; for (long i=imin; i<=imax; ++i) { float dx = oX - i; if (object->CXX*dx*dx + object->CYY*dy*dy + object->CXY*dx*dy <= oAf*oAf) { objectMask[i+naxis1*j] = true; } } } } maskExpansionDone = true; if (writeObjectmaskImage) writeObjectMask(path + "/" + baseName+".mask.fits"); } // not part of the segmentation process, actually void MyImage::addExludedRegionToMask(long imin, long imax, long jmin, long jmax) { if (imin < 0) imin = 0; if (imax > naxis1 - 1) imax = naxis1 - 1; if (jmin < 0) jmin = 0; if (jmax > naxis2 - 1) jmax = naxis2 - 1; if (jmin == 0) for (long j=jmin; j<=jmax; ++j) { for (long i=imin; i<=imax; ++i) { objectMask[i+naxis2*j] = true; } } } void MyImage::releaseAllDetectionMemory() { for (auto &object : objectList) { delete object; object = nullptr; } objectList.clear(); releaseDetectionPixelMemory(); } void MyImage::releaseDetectionPixelMemory() { emit setMemoryLock(true); dataSegmentation.clear(); dataSegmentation.squeeze(); dataMeasure.clear(); dataMeasure.squeeze(); objectMask.clear(); objectMask.squeeze(); objectMaskDone = false; objectMaskDonePass1 = false; objectMaskDonePass2 = false; segmentationDone = false; emit setMemoryLock(false); } void MyImage::writeCatalog(QString minFWHM_string, QString maxFlag_string) { QString outpath = path+"/cat/iview/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); float minFWHM = minFWHM_string.toFloat(); float maxFlag = maxFlag_string.toFloat(); if (maxFlag_string.isEmpty()) maxFlag = 100; // Write iview catalog QFile file(path+"/cat/iview/"+chipName+".iview"); if (file.open(QIODevice::WriteOnly)) { QTextStream outputStream(&file); for (auto &object : objectList) { outputStream.setRealNumberPrecision(9); if (3.*object->AWIN >= minFWHM && object->FLAGS <= maxFlag && object->FLUX_AUTO > 0. && object->ELLIPTICITY < 0.6) { // MUST APPLY ORIGIN OFFSET CORRECTION (+1), because calculations were done starting counting at 0 (in FITS files we start at 1) outputStream << object->XWIN + 1. << " " << object->YWIN + 1. << " " << object->AWIN << " " << object->BWIN << " " << object->THETAWIN << "\n"; } } file.close(); } else { emit messageAvailable("Could not create IView source catalog: "+path+"/cat/iview/"+chipName+".iview", "error"); emit critical(); } // Write anet catalog char x[100] = "X"; char y[100] = "Y"; char mag[100] = "MAG"; char *ttype[3] = {x, y, mag}; char tf1[10] = "1D"; char tf2[10] = "1D"; char tf3[10] = "1E"; char *tform[3] = {tf1, tf2, tf3}; long numSources = objectList.length(); long numSourcesRetained = 0.; for (long i=0; iAWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->FLUX_AUTO > 0.) { ++numSourcesRetained; } } long nrows = numSourcesRetained; double x_arr[nrows]; double y_arr[nrows]; float mag_arr[nrows]; long k = 0; for (long i=0; iAWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->FLUX_AUTO > 0.) { // MUST APPLY ORIGIN OFFSET CORRECTION (+1), because calculations were done starting counting at 0 (in FITS files we start at 1) x_arr[k] = objectList[i]->XWIN + 1.; y_arr[k] = objectList[i]->YWIN + 1.; mag_arr[k] = objectList[i]->MAG_AUTO; ++k; } } int status = 0; fitsfile *fptr; long firstrow = 1; long firstelem = 1; int tfields = 3; QString filename = path+"/cat/"+chipName+".anet"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype, tform, nullptr, "OBJECTS", &status); fits_write_col(fptr, TDOUBLE, 1, firstrow, firstelem, nrows, x_arr, &status); fits_write_col(fptr, TDOUBLE, 2, firstrow, firstelem, nrows, y_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, mag_arr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } void MyImage::makeXcorrData() { dataXcorr = dataCurrent; // Xcorrelation works best if we mask all unrelevant pixels long i = 0; for (auto &pixel: dataXcorr) { if (globalMaskAvailable && globalMask.at(i)) pixel = 0.; if (dataSegmentation.at(i) == -1) pixel = 0.; if (weightInMemory && dataWeight.at(i) == 0.) pixel = 0.; ++i; } } // Appends a new binary table to an already opened FITS file (handled by Controller class) void MyImage::appendToScampCatalogInternal(fitsfile *fptr, QString minFWHM_string, QString maxFlag_string, bool empty) { float minFWHM = minFWHM_string.toFloat(); float maxFlag = maxFlag_string.toFloat(); if (maxFlag_string.isEmpty()) maxFlag = 100; if (minFWHM_string.isEmpty()) minFWHM = 0.01; // STEP 1: LDAC_IMHEAD table, containing the FITS header int status = 0; long firstrow = 1; long firstelem = 1; int tfields = 1; long nrows = 1; char name[100] = "Field Header Card"; char *ttype1[1] = {name}; // Awkward C-stuff. This is the only way I could get this to work. // If the tf0 string is built differently, if strcmp says they are identical, the TTYPE1 keyword is not written properly. // And it cannot be udpated properly with fits_update_key() either // Update the WCS keywords in fullheader so the LDAC_IMHEAD string is correct. Not sure scamp cares, but nonetheless replaceCardInFullHeaderString("CRVAL1", wcs->crval[0]); replaceCardInFullHeaderString("CRVAL2", wcs->crval[1]); replaceCardInFullHeaderString("CRPIX1", wcs->crpix[0]); replaceCardInFullHeaderString("CRPIX2", wcs->crpix[1]); replaceCardInFullHeaderString("CD1_1", wcs->cd[0]); replaceCardInFullHeaderString("CD1_2", wcs->cd[1]); replaceCardInFullHeaderString("CD2_1", wcs->cd[2]); replaceCardInFullHeaderString("CD2_2", wcs->cd[3]); long headerLength = strlen(fullheader); char tf0[100]; sprintf(tf0, "%ldA", headerLength); char *tform1[1] = {tf0}; const char *headerstring[1]; headerstring[0] = fullheader; fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype1, tform1, nullptr, "LDAC_IMHEAD", &status); fits_write_col(fptr, TSTRING, 1, firstrow, firstelem, nrows, headerstring, &status); // STEP 2: LDAC_OBJECTS table char xwin[100] = "XWIN_IMAGE"; char ywin[100] = "YWIN_IMAGE"; char erra[100] = "ERRAWIN_IMAGE"; char errb[100] = "ERRBWIN_IMAGE"; char errt[100] = "ERRTHETAWIN_IMAGE"; char flux[100] = "FLUX_AUTO"; char fluxerr[100] = "FLUXERR_AUTO"; char flags[100] = "FLAGS"; char alpha[100] = "ALPHA_J2000"; char delta[100] = "DELTA_J2000"; char fwhm[100] = "FWHM_IMAGE"; char mag[100] = "MAG_AUTO"; char ell[100] = "ELLIPTICITY"; char *ttype2[13] = {xwin, ywin, erra, errb, errt, flux, fluxerr, flags, alpha, delta, fwhm, mag, ell}; char tf1[10] = "1E"; char tf2[10] = "1E"; char tf3[10] = "1E"; char tf4[10] = "1E"; char tf5[10] = "1E"; char tf6[10] = "1E"; char tf7[10] = "1E"; char tf8[10] = "1I"; char tf9[10] = "1D"; char tf10[10] = "1D"; char tf11[10] = "1E"; char tf12[10] = "1E"; char tf13[10] = "1E"; char *tform2[13] = {tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9, tf10, tf11, tf12, tf13}; long numSources = objectList.length(); // if (empty) numSources = 0; // empty table for deactivated images long numSourcesRetained = 0; for (long i=0; iAWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->FLUX_AUTO > 0.) { ++numSourcesRetained; } } nrows = numSourcesRetained; // one row per source // if (empty) nrows = 0; // empty table for deactivated images float xwin_arr[nrows]; float ywin_arr[nrows]; float erra_arr[nrows]; float errb_arr[nrows]; float errt_arr[nrows]; float flux_arr[nrows]; float fluxerr_arr[nrows]; short flags_arr[nrows]; double alpha_arr[nrows]; double delta_arr[nrows]; float fwhm_arr[nrows]; float mag_arr[nrows]; float ell_arr[nrows]; long k = 0; for (long i=0; iAWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->FLUX_AUTO > 0.) { // MUST APPLY ORIGIN OFFSET CORRECTION (+1), because calculations were done starting counting at 0 (in FITS files we start at 1) xwin_arr[k] = objectList[i]->XWIN + 1.; ywin_arr[k] = objectList[i]->YWIN + 1.; erra_arr[k] = objectList[i]->ERRAWIN; errb_arr[k] = objectList[i]->ERRBWIN; errt_arr[k] = objectList[i]->ERRTHETAWIN; flux_arr[k] = objectList[i]->FLUX_AUTO; fluxerr_arr[k] = sqrt(objectList[i]->FLUX_AUTO); flags_arr[k] = objectList[i]->FLAGS; // The following are not needed by scamp. They are just for completeness. alpha_arr[k] = objectList[i]->ALPHA_J2000; delta_arr[k] = objectList[i]->DELTA_J2000; fwhm_arr[k] = objectList[i]->FWHM; mag_arr[k] = objectList[i]->MAG_AUTO; ell_arr[k] = objectList[i]->ELLIPTICITY; ++k; } } firstrow = 1; firstelem = 1; tfields = 13; fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype2, tform2, nullptr, "LDAC_OBJECTS", &status); fits_write_col(fptr, TFLOAT, 1, firstrow, firstelem, nrows, xwin_arr, &status); fits_write_col(fptr, TFLOAT, 2, firstrow, firstelem, nrows, ywin_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, erra_arr, &status); fits_write_col(fptr, TFLOAT, 4, firstrow, firstelem, nrows, errb_arr, &status); fits_write_col(fptr, TFLOAT, 5, firstrow, firstelem, nrows, errt_arr, &status); fits_write_col(fptr, TFLOAT, 6, firstrow, firstelem, nrows, flux_arr, &status); fits_write_col(fptr, TFLOAT, 7, firstrow, firstelem, nrows, fluxerr_arr, &status); fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, flags_arr, &status); fits_write_col(fptr, TDOUBLE, 9, firstrow, firstelem, nrows, alpha_arr, &status); fits_write_col(fptr, TDOUBLE, 10, firstrow, firstelem, nrows, delta_arr, &status); fits_write_col(fptr, TFLOAT, 11, firstrow, firstelem, nrows, fwhm_arr, &status); fits_write_col(fptr, TFLOAT, 12, firstrow, firstelem, nrows, mag_arr, &status); fits_write_col(fptr, TFLOAT, 13, firstrow, firstelem, nrows, ell_arr, &status); // fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, fieldpos, &status); // Color-coding output lines QString detStatus = ""; QString level = "image"; if (nrows<10 && nrows>3) { detStatus = " (low source count)"; level = "warning"; } if (nrows<=3 && nrows >= 1) { detStatus = " (very low source count)"; level = "stop"; } if (nrows==0) { detStatus = " (no sources detected, or image deactivated)"; level = "stop"; } messageAvailable(rootName + " : " + QString::number(nrows) + " sources after filtering..." +detStatus, level); printCfitsioError(__func__, status); } THELI-3.1.3/src/myimage/skysub.cc000066400000000000000000000122731417631501300164370ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "../functions.h" #include "myimage.h" #include "wcs.h" #include #include #include #include #include /* // subtract a polynomial fit void MyImage::subtractPolynomialSkyFit(gsl_vector* c, int order) { if (!successProcessing) return; QVector ra; QVector dec; QVector radius; // readSkyPositions(ra, dec, sky); // calculateSkyFit(ra, dec, sky, order); } */ // Needed for polynomial fit QVector MyImage::locateSkyNode(const double alpha, const double delta, const double radius) { double xpos = 0.; double ypos = 0.; sky2xy(alpha, delta, xpos, ypos); long xcen = xpos; long ycen = ypos; // maximally inscribe a square, of half width 'w' into the circular aperture long w = radius*0.7 / plateScale; if (w<1) return QVector(); QVector aperture; long xmin = xcen - w < 0 ? 0 : xcen - w; long ymin = ycen - w < 0 ? 0 : ycen - w; long xmax = xcen + w >= naxis1 ? naxis1-1 : xcen + w; long ymax = ycen + w >= naxis2 ? naxis2-1 : ycen + w; long numPixels = (xmax-xmin+1)*(ymax-ymin+1); if (numPixels < 10) return QVector(); // return if insufficient number of data points aperture << xmin << xmax << ymin << ymax; return aperture; } // Needed for polynomial fit and constant sky sub void MyImage::evaluateSkyNodes(const QVector alpha, const QVector delta, const QVector radius) { if (alpha.length() != delta.length() || alpha.length() != radius.length() || alpha.isEmpty()) { return; } skyPolyfitNodes.clear(); for (long k=0; k aperture = locateSkyNode(alpha[k], delta[k], radius[k]); if (aperture.isEmpty()) continue; QVector sample; long xmin = aperture[0]; long xmax = aperture[1]; long ymin = aperture[2]; long ymax = aperture[3]; sample.reserve((xmax-xmin+1)*(ymax-ymin+1)); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { if (globalMaskAvailable) { if (!globalMask[i+naxis1*j]) sample.append(dataCurrent[i+naxis1*j]); } else { sample.append(dataCurrent[i+naxis1*j]); } } } float sky; if (sample.length() < 10) continue; // insufficient number of data points if (sample.length() < 1000) sky = straightMedian_T(sample); // Mode won't work if sample is small. else sky = modeMask(sample, "stable")[0]; QVector node = {alpha[k], delta[k], sky}; skyPolyfitNodes.append(node); } } void MyImage::subtractSkyFit(int order, gsl_vector *c, bool saveSkyModel) { QVector skymodel; if (saveSkyModel) skymodel.resize(naxis1*naxis2); skymodel.squeeze(); float skysum = 0.; if (*verbosity > 1) emit messageAvailable(baseName + " : Subtracting polynomial fit ...", "image"); long t = 0; for (long j=0; jcd[0] * (double(i)-wcs->crpix[0]) + wcs->cd[1] * (double(j)-wcs->crpix[1]) + wcs->crval[0]; // double dec_pix = wcs->cd[2] * (double(i)-wcs->crpix[0]) + wcs->cd[3] * (double(j)-wcs->crpix[1]) + wcs->crval[1]; // Potentially very slow! double ra_pix; double dec_pix; xy2sky(double(i), double(j), ra_pix, dec_pix); // Evaluate the background model double s = 0; double sky = gsl_vector_get(c, s++); // Do not combine the following two for loops, because of the s++ for (int k=1; k<=order; ++k) { sky += gsl_vector_get(c, s++) * pow(ra_pix, k); } for (int k=1; k<=order; ++k) { sky += gsl_vector_get(c, s++) * pow(dec_pix, k); } dataCurrent[i+naxis1*j] -= sky; skysum += sky; if (saveSkyModel) { skymodel[t] = sky; ++t; } } } meanExposureBackground = skysum / (naxis1*naxis2); if (saveSkyModel) { mkAbsDir(path + "/SKY_IMAGES"); QString fileName = path+"/SKY_IMAGES/"+baseName+".sky.fits"; write(fileName, skymodel, exptime, filter, header); } } THELI-3.1.3/src/myimage/sourceextractor.cc000066400000000000000000000300241417631501300203450ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // This file deals with running Source Extractor as an external tool #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../threading/sourceextractorworker.h" #include #include #include #include #include #include void MyImage::buildSourceExtractorCommand() { if (!successProcessing) return; // Create the 'cat/' sub-directory if it does not exist yet. mkAbsDir(path+"/cat/iview/"); QString sourceExtractor = findExecutableName("source-extractor"); sourceExtractorCommand = sourceExtractor + " "; sourceExtractorCommand += path + "/" + chipName + processingStatus->statusString + ".fits"; sourceExtractorCommand += " -CATALOG_NAME " + path+"/cat/" + chipName + ".cat"; sourceExtractorCommand += " -WEIGHT_IMAGE " + weightPath + "/" + chipName + ".weight.fits"; // NOTE: further options are appended in controller::detectionSourceExtractor() // Check if weight exists QFile weight(weightPath+"/"+chipName+".weight.fits"); if (!weight.exists()) { emit messageAvailable(baseName + " : associated weight map not found:
" + weightPath + "/" + chipName + ".weight.fits
" + "The weight is required for the creation of source catalogs.", "error"); emit critical(); successProcessing = false; } } // start in same thread void MyImage::createSourceExtractorCatalog_old() { if (!successProcessing) return; QProcess process; process.start("/bin/sh -c \""+sourceExtractorCommand+"\""); process.waitForFinished(-1); } // start in new thread void MyImage::createSourceExtractorCatalog() { if (!successProcessing) return; if (*verbosity >= 2) emit messageAvailable("Running the following command in " + path + " :
"+sourceExtractorCommand, "image"); // Run the SourceExtractor command workerThread = new QThread(); sourceExtractorWorker = new SourceExtractorWorker(sourceExtractorCommand, path); sourceExtractorWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, sourceExtractorWorker, &SourceExtractorWorker::runSourceExtractor); connect(sourceExtractorWorker, &SourceExtractorWorker::errorFound, this, &MyImage::errorFoundReceived); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); // Direct connection required, otherwise the task hangs after the first SourceExtractor command // (does not proceed to the next step in the controller's for loop) connect(sourceExtractorWorker, &SourceExtractorWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(sourceExtractorWorker, &SourceExtractorWorker::finished, sourceExtractorWorker, &QObject::deleteLater); connect(sourceExtractorWorker, &SourceExtractorWorker::messageAvailable, this, &MyImage::messageAvailableReceived); workerThread->start(); workerThread->wait(); } void MyImage::errorFoundReceived() { successProcessing = false; } void MyImage::filterSourceExtractorCatalog(QString minFWHM, QString maxFlag) { if (!successProcessing) return; fitsfile *fptr; int status = 0; QString filterString = ""; if (!maxFlag.isEmpty() && minFWHM.isEmpty()) filterString = "FLAGS <= "+ maxFlag; else if (maxFlag.isEmpty() && !minFWHM.isEmpty()) filterString = "FWHM_IMAGE >= "+minFWHM; else if (!maxFlag.isEmpty() && !minFWHM.isEmpty()) filterString = "FLAGS <= "+ maxFlag + " && FWHM_IMAGE >= "+minFWHM; else return; QString catName = path+"/cat/"+chipName+".cat"; fits_open_file(&fptr, catName.toUtf8().data(), READWRITE, &status); char tblname[100] = "LDAC_OBJECTS"; int extver = 0; fits_movnam_hdu(fptr, BINARY_TBL, tblname, extver, &status); fits_select_rows(fptr, fptr, filterString.toUtf8().data(), &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); // Cannot do that, creating a child for a parent in a different thread; // should push the message directly to monitor instead; // printCfitsioError(__func__, status); } void MyImage::calcMedianSeeingEllipticitySex(QString catName, int extnum) { if (!successProcessing) return; fitsfile *fptr; int status = 0; if (catName.isEmpty()) catName = path+"/cat/"+chipName+".cat"; fits_open_file(&fptr, catName.toUtf8().data(), READONLY, &status); // Move to the LDAC_OBJECTS table if (extnum == 0) { // working on single source extractor catalogs before being merged into scamp catalog char tblname[100] = "LDAC_OBJECTS"; int extver = 0; fits_movnam_hdu(fptr, BINARY_TBL, tblname, extver, &status); } else { int hduType = 0; fits_movabs_hdu(fptr, extnum, &hduType, &status); } long nrows = 0; int fwhmColNum = -1; int ellColNum = -1; fits_get_num_rows(fptr, &nrows, &status); char fwhmName[100] = "FWHM_IMAGE"; char ellName[100] = "ELLIPTICITY"; fits_get_colnum(fptr, CASESEN, fwhmName, &fwhmColNum, &status); fits_get_colnum(fptr, CASESEN, ellName, &ellColNum, &status); int firstrow = 1; int firstelem = 1; int anynul = 0; double *fwhm = new double[nrows]; double *ell = new double[nrows]; fits_read_col(fptr, TDOUBLE, fwhmColNum, firstrow, firstelem, nrows, NULL, fwhm, &anynul, &status); fits_read_col(fptr, TDOUBLE, ellColNum, firstrow, firstelem, nrows, NULL, ell, &anynul, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); // Put into a vector so we can do calculations QVector fwhmVec(nrows); QVector ellVec(nrows); for (long i=0; i void MyImage::toTIFF(int bit, float minthresh, float maxthresh, bool zscaleing, float grey, float gamma) { /* // If no dynamic range provided, use the data min/max values if (!zscaleing) { minthresh = minVec_T(dataCurrent); maxthresh = maxVec_T(dataCurrent); } */ if (*verbosity >= 2) emit messageAvailable("Creating "+baseName+".tiff ...", "ignore"); if (dataTIFF.isEmpty()) dataTIFF = dataCurrent; long n = naxis1; long m = naxis2; long dim = n*m; // If z-scale is requested if (zscaleing) { float medVal = medianMask_T(dataTIFF); float rmsVal = rmsMask_T(dataTIFF); minthresh = medVal - 2.*rmsVal; maxthresh = medVal + 10.*rmsVal; } // If gamma correction if requested if ( gamma != 1.0 ) { gamma = 1./gamma; double gmaxlevel = pow(maxthresh, gamma); #pragma omp parallel for for (long k=0; k= maxthresh) dataTIFF[k] = maxthresh; } float blowup = 0.; if (bit == 8) { grey = grey / 100. * 253.; blowup = (253. - grey) / (maxthresh - minthresh); } else { grey = grey / 100. * 65000.; blowup = (65000. - grey) / (maxthresh - minthresh); } std::vector< std::vector > imtiff(n); for (long i=0; i #include #include #include void MyImage::readWeight() { dataWeight_deletable = false; // Leave if image is already loaded if (weightInMemory) return; else { int status = 0; fitsfile *fptr = nullptr; QString fileName = weightPath+"/"+weightName+".fits"; initFITS(&fptr, fileName, &status); readDataWeight(&fptr, &status); fits_close_file(fptr, &status); if (status) { printCfitsioError(__func__, status); successProcessing = false; weightInMemory = false; } else { weightInMemory = true; weightOnDrive = true; successProcessing = true; } } } void MyImage::initWeightfromGlobalWeight(const QList &gwList) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Init weight from global weight ...", "image"); // Load the matching global weight bool loadSuccess = false; for (auto &gw: gwList) { if (gw->filter == filter && filter == "RGB") { emit messageAvailable("MyImage::initWeightFromGlobalWeight(): You must first apply the flatfield to the science data!", "error"); emit critical(); successProcessing = false; loadSuccess = false; break; } if (gw->filter == filter) { if (!gw->imageInMemory) gw->readImageThreadSafe(); // if (!gw->imageInMemory) gw->readImage(); dataWeight = gw->dataCurrent; loadSuccess = true; weightInMemory = true; break; } } if (!loadSuccess) { emit messageAvailable(chipName + " : MyImage::initWeightFromGlobalWeight(): Did not find the globalweight for filter " + filter, "error"); emit critical(); successProcessing = false; } // An oddball, not sure that will ever happen if (loadSuccess && dataWeight.length() != dataCurrent.length()) { emit messageAvailable(chipName + " : MyImage::initWeightFromGlobalWeight(): weight and science image do not have the same size!", "error"); emit critical(); successProcessing = false; } } void MyImage::thresholdWeight(QString imageMin, QString imageMax) { if (imageMin.isEmpty() && imageMax.isEmpty()) return; if (imageMin == imageMax) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Thresholding weight if image is outside ["+imageMin+","+imageMax+"] ...", "image"); float minVal = imageMin.toFloat(); float maxVal = imageMax.toFloat(); if (imageMin.isEmpty()) minVal = -1.e9; if (imageMax.isEmpty()) maxVal = 1.e9; if (minVal > maxVal) std::swap(minVal, maxVal); long i=0; for (auto &pixel : dataWeight) { if (dataCurrent.at(i) < minVal) pixel = 0.; if (dataCurrent.at(i) > maxVal) pixel = 0.; ++i; } } void MyImage::maskSaturatedPixels(QString tolerance, bool requested) { if (!successProcessing) return; if (!requested) return; float toleranceFloat = 1.0; if (!tolerance.isEmpty()) toleranceFloat = tolerance.toFloat(); long i=0; for (auto &pixel : dataWeight) { if (dataCurrent.at(i) >= saturationValue*toleranceFloat) pixel = 0.; ++i; } } void MyImage::roundEdgeOfWeight(float edge, bool roundEdge) { dataWeightSmooth = dataWeight; for (long j=0; j 1) emit messageAvailable(chipName + " : Mask found, applying mask to weight ...", "image"); addRegionFilesToWeight(naxis1, naxis2, regionFileName, dataWeight); } void MyImage::freeWeight() { emit setMemoryLock(true); if (minimizeMemoryUsage) { dataWeight.clear(); dataWeight.squeeze(); weightInMemory = false; } else { dataWeight_deletable = true; } emit setMemoryLock(false); } void MyImage::maskBloomingSpike(QString instType, QString range, QString minVal, bool requested, QString bloomMin, QString bloomMax) { if (!successProcessing) return; if (!requested) return; if (instType != "OPT") return; if (*verbosity > 1) emit messageAvailable(chipName + " : Detecting blooming spikes ...", "image"); float histstep = 1000.; float maxval = maxVec_T(dataCurrent); float minval = minVal.toFloat(); if (minVal.isEmpty()) minval = meanMask_T(dataCurrent) + 10.*rmsMask_T(dataCurrent); if (maxval > 200000.) maxval = 200000.; QVector mask(naxis1*naxis2, true); // false if pixel is good, true if pixel is "bloomed" // masking long l = 0; long k = 0; for (auto &pixel : dataCurrent) { if (pixel < minval) mask[k] = false; else ++l; ++k; } long npix1 = l; // number of potentially bloomed pixels if (npix1 == 0) { if (*verbosity > 1) emit messageAvailable(chipName + " : No pixels found above blooming threshold ...", "image"); return; } // detect value of blooming spike QVector pixels(npix1,0); QVector pixelcoords(npix1,0); l = 0; k = 0; for (auto &pixel : dataCurrent) { if (mask[k]) { pixels[l] = pixel; pixelcoords[l] = k; ++l; } ++k; } // The count thresholds for blooming spikes float bloommin = 0.; float bloommax = 0.; if (!bloomMin.isEmpty() && !bloomMax.isEmpty()) { // manually given; NOT IMPLEMENTED in GUI. I think the auto mode works just fine bloommin = bloomMin.toFloat(); bloommax = bloomMax.toFloat(); } else { // auto long nhist = ceil( (maxval-minval) / histstep); QVector hist(nhist,0); for (long j=0; j= minval + histstep * k && pixels[j] < minval + histstep * (k+1)) { ++hist[k]; } } } float maxhist = maxVec_T(hist); long bloommaxindex = maxIndex(hist); float bloomval = minval + bloommaxindex * histstep; // detect a reasonable dynamic range for the blooming spike long max_int = bloommaxindex; long i = 0; // was i=1; dont understand why; fails if the highest value is at the last position in hist, hence i=0 long maxindex_int = 0; while (max_int < nhist && hist[max_int] > 0.1 * maxhist) { // max_int < nhist is always fulfilled, but used here for safe coding practices max_int = bloommaxindex + i; if (max_int > nhist-1) { max_int = nhist-1; break; } maxindex_int = max_int; ++i; } long min_int = bloommaxindex; i = 0; // was i=1; dont understand why; fails if the highest value is at the last position in hist, hence i=0 long minindex_int = 0; while (hist[min_int] > 0.1 * maxhist && min_int > 0) { min_int = bloommaxindex - i; if (min_int < 0) { min_int = 0; break; } minindex_int = min_int; ++i; } float rangeval = range.toFloat(); bloommin = minval + (minindex_int - 1) * histstep - rangeval; bloommax = minval + (maxindex_int + 1) * histstep + rangeval; bloommax = bloomval + 1.5 * (bloommax - bloomval); } // qDebug() << bloommin << bloommax; // Blooming range: bloommin bloommax // keep only pixels with values within the blooming range l = 0; for (long i=0; i= bloommin && pixels[i] <= bloommax) { ++l; } } long npix2 = l; // Number of bloomed pixels QVector pixels2; QVector pixelcoords2; pixels2.reserve(npix2); pixelcoords2.reserve(npix2); for (long i=0; i= bloommin && pixels[i] <= bloommax) { pixels2.append(pixels[i]); pixelcoords2.append(pixelcoords[i]); } } // Mask the bloomed pixels in the weight for (long i=0; i 1) emit messageAvailable(chipName + " : Bloomed pixels masked. Dynamic range: "+bloomRange, "image"); } void MyImage::laplaceFilter(QVector &dataFiltered) { // Laplace kernel QVector kernel = {-1., -2., -1., -2., +12., -2., -1., -2., -1.}; // Laplace filtering using direct convolution, to enhance local defects long n = naxis1; long m = naxis2; float datatmp = 0.; float baseLevel = medianMask(dataCurrent); for (long j=1; j &data_in, QVector &data_out, int filtersize) { int s = 2*filtersize+1; int n = naxis1; int m = naxis2; s = s*s; QVector chunk(s,0); for (int j=0; j=0 && jt>=0 && it=0 && jt>=0 && it 1) emit messageAvailable(chipName + " : Filtering spurious pixels ...", "image"); long n = naxis1; long m = naxis2; QVector dataLaplace(n*m); QVector dataMedian(n*m); // Laplace filter, then median filter the Laplace filtered image laplaceFilter(dataLaplace); // CHECK: hogging some memory median2D(dataLaplace, dataMedian, 1); // CHECK: hogging some memory // Remove the median image from the Laplace image. // Suppresses residuals from bright but unsaturated stars long k = 0; for (auto &pixel : dataLaplace) { pixel -= dataMedian[k]; ++k; } float rms = 1.48 * madMask_T(dataLaplace, globalMask); float thresh = 8.0 / aggressiveFactor; // user-adjusted threshold; the higher, the lower the threshold. Default: 8 sigma detection float cutoff = thresh*rms; // Initiate cosmics mask QVector cosmicsMask(n*m, false); // Thresholding step 1 // Everything deviating by more than 'cutoff' k = 0; for (auto &pixel : dataLaplace) { // not masking negative outliers because of the compensation of the laplace kernel if (pixel > cutoff) cosmicsMask[k] = true; ++k; } // Thresholding step 2 // If pixels above and below, or left and right are masked, then the current pixel gets also masked QVector mask_tmp = cosmicsMask; for (int j=1; j cutoff) { isum += it; jsum += jt; ++count; } } } // Using the mean i and j to make sure pixels are not in the same column; // This is to avoid that a single bad column/row gets tripled in width. float meani = float(isum)/float(count); float meanj = float(jsum)/float(count); if (count >= 2 && fabs(meani-i) < 1. && fabs(meanj-j) < 1. ) cosmicsMask[i+n*j] = true; } } // Thresholding step 4 // If at least 4 out of the 8 surrounding pixels deviate by more than 0.5*cutoff, then the current pixel gets also masked for (int j=1; j 0.5*cutoff) ++count; } } if (count >= 4) cosmicsMask[i+n*j] = true; } } // Apply the cosmics mask to the weight map k = 0; for (auto &pixel : dataWeight) { if (cosmicsMask[k]) pixel = 0.; ++k; } } THELI-3.1.3/src/myimage/writefits.cc000066400000000000000000000305001417631501300171300ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include "../functions.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingStatus/processingStatus.h" #include "wcs.h" #include "wcshdr.h" #include #include #include #include void MyImage::writeImage(QString fileName, QString filter, float exptime, bool addGain) { if (!successProcessing) return; if (fileName.isEmpty()) { fileName = path+"/"+chipName+processingStatus->statusString+".fits"; } if (addGain) addGainNormalization = true; else addGainNormalization = false; bool success = write(fileName, dataCurrent, exptime, filter, header); if (success) imageOnDrive = true; else imageOnDrive = false; emit modelUpdateNeeded(chipName); } // same as above, just writes the dataTIFF vector instead void MyImage::writeImageTIFF(QString fileName, QString filter, float exptime, bool addGain) { if (!successProcessing) return; if (addGain) addGainNormalization = true; else addGainNormalization = false; static_cast (write(fileName, dataTIFF, exptime, filter, header)); } void MyImage::writeImageBackupL1() { if (!successProcessing) return; if (dataBackupL1.isEmpty() || !backupL1InMemory) return; QString fileName = pathBackupL1+"/"+chipName+statusBackupL1+".fits"; addGainNormalization = true; bool success = write(fileName, dataBackupL1, exptime, filter, header); if (success) backupL1OnDrive = true; else backupL1OnDrive = false; // emit modelUpdateNeeded(chipName); } void MyImage::writeImageBackupL2() { if (!successProcessing) return; if (dataBackupL2.isEmpty() || !backupL2InMemory) return; QString fileName = pathBackupL2+"/"+chipName+statusBackupL2+".fits"; addGainNormalization = true; bool success = write(fileName, dataBackupL2, exptime, filter, header); if (success) backupL2OnDrive = true; else backupL2OnDrive = false; // emit modelUpdateNeeded(chipName); } void MyImage::writeImageBackupL3() { if (!successProcessing) return; if (dataBackupL3.isEmpty() || !backupL3InMemory) return; QString fileName = pathBackupL3+"/"+chipName+statusBackupL3+".fits"; addGainNormalization = true; bool success = write(fileName, dataBackupL3, exptime, filter, header); if (success) backupL3OnDrive = true; else backupL3OnDrive = false; // emit modelUpdateNeeded(chipName); } void MyImage::writeBackgroundModel() { if (!successProcessing) return; mkAbsDir(path + "/SKY_IMAGES"); QString fileName = path + "/SKY_IMAGES/" + baseName+".sky.fits"; write(fileName, dataBackground, exptime, filter, header); } void MyImage::writeWeight(QString fileName) { if (!successProcessing) return; bool success = write(fileName, dataWeight, exptime, filter, header); if (success) weightOnDrive = true; else weightOnDrive = false; } void MyImage::writeWeightSmoothed(QString fileName) { if (!successProcessing) return; bool success = write(fileName, dataWeightSmooth, exptime, filter, header); if (success) weightOnDrive = true; else weightOnDrive = false; } void MyImage::writeConstSkyImage(float constValue) { if (!successProcessing) return; mkAbsDir(path+"/SKY_IMAGES"); QString fileName = path+"/SKY_IMAGES/"+baseName+".sky.fits"; writeConstImage(fileName, constValue, header); } void MyImage::writeImageDebayer(bool addGain) { if (!successProcessing) return; QString fileName = path+"/"+chipName+processingStatus->statusString+".fits"; if (addGain) addGainNormalization = true; else addGainNormalization = false; bool success = write(fileName, dataCurrent, exptime, filter, header); if (success) imageOnDrive = true; else imageOnDrive = false; emit modelUpdateNeeded(chipName); } // If the 'headerRef' member is set, the header from that image will be copied. bool MyImage::write(QString fileName, const QVector &data, const float exptime, const QString filter, const QVector header) { // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = FLOAT_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i= 0.) { fits_write_key_flt(fptr, "EXPTIME", exptime, 6, nullptr, &status); } if (!filter.isEmpty()) { fits_update_key_str(fptr, "FILTER", filter.toUtf8().data(), nullptr, &status); } if (addGainNormalization) { fits_update_key_flt(fptr, "GAINCORR", gainNormalization, 6, nullptr, &status); } fits_update_key_dbl(fptr, "MJD-OBS", mjdobs, 15, nullptr, &status); // BZERO should be 0 after THELI processing. Pixels are scaled by cfitsio already when loading images. fits_update_key_flt(fptr, "BZERO", 0.0, 6, nullptr, &status); // This image has been processed by THELI fits_update_key_lng(fptr, "THELIPRO", 1, "Indicates that this is a THELI FITS file", &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; if (status) { printCfitsioError(__func__, status); successProcessing = false; return false; } else { successProcessing = true; if (*verbosity > 1) emit messageAvailable(fileName + " : Written to drive.", "image"); return true; } // If requested, copy a reference header. This assumes that the image geometries are identical! /* if (!headerRef.isEmpty()) { fitsfile *reference_fptr = nullptr; int status_ref = 0; fits_open_file(&reference_fptr, headerRef.toUtf8().data(), READONLY, &status_ref); fits_copy_header(reference_fptr, fptr, &status_ref); fits_close_file(reference_fptr, &status_ref); printCfitsioError(__func__, status_ref); } */ } void MyImage::writeSegmentation(QString fileName) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Writing segmentation map ("+fileName+") ...", "image"); fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = LONG_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; long *array = new long[nelements]; for (long i=0; i 1) emit messageAvailable(chipName + " : Writing object mask ("+fileName+") ...", "image"); fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = LONG_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; long *array = new long[nelements]; for (long i=0; i header) { // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = FLOAT_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i= 0.) { fits_write_key_flt(fptr, "EXPTIME", exptime, 6, nullptr, &status); } if (!filter.isEmpty()) { fits_update_key_str(fptr, "FILTER", filter.toUtf8().data(), nullptr, &status); } if (addGainNormalization) { fits_update_key_flt(fptr, "GAINCORR", gainNormalization, 6, nullptr, &status); } // BZERO should be 0 after THELI processing. Pixels are scaled by cfitsio already when loading images. fits_update_key_flt(fptr, "BZERO", 0.0, 6, nullptr, &status); // This image has been processed by THELI fits_update_key_lng(fptr, "THELIPRO", 1, "Indicates that this is a THELI FITS file", &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } /* // same as write(), but also adds MJDOBS bool MyImage::writeDebayer(QString fileName, const float exptime, const QString filter, const QVector header) { // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = FLOAT_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i= 0.) { fits_write_key_flt(fptr, "EXPTIME", exptime, 6, nullptr, &status); } if (!filter.isEmpty()) { fits_update_key_str(fptr, "FILTER", filter.toUtf8().data(), nullptr, &status); } if (addGainNormalization) { fits_update_key_flt(fptr, "GAINCORR", gainNormalization, 6, nullptr, &status); } fits_update_key_dbl(fptr, "MJD-OBS", mjdobs, 15, nullptr, &status); // BZERO should be 0 after THELI processing. Pixels are scaled by cfitsio already when loading images. fits_update_key_flt(fptr, "BZERO", 0.0, 6, nullptr, &status); // This image has been processed by THELI fits_update_key_lng(fptr, "THELIPRO", 1, "Indicates that this is a THELI FITS file", &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; if (status) { printCfitsioError(__func__, status); successProcessing = false; return false; } else { successProcessing = true; if (*verbosity > 1) emit messageAvailable(fileName + " : Written to drive.", "image"); return true; } } */ THELI-3.1.3/src/preferences.cc000066400000000000000000000224771417631501300157770ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "preferences.h" #include "ui_preferences.h" #include "functions.h" #include #include #include #include #include #include #include "fitsio.h" #include Preferences::Preferences(bool running, QWidget *parent) : QDialog(parent), ui(new Ui::Preferences) { ui->setupUi(this); int maxCPU = QThread::idealThreadCount(); if (maxCPU <= 0) { emit messageAvailable("Could not determine the number of CPUs for this machine! Max number of CPUs is set to 1.", "warning"); emit warning(); maxCPU = 1; } if (!fits_is_reentrant()) maxCPU = 1; ui->prefCPUSpinBox->setMaximum(maxCPU); applyStyleSheets(); configureMemory(); // Must do before reading settings readSettings(); QFont currentFont = this->font(); int fontsize = currentFont.pointSize(); ui->prefFontsizeSpinBox->setValue(fontsize); // Prevent changes to important parameters while running if (running) { ui->parallelizationFrame->setDisabled(true); ui->memoryFrame->setDisabled(true); ui->prefIntermediateDataComboBox->setDisabled(true); } else { ui->parallelizationFrame->setEnabled(true); ui->memoryFrame->setEnabled(true); ui->prefIntermediateDataComboBox->setEnabled(true); } ui->prefServerComboBox->hide(); ui->prefDataServerLabel->hide(); ui->prefProcessSkyCheckBox->hide(); } void Preferences::configureMemory() { // Memory setup. If we have less than 10 GB then we use MB, otherwise GB. // We always leave 1 GB for the operating system and other tasks /* totalMemory = get_memory() / 1024; // [ MB ] if (totalMemory < 10000) { maxMemoryUsed = int(totalMemory) - 1024; ui->prefMemoryLabel->setText("Max usable memory [ MB ]"); ui->prefMemorySpinBox->setMinimum(500); ui->prefMemorySpinBox->setMaximum(maxMemoryUsed); } else { maxMemoryUsed = int(totalMemory / 1024) - 1; ui->prefMemoryLabel->setText("Max usable memory [ GB ]"); ui->prefMemorySpinBox->setMinimum(1); ui->prefMemorySpinBox->setMaximum(maxMemoryUsed); } */ // MB only totalMemory = get_memory() / 1024; // [ MB ] maxMemoryUsed = int(totalMemory); ui->prefMemoryLabel->setText("Max usable memory [ MB ]"); ui->prefMemorySpinBox->setMinimum(1024); ui->prefMemorySpinBox->setMaximum(maxMemoryUsed); } void Preferences::applyStyleSheets() { QList labelList; labelList.append(ui->generalLabel); labelList.append(ui->parallelizationLabel); labelList.append(ui->memoryLabel); labelList.append(ui->fontLabel); labelList.append(ui->userInterfaceLabel); for (auto &it : labelList) { it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);"); it->setMargin(8); } QList frameList; frameList.append(ui->generalFrame); frameList.append(ui->parallelizationFrame); frameList.append(ui->memoryFrame); frameList.append(ui->fontFrame); frameList.append(ui->userInterfaceFrame); /* for (auto &it : confFrameList) { // specify large style sheet? } */ QList checkboxList; checkboxList.append(ui->prefGPUCheckBox); checkboxList.append(ui->prefMemoryCheckBox); checkboxList.append(ui->prefSwitchProcessMonitorCheckBox); // for (auto &it : checkboxList) { // it->setStyleSheet("background-color: rgb(190,190,210);"); // } } void Preferences::updateParallelization(bool running) { if (running) ui->parallelizationFrame->setDisabled(true); else ui->parallelizationFrame->setEnabled(true); } Preferences::~Preferences() { delete ui; } int Preferences::writeSettings() { QSettings settings_lastproject("THELI", "PREFERENCES"); settings_lastproject.setValue("prefServerComboBox", ui->prefServerComboBox->currentText()); settings_lastproject.setValue("prefIntermediateDataComboBox", ui->prefIntermediateDataComboBox->currentText()); settings_lastproject.setValue("prefVerbosityComboBox", ui->prefVerbosityComboBox->currentIndex()); settings_lastproject.setValue("prefDiskspacewarnSpinBox", ui->prefDiskspacewarnSpinBox->value()); settings_lastproject.setValue("prefCPUSpinBox", ui->prefCPUSpinBox->value()); settings_lastproject.setValue("prefGPUCheckBox", ui->prefGPUCheckBox->isChecked()); settings_lastproject.setValue("prefProcessSkyCheckBox", ui->prefProcessSkyCheckBox->isChecked()); settings_lastproject.setValue("prefMemorySpinBox", ui->prefMemorySpinBox->value()); settings_lastproject.setValue("prefMemoryCheckBox", ui->prefMemoryCheckBox->isChecked()); settings_lastproject.setValue("prefFontsizeSpinBox", ui->prefFontsizeSpinBox->value()); settings_lastproject.setValue("prefSwitchProcessMonitorCheckBox", ui->prefSwitchProcessMonitorCheckBox->isChecked()); settings_lastproject.setValue("prefFont", this->font()); return settings_lastproject.status(); } int Preferences::readSettings() { QSettings settings("THELI", "PREFERENCES"); ui->prefDiskspacewarnSpinBox->setValue(settings.value("prefDiskspacewarnSpinBox", 256).toInt()); ui->prefVerbosityComboBox->setCurrentIndex(settings.value("prefVerbosityComboBox", 1).toInt()); ui->prefServerComboBox->setCurrentText(settings.value("prefServerComboBox").toString()); ui->prefCPUSpinBox->setValue(settings.value("prefCPUSpinBox", QThread::idealThreadCount()).toInt()); ui->prefGPUCheckBox->setChecked(settings.value("prefGPUCheckBox", false).toBool()); ui->prefProcessSkyCheckBox->setChecked(settings.value("prefProcessSkyCheckBox", false).toBool()); ui->prefFontsizeSpinBox->setValue(settings.value("prefFontsizeSpinBox").toInt()); ui->prefMemorySpinBox->setValue(settings.value("prefMemorySpinBox", maxMemoryUsed).toInt()); ui->prefSwitchProcessMonitorCheckBox->setChecked(settings.value("prefSwitchProcessMonitorCheckBox", true).toBool()); ui->prefIntermediateDataComboBox->setCurrentText(settings.value("prefIntermediateDataComboBox", "If necessary").toString()); ui->prefMemoryCheckBox->setChecked(settings.value("prefMemoryCheckBox", false).toBool()); this->setFont(settings.value("prefFont").value()); return settings.status(); } void Preferences::on_prefFontdialogPushButton_clicked() { bool ok; QFont currentFont = this->font(); QFont font = QFontDialog::getFont(&ok, QFont(currentFont), this); if (ok) { emit fontChanged(font); this->setFont(font); } int fontsize = font.pointSize(); ui->prefFontsizeSpinBox->setValue(fontsize); } void Preferences::on_prefFontsizeSpinBox_valueChanged(int arg1) { emit fontSizeChanged(arg1); } void Preferences::receiveDefaultFont(QFont font) { defaultFont = font; } void Preferences::on_prefDefaultFontPushButton_clicked() { emit fontChanged(defaultFont); this->setFont(defaultFont); int fontsize = defaultFont.pointSize(); ui->prefFontsizeSpinBox->setValue(fontsize); } void Preferences::on_prefDiskspacewarnSpinBox_valueChanged(int arg1) { emit diskspacewarnChanged(arg1); } void Preferences::on_prefCPUSpinBox_valueChanged(int arg1) { emit numcpuChanged(arg1); } void Preferences::on_prefMemoryCheckBox_clicked() { if (ui->prefMemoryCheckBox->isChecked()) { ui->prefIntermediateDataComboBox->setCurrentIndex(1); ui->prefIntermediateDataComboBox->setDisabled(true); } else { ui->prefIntermediateDataComboBox->setCurrentIndex(1); ui->prefIntermediateDataComboBox->setDisabled(false); } emit memoryUsageChanged(ui->prefMemoryCheckBox->isChecked()); } void Preferences::on_prefIntermediateDataComboBox_currentTextChanged(const QString &arg1) { if (ui->prefIntermediateDataComboBox->currentIndex() == 0) ui->prefMemoryCheckBox->setChecked(false); emit intermediateDataChanged(arg1); } void Preferences::on_prefVerbosityComboBox_currentIndexChanged(int index) { emit verbosityLevelChanged(index); } void Preferences::on_prefSwitchProcessMonitorCheckBox_clicked() { emit switchProcessMonitorChanged(ui->prefSwitchProcessMonitorCheckBox->isChecked()); } void Preferences::on_prefCancelButton_clicked() { close(); } void Preferences::on_prefCloseButton_clicked() { auto result = writeSettings(); if (result== QSettings::AccessError) { emit messageAvailable("Could not store preferences (access error).", "warning"); emit warning(); } else if (result == QSettings::FormatError) { emit messageAvailable("A formatting error occurred while writing the preferences.", "warning"); emit warning(); } emit preferencesUpdated(); close(); } THELI-3.1.3/src/preferences.h000066400000000000000000000044621417631501300156330ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef PREFERENCES_H #define PREFERENCES_H #include #include namespace Ui { class Preferences; } class Preferences : public QDialog { Q_OBJECT signals: int diskspacewarnChanged(int); int fontSizeChanged(int); int fontChanged(QFont); int instPreferenceChanged(int); int numcpuChanged(int); int serverChanged(QString); int memoryUsageChanged(bool); int intermediateDataChanged(QString); void verbosityLevelChanged(int index); void preferencesUpdated(); int switchProcessMonitorChanged(bool); void messageAvailable(QString message, QString type); void warning(); public: explicit Preferences(bool running, QWidget *parent = nullptr); ~Preferences(); private slots: void on_prefFontdialogPushButton_clicked(); void on_prefFontsizeSpinBox_valueChanged(int arg1); void on_prefDefaultFontPushButton_clicked(); void on_prefDiskspacewarnSpinBox_valueChanged(int arg1); void on_prefCPUSpinBox_valueChanged(int arg1); void on_prefMemoryCheckBox_clicked(); void on_prefIntermediateDataComboBox_currentTextChanged(const QString &arg1); void on_prefVerbosityComboBox_currentIndexChanged(int index); void on_prefSwitchProcessMonitorCheckBox_clicked(); void on_prefCancelButton_clicked(); void on_prefCloseButton_clicked(); public slots: void receiveDefaultFont(QFont); void updateParallelization(bool running); private: Ui::Preferences *ui; QFont defaultFont; float totalMemory; int maxMemoryUsed; void applyStyleSheets(); void configureMemory(); int readSettings(); int writeSettings(); }; #endif // PREFERENCES_H THELI-3.1.3/src/preferences.ui000066400000000000000000003214021417631501300160150ustar00rootroot00000000000000 Preferences 0 0 635 454 0 0 0 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 0 0 0 255 255 255 0 0 0 255 255 255 200 200 201 0 0 0 212 212 212 255 255 220 0 0 0 0 0 0 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 0 0 0 255 255 255 0 0 0 255 255 255 200 200 201 0 0 0 212 212 212 255 255 220 0 0 0 85 85 85 170 170 170 255 255 255 212 212 212 85 85 85 113 113 113 85 85 85 255 255 255 85 85 85 200 200 201 200 200 201 0 0 0 170 170 170 255 255 220 0 0 0 Preferences true 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); General setup true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Raised Disk space warning [ MB ] Store intermediate data Verbosity prefServerComboBox The amount of information shown in the monitor window Minimal Normal Full Debug When to show a warning that you are running out of disk space 256 9999 256 false When checked, SKY images are treated like science images and fully processed. Fully process SKY images Default: Store intermediate data only if necessary (reduced I/O) If necessary Always false Qt::ClickFocus The server from which to download astrometric and photometric reference catalogs Canada China France India Japan South Africa UK USA false Data server Qt::Vertical QSizePolicy::Fixed 20 20 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Parallelization true 252 252 252 235 235 238 252 252 252 235 235 238 235 235 238 235 235 238 true QFrame::StyledPanel QFrame::Raised Max number of CPUs The maximum number of CPUs THELI may use. This requires that your C++ compiler supports OpenMP v3.0 or later (e.g. GCC v4.4) Maximum number of CPUs 1 false A few tasks profit from GPU parallelization. This requires that you have GCC v6.1 or later, or another compiler that supports the OpenMP 4.5 standard. Offload calculations to the graphics card (some tasks, only). Include GPU in parallelization Qt::Vertical QSizePolicy::Fixed 20 20 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Memory usage true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Raised Max memory used The maxmimum amount of RAM THELI may use (time-averaged soft limit) MB 1024 1000000 512 By default, THELI keeps as much data as possible in memory. Minimizing memory usage results in increased I/O and slower execution.<br> Minimize memory usage Qt::Vertical QSizePolicy::MinimumExpanding 20 13 Qt::Horizontal QSizePolicy::Fixed 30 20 0 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); User interface behaviour true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Raised When clicking the Start button, THELI will switch to the process monitor to display details of the reduction process. Switch to process monitor after "Start" true Qt::Vertical QSizePolicy::Fixed 20 20 0 0 75 true color: rgb(100, 230, 230);background-color: rgb(58, 78, 98); Font settings true 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 true QFrame::StyledPanel QFrame::Raised Default font 8 Choose font [...] Font size Qt::Vertical QSizePolicy::Fixed 20 18 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 OK 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 0 0 0 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 0 0 0 255 255 255 0 0 0 255 255 255 235 235 238 0 0 0 245 245 246 255 255 220 0 0 0 117 117 119 235 235 238 255 255 255 245 245 246 117 117 119 157 157 159 117 117 119 255 255 255 117 117 119 235 235 238 235 235 238 0 0 0 235 235 238 255 255 220 0 0 0 Cancel Qt::Horizontal 17 27 Qt::Vertical 20 18 Qt::Horizontal 0 20 THELI-3.1.3/src/processingExternal/000077500000000000000000000000001417631501300170325ustar00rootroot00000000000000THELI-3.1.3/src/processingExternal/errordialog.cc000066400000000000000000000401741417631501300216600ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "errordialog.h" #include "ui_errordialog.h" #include "../functions.h" #include "../preferences.h" #include #include #include #include ErrorDialog::ErrorDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ErrorDialog) { ui->setupUi(this); // connect(ui->errorShowPushButton, &QPushButton::clicked, this, &ErrorDialog::openLogfile); readSettings(); } ErrorDialog::~ErrorDialog() { delete ui; } void ErrorDialog::update(){ ui->errorCodeLabel->setText(code); ui->errorFoundLabel->setText("An error was found in this logfile (line "+line+"):"); ui->errorExplanationTextEdit->setText(explanation); ui->errorSuggestionsTextEdit->setText(suggestion); ui->errorLogfileLineEdit->setText(logname); } void ErrorDialog::getErrorLine(QString code) { QStringList list = code.split(" "); if (list.length() >=3 ) { line = list.at(2); line.remove("):"); } else { line = ""; } } int ErrorDialog::readSettings() { QSettings settings("THELI", "PREFERENCES"); editorPreference = settings.value("prefEditorComboBox").toString(); return settings.status(); } void ErrorDialog::on_errorShowPushButton_clicked() { showLogfile(logname, line); } void ErrorDialog::translate() { // Typically, the errormessage string looks like this: // "Error (line 3743): performing run processing" // Split it by the first colon, then simplify the string thereafter // Remove everything up to and including the colon: int colonindex = code.indexOf(":"); code = code.remove(0,colonindex+1); code = code.simplified(); if (code == "Illegal instruction") { explanation = "This is an error that mostly occurs in 'scamp' during astrometry."; suggestion = "The cause for this is not known. " "Try using a denser / less dense reference catalog, adjust the object detection thresholds, and/or the scamp parameters."; } // Uncomment the following for testing purposes /* else if (code == "GUIVERSION !") { explanation = "Dummy"; suggestion = "Dummy"; } */ else if (code == "inaccuracies likely to occur") { explanation = "This warning occurs during astrometry or coaddition. It always implies a bad astrometric solution, " "which may or may not be immediately visible in your coadded image."; suggestion = "You should rerun the astrometry, trying to achieve a better solution. " "Review the checkplots in the \"plots/\" directory carefully. Were the images correctly " "identified on the sky? (fgroups_1.png)"; } else if (code == "WARNING: Not enough matched detections in ") { explanation = "This error occurs during astrometry with scamp. " "It means that for or more detectors no matches were found with the reference catalog, " "which should be immediately visible in plots/fgroups_1.png .\n" "The three most common reasons are\n" "(1) The reference catalog and the source catalog do not share sufficiently many sources\n" "(2) The true astrometric solution is outside the search space defined by the scamp parameters\n" "(3) The scamp parameters insufficiently constrain the solution space (too many false positives).\n"; suggestion = "(1) Review the checkplots. Are most images off or just a single one (which?)\n" "(2) If in a low density field, decrease the source detection thresholds for the object catalogs " " and increase the magnitude for the reference catalog to get more sources." "(3) If still unsuccessful, load the reference catalog ($HOME/.theli/scripts/theli_mystd.[skycat | reg] " " over one of your images, and see if you can match it by eye. How large are the offsets / rotations? " " Adjust POSITION_MAXERR and POSANGLE_MAXERR accordingly.\n" "(4) Reference catalog and matching parameters look fine, but still no success? " " Load the source detections (SCIENCE/cat/[ds9cat | skycat]/ over your image. " " Can you match them with the reference catalog?\n" "(5) Try the astrometry.net implementation in THELI.\n" "(1-4) should solve most problems. Think out of the box, e.g if you observe in K-band in a molecular " " cloud you'll have plenty of detetcions, but optical reference catalogs won't show anything. " " Use 2MASS instead. Or, all reference sources are badly saturated in your images and rejected " " from your source catalogs. Use deeper reference catalogs, or adjust the detection flags. " "(5) There are other cases though which are harder to crack, e.g. wide-angle fish-eye exposures, " " MCAO, etc, and there is no off-the-shelf answer what to do."; } else if (code == " 0 astrometric references loaded from theli_mystd.scamp") { explanation = "scamp does not find reference sources in the downloaded online catalog."; suggestion = "Did you download the reference catalog for the correct sky position? " "It could also be that you have one or more stray images from a different pointing in your data set, " "and that results in the reference catalog being downloaded in an area somewhere 'in between' the two " "pointings, resulting in no actual overlap with either position."; } else if (code == "WARNING: Significant inaccuracy likely to occur in projection") { explanation = "This warning occurs during coaddition. It always implies a bad astrometric solution, " "which may or may not be immediately visible in your coadded image."; suggestion = "You must rerun the astrometry and try to achieve a better solution. " "Review the checkplots in the \"plots/\" directory carefully. Were the images correctly " "identified on the sky? (fgroups_1.png)"; } else if (code == "WARNING: Null or negative global weighting factor") { explanation = "This occurs during coaddition and means that the (manually provided) " "reference coordinates do not (by a large amount) overlap with the actual pointing of your data."; suggestion = "Check the manually provided reference coordinates."; } else if (code == "fatal: division by zero attempted") { explanation = "Happens during astrometry, in case one or more images have no or very few sources. " "It could also be that there is an error with one of the download servers for the reference catalog."; suggestion = "Lower your detection thresholds. Check your images for bad ones (clouds, focus, etc). " "Try a different reference catalog or download server (under Edit->Preferences) if the problem occurs at this step."; } else if (code == "no match with reference catalog !") { explanation = "scamp does not find matching sources in the reference catalog."; suggestion = "Did you download the reference catalog for the correct sky position? " "It could also be that you have one or more stray images from a different pointing in your data set, " "and that results in the reference catalog being downloaded in an area somewhere 'in between' the two " "pointings, resulting in no actual overlap with either position.\n" "Other things to check:\n" "(1) The reference catalog and the source catalog do not share sufficiently many sources,\n" "(2) The true astrometric solution is outside the search space defined by the scamp parameters,\n" "(3) The scamp parameters insufficiently constrain the solution space (too many false positives)."; suggestion = "(1) Review the checkplots. Are most images off or just a single one (which?)\n" "(2) If in a low density field, decrease the source detection thresholds for the object catalogs " " and increase the magnitude for the reference catalog to get more sources.\n" "(3) If still unsuccessful, load the reference catalog ($HOME/.theli/scripts/theli_mystd.[skycat | reg] " " over one of your images, and see if you can match it by eye. How large are the offsets / rotations? " " Adjust POSITION_MAXERR and POSANGLE_MAXERR accordingly.\n" "(4) Reference catalog and matching parameters look fine, but still no success? " " Load the source detections (SCIENCE/cat/[ds9cat | skycat]/ over your image. " " Can you match them with the reference catalog?" "(5) Try the astrometry.net implementation in THELI.\n" "(1-4) should solve most problems. Think out of the box, e.g if you observe in K-band in a molecular " " cloud you'll have plenty of detetcions, but optical reference catalogs won't show anything. " " Use 2MASS instead. Or, all reference sources are badly saturated in your images and rejected " " from your source catalogs. Use deeper reference catalogs, or adjust the detection flags.\n" "(5) There are other cases though which are harder to crack, e.g. wide-angle fish-eye exposures, " " MCAO, etc, and there is no off-the-shelf answer what to do."; } else if (code == "Not enough memory") { explanation = "This happens either during astrometry or coaddition."; suggestion = "If in astrometry, try reducing the number of CPUs by a factor of two. " "Check the memory usage using 'top' on the command line. If doing a coaddition, are you " "creating a huge mosaic? Perhaps you have entered the wrong plate scale?"; } else if (code == "buffer overflow detected") { explanation = "This happens either during astrometry or coaddition."; suggestion = "If in astrometry, try reducing the number of CPUs by a factor of two. " "Check the memory usage using 'top' on the command line. If doing a coaddition, are you " "creating a huge mosaic? Perhaps you have entered the wrong plate scale?"; } else if (code == "did not solve") { explanation = "This error occurs when astrometry.net cannot find a solution."; suggestion = "Try running the astrometry with scamp, where you have much more control."; } else if (code == "(core dumped)") { explanation = "This is a very uncommon error implying some memory corruption."; suggestion = "If it happens during coaddition, check plate scale " "and manually provided reference coordinates."; } else if (code == "has flux scale = 0: I will take 1 instead") { explanation = "This happens during coaddition and implies a wrong / incomplete astrometric solution."; suggestion = "Check the logfile to see which image is causing the problem. Perhaps the image is bad " "and could not be solved completely during astrometry."; } else if (code == "Could not allocate memory") { explanation = "This happens most likely during astrometry or coaddition."; suggestion = "If in astrometry, try reducing the number of CPUs by a factor of two.\n" "Check the memory usage using 'top' on the command line. If doing a coaddition, are you " "creating a huge mosaic? Perhaps you have entered the wrong plate scale?"; } else if (code == "ERROR: No photometric reference sources retrieved!") { explanation = "This occurs when determining an absolute photometric zeropoint."; suggestion = "Is the WCS in your image good? Is the network connection working? " "If you used a catalog that does not have full sky coverage (e.g. SDSS, PANSTARRS), then " "this message indicates that your field is probably not covered by that catalog."; } else if (code == "ERROR: Could not find file with blank sky positions") { explanation = "The positions where the sky estimates are taken was not found."; suggestion = "If you requested a polynomial fit, then you must define blank sky positions. " "This message will also be shown if you requested a constant sky subtraction, " "with the empty sky regions set to 'Specific sky area(s)' instead of a whole chip. " "If you want to use specific areas, use the THELI internal FITS viewer to create a file with empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "ERROR: File with blank sky positions") { explanation = "The file with empty sky positions does not contain any entries."; suggestion = "Use the THELI internal FITS viewer to create a file with empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "ERROR: Less than 3 sky positions were located in the images.") { explanation = "The sky polynomial fit is underconstrained. More sky positions are required."; suggestion = "Use the THELI internal FITS viewer to create a file with sufficiently many empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "ERROR: Insufficient number of sky positions for a model of degree") { explanation = "The sky polynomial fit is underconstrained. More sky positions are required."; suggestion = "Use the THELI internal FITS viewer to create a file with sufficiently many empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "Did not create any quads") { explanation = "astrometry.net did not create any quads, which are used for pattern matching between source and reference catalog"; suggestion = "This can happen if the source density is very low. Try using a different reference catalog."; } else if (code == "solve-field: invalid option --") { explanation = "The syntax of astrometry.net has changed."; suggestion = "THELI is not using the correct syntax for astrometry.net. Please send the logfile to schirmer@mpia.de ."; } } void ErrorDialog::on_errorLogfileLineEdit_textChanged(const QString &arg1) { paintPathLineEdit(ui->errorLogfileLineEdit, arg1, "file"); } THELI-3.1.3/src/processingExternal/errordialog.h000066400000000000000000000025171417631501300215210ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef ERRORDIALOG_H #define ERRORDIALOG_H #include namespace Ui { class ErrorDialog; } class ErrorDialog : public QDialog { Q_OBJECT public: explicit ErrorDialog(QWidget *parent = nullptr); ~ErrorDialog(); QString code; QString title; QString explanation; QString suggestion; QString logname; QString line; void translate(); void getErrorLine(QString code); void update(); private slots: void on_errorShowPushButton_clicked(); void on_errorLogfileLineEdit_textChanged(const QString &arg1); private: Ui::ErrorDialog *ui; QString editorPreference; int readSettings(); }; #endif // ERRORDIALOG_H THELI-3.1.3/src/processingExternal/errordialog.ui000066400000000000000000000160031417631501300217020ustar00rootroot00000000000000 ErrorDialog 0 0 740 573 THELI Error translation An error was found in this logfile (line XXXX): Qt::Horizontal 216 20 Qt::NoFocus Show logfile Qt::NoFocus true 75 true Error code: 170 0 0 170 0 0 119 120 120 75 true true false Message Qt::Horizontal 40 20 Qt::Vertical QSizePolicy::Fixed 20 18 75 true Explanation: 0 0 16777215 100 Qt::NoFocus QFrame::Panel true Qt::Vertical QSizePolicy::Fixed 20 18 75 true Suggestions how to solve this: Qt::NoFocus QFrame::Panel 1 true Qt::Horizontal 217 20 Close errorClosePushButton clicked() ErrorDialog close() 563 570 504 569 THELI-3.1.3/src/processingInternal/000077500000000000000000000000001417631501300170245ustar00rootroot00000000000000THELI-3.1.3/src/processingInternal/controller.cc000066400000000000000000001466671417631501300215420ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "instrumentdata.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "ui_memoryviewer.h" #include "../dockwidgets/monitor.h" #include "../myimage/myimage.h" #include "../functions.h" #include "../preferences.h" #include "../tools/cfitsioerrorcodes.h" #include #include #include #include #include #include #include #include #include #include Controller::Controller(const instrumentDataType *instrumentData, QString statusold, ConfDockWidget *confDockWidget, Monitor *processMonitor, MainWindow *parent) : QMainWindow(parent), cdw(confDockWidget), instData(instrumentData) { mainGUI = parent; // cdw = confDockWidget; // instData = instrumentData; statusOld = statusold; monitor = processMonitor; // Load detector info only if an instrument has been selected // In some instances, e.g. deleting all manually defined user insts, this command would fail // Same for the masks if (!instrumentData->nameFullPath.isEmpty()) { getDetectorSections(); mask = new Mask(instData, this); } // Before populating all Data objects omp_init_lock(&lock); omp_init_lock(&memoryLock); omp_init_lock(&wcsLock); omp_init_lock(&genericLock); omp_init_lock(&progressLock); omp_init_lock(&backgroundLock); loadPreferences(); // Populate data tree mapDataTree(); // Tell DT_x about the memory preference updateMemoryPreference(minimizeMemoryUsage); // Initialization initEnvironment(thelidir, userdir); instrument_dir = mainGUI->instrument_dir; // loadPreferences(); externalProcess = new QProcess(this); // connect(externalProcess, &QProcess::readyReadStandardOutput, this, &Controller::processExternalStdout); // connect(externalProcess, &QProcess::readyReadStandardError, this, &Controller::processExternalStderr); stdoutByteArray = new QByteArray(); stderrByteArray = new QByteArray(); stdoutByteArray->reserve(10000); stderrByteArray->reserve(10000); // setupExternalProcesses(); populateCommentMap(); // Done at top level, so it is not repeated many times by the Splitter class populateHeaderDictionary(); populateFilterDictionary(); populateInstrumentDictionary(); // Daisy-chaining scamp, and the coadditions connect(this, &Controller::showScampCheckPlots, this, &Controller::showScampCheckPlotsReceived); connect(this, &Controller::swarpStartResampling, this, &Controller::coaddResample); connect(this, &Controller::swarpStartSwarpfilter, this, &Controller::coaddSwarpfilter); connect(this, &Controller::swarpStartCoaddition, this, &Controller::coaddCoaddition); connect(this, &Controller::swarpStartUpdate, this, &Controller::coaddUpdate); progressTimer = new QTimer(this); connect(progressTimer, SIGNAL(timeout()), SLOT(displayProgress())); progressTimer->start(100); } void Controller::getNumberOfActiveImages(Data *&data) { numActiveImages = 0; progress = 0.; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : data->myImageList.at(chip)) { if (it->activeState == MyImage::ACTIVE) ++numActiveImages; } } progressStepSize = 100./(float(numActiveImages)); progressHalfStepSize = 0.5*progressStepSize; // Last 5% are reserved for mode determination and writing to drive // 45% are in Data::combineImagesCalib() for combination progressCombinedStepSize = 5./instData->numUsedChips; } Controller::~Controller() { for (auto &DT_x : masterListDT) { for (auto &it : DT_x) { delete it; it = nullptr; } } delete GLOBALWEIGHTS; GLOBALWEIGHTS = nullptr; // mask->reset(); delete mask; mask = nullptr; omp_destroy_lock(&lock); omp_destroy_lock(&memoryLock); omp_destroy_lock(&genericLock); omp_destroy_lock(&progressLock); omp_destroy_lock(&backgroundLock); for (auto &it : externalProcesses) { delete it; it = nullptr; } // delete externalProcess; delete stdoutByteArray; delete stderrByteArray; stdoutByteArray = nullptr; stderrByteArray = nullptr; } // Reads whatever is defined in the Setup data tree section, and maps it onto the various lists void Controller::mapDataTree() { if (QDir(mainDirName) == QDir::home()) { emit messageAvailable("For safety reasons, your home directory is not permitted as the main directory.", "error"); criticalReceived(); return; } dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); mainDirName = mainGUI->ui->setupMainLineEdit->text(); recurseCounter = 0; parseDataDir(mainGUI->ui->setupBiasLineEdit, DT_BIAS); recurseCounter = 0; parseDataDir(mainGUI->ui->setupDarkLineEdit, DT_DARK); recurseCounter = 0; parseDataDir(mainGUI->ui->setupFlatoffLineEdit, DT_FLATOFF); recurseCounter = 0; parseDataDir(mainGUI->ui->setupFlatLineEdit, DT_FLAT); recurseCounter = 0; parseDataDir(mainGUI->ui->setupScienceLineEdit, DT_SCIENCE); recurseCounter = 0; parseDataDir(mainGUI->ui->setupSkyLineEdit, DT_SKY); recurseCounter = 0; parseDataDir(mainGUI->ui->setupStandardLineEdit, DT_STANDARD); recurseCounter = 0; updateMasterList(); if (QDir(mainDirName+"/GLOBALWEIGHTS/").exists()) { GLOBALWEIGHTS = new Data(instData, mask, mainDirName, "GLOBALWEIGHTS", &verbosity); GLOBALWEIGHTS->maxExternalThreads = maxExternalThreads; GLOBALWEIGHTS->progress = &progress; GLOBALWEIGHTS->dataType = "GLOBALWEIGHT"; connect(GLOBALWEIGHTS, &Data::statusChanged, mainGUI, &MainWindow::statusChangedReceived); connect(GLOBALWEIGHTS, &Data::messageAvailable, this, &Controller::messageAvailableReceived); connect(GLOBALWEIGHTS, &Data::appendOK, this, &Controller::appendOKReceived); connect(GLOBALWEIGHTS, &Data::critical, this, &Controller::criticalReceived); connect(GLOBALWEIGHTS, &Data::warning, this, &Controller::warningReceived); connect(GLOBALWEIGHTS, &Data::showMessageBox, this, &Controller::showMessageBoxReceived); connect(GLOBALWEIGHTS, &Data::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(GLOBALWEIGHTS, &Data::setWCSLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); // if (memoryViewer != nullptr) { // connect(GLOBALWEIGHTS, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); // } GLOBALWEIGHTS->setParent(this); globalweights_created = true; } emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } // Parse the data tree entries // Construct the Data entities void Controller::parseDataDir(QLineEdit *le, QList &DT_x) { DT_x.clear(); if (!QDir(mainDirName).exists() || mainDirName.isEmpty() || le->text().isEmpty()) return; bool successFileScan = true; QString badDirName = ""; QStringList dirs = le->text().replace(","," ").simplified().split(" "); for (auto &it : dirs) { // do not accept any wrong entries; empty the list if (!QDir(mainDirName+"/"+it).exists()) { DT_x.clear(); return; } if (QDir(mainDirName) == QDir::home()) { emit messageAvailable("For safety reasons, your home directory is not permitted as the main directory.", "error"); criticalReceived(); return; } Data *data = new Data(instData, mask, mainDirName, it, &verbosity); connect(data, &Data::statusChanged, mainGUI, &MainWindow::statusChangedReceived); connect(data, &Data::messageAvailable, this, &Controller::messageAvailableReceived); connect(data, &Data::appendOK, this, &Controller::appendOKReceived); connect(data, &Data::critical, this, &Controller::criticalReceived); connect(data, &Data::warning, this, &Controller::warningReceived); connect(data, &Data::showMessageBox, this, &Controller::showMessageBoxReceived); connect(data, &Data::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(data, &Data::setWCSLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); connect(data, &Data::addToProgressBar, this, &Controller::addToProgressBarReceived); connect(data, &Data::errorOccurredInMyImage, this, &Controller::criticalReceived); // if (memoryViewer != nullptr) { // connect(data, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); // } data->setParent(this); data->maxExternalThreads = maxExternalThreads; data->progress = &progress; if (le == mainGUI->ui->setupBiasLineEdit) data->dataType = "BIAS"; else if (le == mainGUI->ui->setupDarkLineEdit) data->dataType = "DARK"; else if (le == mainGUI->ui->setupFlatoffLineEdit) data->dataType = "FLATOFF"; else if (le == mainGUI->ui->setupFlatLineEdit) data->dataType = "FLAT"; else if (le == mainGUI->ui->setupScienceLineEdit) data->dataType = "SCIENCE"; else if (le == mainGUI->ui->setupSkyLineEdit) data->dataType = "SKY"; else if (le == mainGUI->ui->setupStandardLineEdit) data->dataType = "STANDARD"; else { // nothing yet } // Check status consistency successFileScan = data->checkStatusConsistency(); if (!successFileScan) { badDirName = data->dirName; break; } // Needs to know the dataType, hence here and not further up data->broadcastNumberOfFiles(); DT_x << data; } if (!successFileScan) { emit messageAvailable(badDirName + " : Inconsistency detected between FITS file names and recorded processing status.
Inferring status from file names ...", "warning"); /* if (recurseCounter > 1) { qDebug() << badDirName << ": The FITS files found do not match the recorded status"; qDebug() << "Either restore the files manually, or use the memory viewer to set the correct status."; qDebug() << "Restart recommended."; // TODO: the signal emitted is received by the controller and re-emitted, but not received by MainWindow. very odd. hence the message Available(); // Edit: even that signal is not received! emit messageAvailable("
" + badDirName + tr(": The FITS files found do not match the recorded status.\n")+ tr("Either restore the files manually, or use the 'Processing status' menu to reflect the current status.
Restart recommended."), "error"); emit criticalReceived(); emit showMessageBox("Data::INCONSISTENT_DATA_STATUS", badDirName, "status"); return; } */ // RECURSIVE // must repeat everything (simplest implementation), at max once if (recurseCounter == 0) { ++recurseCounter; // Must set before entering same function again! parseDataDir(le, DT_x); } } } void Controller::updateMasterList() { // A full refresh of the master list, e.g. if a data directory was edited in the UI (triggering a parse); masterListDT.clear(); masterListDT << DT_BIAS << DT_DARK << DT_FLATOFF << DT_FLAT << DT_SCIENCE << DT_SKY << DT_STANDARD; } void Controller::rereadScienceDataDirReceived() { dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); for (auto &data: DT_SCIENCE) { delete data; data = nullptr; } DT_SCIENCE.clear(); parseDataDir(mainGUI->ui->setupScienceLineEdit, DT_SCIENCE); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; // And do the final GUI updates to signal processing has finished if (successProcessing) { emit progressUpdate(100); pushEndMessage(taskBasename, "SCIENCE"); } } // Receiving end from setMemoryLock calls within other classes void Controller::setMemoryLockReceived(bool locked) { if (locked) omp_set_lock(&memoryLock); else omp_unset_lock(&memoryLock); } // Receiving end from setWCSLock calls within other classes void Controller::setWCSLockReceived(bool locked) { if (locked) omp_set_lock(&wcsLock); else omp_unset_lock(&wcsLock); } long Controller::makeListofAllImages(QList &allMyImages, Data *data) { allMyImages.clear(); for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; // incrementCurrentThreads(lock); for (auto &it : data->myImageList[chip]) { allMyImages.append(it); } } return allMyImages.length(); } // Rescan the data tree if a LineEdit was successfully edited void Controller::dataTreeEditedReceived() { // Do not do anything while loading a new project (causes crashes in memoryviewer) if (mainGUI->readingSettings) return; QLineEdit* lineEdit = qobject_cast(sender()); // CASE 1: The main data dir has changed. Must update everything. QString maindir = mainGUI->ui->setupMainLineEdit->text(); if (lineEdit == mainGUI->ui->setupMainLineEdit) { QDir dir(maindir); if (dir.exists()) mapDataTree(); return; } // CASE 2: A single element of the data tree has changed QStringList list = datadir2StringList(lineEdit); // Loop over the directories and check whether they exist for (int i=0; iobjectName(); if (name == "setupBiasLineEdit") parseDataDir(lineEdit, DT_BIAS); else if (name == "setupDarkLineEdit") parseDataDir(lineEdit, DT_DARK); else if (name == "setupFlatoffLineEdit") parseDataDir(lineEdit, DT_FLATOFF); else if (name == "setupFlatLineEdit") parseDataDir(lineEdit, DT_FLAT); else if (name == "setupScienceLineEdit") parseDataDir(lineEdit, DT_SCIENCE); else if (name == "setupSkyLineEdit") parseDataDir(lineEdit, DT_SKY); else if (name == "setupStandardLineEdit") parseDataDir(lineEdit, DT_STANDARD); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } void Controller::checkForUnsavedImages(long &numUnsavedLatest, long &numUnsavedBackup) { numUnsavedLatest = 0; numUnsavedBackup = 0; for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { data->countUnsavedImages(numUnsavedLatest, numUnsavedBackup); } } } void Controller::writeUnsavedImagesToDrive(bool includeBackup) { emit messageAvailable("Writing images to disk", "controller"); criticalReceived(); // Do not need to loop over globalweights (they are always saved) for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { data->writeUnsavedImagesToDrive(includeBackup); } } emit messageAvailable("Done writing images ...", "controller"); } void Controller::wipeDataTree() { // Lock, so it doesn't interfere with memory progress bar dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); releaseAllMemory(); // The call above just releases the processed pixels kept in memory, it does NOT clear the image lists as such for (auto &DT_x : masterListDT) { if (!DT_x.isEmpty()) { for (auto &it : DT_x) { it->dataInitialized = false; it->processingStatus = nullptr; it->myImageList.clear(); delete it; it = nullptr; } DT_x.clear(); } } if (globalweights_created) { delete GLOBALWEIGHTS; GLOBALWEIGHTS = nullptr; globalweights_created = false; } masterListDT.clear(); emit clearMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } void Controller::newProjectLoadedReceived() { // wipeDataTree(); // Done in MainWindow::on_setupProjectLoadPushButton_clicked(); // Must be done then because e.g. the number of chips changes. // Infer the status of the project statusOld = mainGUI->status.getStatusFromHistory(); // Re-read full data tree mapDataTree(); } void Controller::displayProgress() { emit progressUpdate(progress); } void Controller::updateAll() { // Reset all masks mask->reset(); mask->instData = instData; mask->initMasks(); // For GROND (and other multi-channel instruments) provideAlternativeMask(); // instData member is a pointer and does not need updating when a new instrument is selected (true? must check!) mapDataTree(); // updates the memory view } // so far called in MainGUIWorker::runTask(); should be done better by signal emission void Controller::loadPreferences() { // Start with max number of CPUs (updated with user preference below) QSettings settings("THELI", "PREFERENCES"); maxCPU = settings.value("prefCPUSpinBox", QThread::idealThreadCount()).toInt(); useGPU = settings.value("prefGPUCheckBox", false).toBool(); maxRAM = 0.75 * settings.value("prefMemorySpinBox").toInt(); // 75% of RAM verbosity = settings.value("prefVerbosityComboBox", 1).toInt(); if (settings.value("prefIntermediateDataComboBox", "If necessary") == "If necessary") alwaysStoreData = false; else alwaysStoreData = true; minimizeMemoryUsage = settings.value("prefMemoryCheckBox", false).toBool(); availableThreads = maxCPU; verbosity = settings.value("prefVerbosityComboBox").toInt(); if (settings.status() != QSettings::NoError) { emit messageAvailable("WARNING: Could not retrieve CPU and GPU parameters from preferences. Parallelization deactivated.", "warning"); maxCPU = 1; maxThreadsIO = 1; maxExternalThreads = 1; maxInternalThreads = 1; maxRAM = 1024; useGPU = false; verbosity = 1; } // We have maxExternalThreads, which is the max number of threads working on independent detectors. // If more CPUs than detectors, limit this number so that we have left-over threads for further parallelization // (internal threads in Data class) if (maxCPU > instData->numUsedChips) { // maxExternalThreads = instData->numUsedChips; // NO! The loops skipped for a bad chip will just wait until another CPU becomes available. maxExternalThreads = instData->numChips; // keep full number of CPUs instead maxInternalThreads = maxCPU - maxExternalThreads + 1; } else { maxExternalThreads = maxCPU; maxInternalThreads = 1; } pushParallelizationToData(DT_BIAS); pushParallelizationToData(DT_DARK); pushParallelizationToData(DT_FLATOFF); pushParallelizationToData(DT_FLAT); pushParallelizationToData(DT_SCIENCE); pushParallelizationToData(DT_SKY); pushParallelizationToData(DT_STANDARD); if (GLOBALWEIGHTS != nullptr) pushParallelizationToData(GLOBALWEIGHTS); // For Swarp coaddition externalProcesses.resize(maxCPU); for (int i=0; i DT_x) { if (DT_x.isEmpty()) return; for (auto &it : DT_x) { if (it == nullptr) continue; it->maxCPU = maxCPU; it->maxExternalThreads = maxExternalThreads; it->maxThreadsIO = maxThreadsIO; it->useGPU = useGPU; it->maxRAM = maxRAM; } } void Controller::pushParallelizationToData(Data *data) { if (data == nullptr) return; data->maxCPU = maxCPU; data->maxExternalThreads = maxExternalThreads; data->maxThreadsIO = maxThreadsIO; data->useGPU = useGPU; data->maxRAM = maxRAM; } void Controller::addToProgressBarReceived(const float differential) { omp_set_lock(&progressLock); progress += differential; emit progressUpdate(progress); omp_unset_lock(&progressLock); } void Controller::releaseAllMemory() { // memory lock set in caller // Globalweights if (GLOBALWEIGHTS != nullptr) { GLOBALWEIGHTS->releaseAllMemory(); } // Pass through normal data tree for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { if (data == nullptr) continue; data->releaseAllMemory(); } } } void Controller::doDataFitInRAM(const long nImages, const long storageSize) { if (alwaysStoreData) return; // we are good if (nImages*storageSize > maxRAM) { alwaysStoreData = true; QSettings settings("THELI", "PREFERENCES"); settings.setValue("prefIntermediateDataComboBox", "Always"); if (settings.status() != QSettings::NoError) { emit messageAvailable("Could not update preferences concerning intermediate data storage", "warning"); } else { emit messageAvailable("******************************************************", "note"); emit messageAvailable("High memory use expected. Will write FITS images to drive on the fly.", "note"); emit messageAvailable("******************************************************
", "note"); } } } void Controller::releaseMemory(float RAMneededThisThread, int numThreads, QString mode) { // Requested by several threads, hence this must be locked omp_set_lock(&memoryLock); float RAMfreed = 0.; bool RAMwasReallyReleased = false; float currentTotalMemoryUsed = mainGUI->myRAM->getRAMload(); // Globalweights if (GLOBALWEIGHTS != nullptr && globalweights_created) { GLOBALWEIGHTS->releaseMemory(RAMneededThisThread, RAMneededThisThread*numThreads, currentTotalMemoryUsed, mode); } // Pass through normal data tree for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { if (data == nullptr) continue; // memviewer is updated by signals emitted by MyImage class float released = data->releaseMemory(RAMneededThisThread, RAMneededThisThread*numThreads, currentTotalMemoryUsed, mode); if (released >= 0.) { RAMfreed += released; RAMwasReallyReleased = true; } } } // float RAMstillneeded = RAMneededThisThread - RAMfreed; if (RAMfreed < RAMneededThisThread && RAMwasReallyReleased && currentTotalMemoryUsed > 0. && RAMfreed < currentTotalMemoryUsed - 100 // 100 is to suppress insignificant warnings && RAMneededThisThread > maxRAM - currentTotalMemoryUsed) { // && !swapWarningShown) { if (verbosity > 1) { emit messageAvailable(QString::number(long(RAMneededThisThread)) + " MB requested, " + QString::number(long(RAMfreed)) + " MB released. Try fewer CPUs to avoid swapping.", "warning"); } swapWarningShown = true; } // emit messageAvailable("Released "+QString::number(long(RAMfreed)) + " MB", "note"); if (RAMfreed >= RAMneededThisThread && RAMwasReallyReleased) { if (verbosity >= 2) emit messageAvailable("Released "+QString::number(long(RAMfreed)) + " MB", "note"); } omp_unset_lock(&memoryLock); } // This function is called after each task to respect the maximum amount of memory allowed by the user. // Actual use may overshoot during processing void Controller::satisfyMaxMemorySetting() { // Requested by several threads, hence this must be locked omp_set_lock(&memoryLock); float RAMfreed = 0.; bool RAMwasReallyReleased = false; float currentTotalMemoryUsed = mainGUI->myRAM->getRAMload(); float mustReleaseRAM = currentTotalMemoryUsed - maxRAM; // Globalweights if (GLOBALWEIGHTS!= nullptr) { GLOBALWEIGHTS->releaseMemory(mustReleaseRAM, mustReleaseRAM, currentTotalMemoryUsed); } // Pass through normal data tree for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { float released = data->releaseMemory(mustReleaseRAM, mustReleaseRAM, currentTotalMemoryUsed); if (released >= 0.) { RAMfreed += released; RAMwasReallyReleased = true; } } } if (RAMfreed < mustReleaseRAM && RAMwasReallyReleased && !swapWarningShown) { emit messageAvailable("Tried to release "+QString::number(long(mustReleaseRAM)) + " MB, " + QString::number(long(RAMfreed)) + " MB actually released.", "warning"); swapWarningShown = true; } if (RAMfreed >= mustReleaseRAM && RAMwasReallyReleased) { if (verbosity >= 2) emit messageAvailable("Released "+QString::number(long(RAMfreed)) + " MB", "note"); } omp_unset_lock(&memoryLock); } void Controller::checkSuccessProcessing(const Data *data) { if (userStop || userKill) { emit messageAvailable("Aborted", "stop"); return; } if (!data->successProcessing) { successProcessing = false; emit messageAvailable("Data processing in " + data->dirName + " unsuccessful.", "error"); criticalReceived(); } } // Shows a message box where the user can optionally trigger a clearance of the error state. // The task that triggers this bool Controller::testResetDesire(const Data *data) { if (!data->successProcessing) { emit showMessageBox("Controller::RESET_REQUESTED", data->subDirName, ""); return false; } return true; } void Controller::getDetectorSections() { overscanX.clear(); overscanY.clear(); dataSection.clear(); overscanX.resize(instData->numChips); overscanY.resize(instData->numChips); dataSection.resize(instData->numChips); QVector xmin = instData->overscan_xmin; QVector xmax = instData->overscan_xmax; QVector ymin = instData->overscan_ymin; QVector ymax = instData->overscan_ymax; // to stay safe, i include chips that are not used for (int chip=0; chipnumChips; ++chip) { // Overscan X QVector overscanxRegion; if (!xmin.isEmpty() && !xmax.isEmpty()) overscanxRegion << xmin[chip] << xmax[chip]; overscanX[chip] << overscanxRegion; // Overscan Y QVector overscanyRegion; if (!ymin.isEmpty() && !ymax.isEmpty()) overscanyRegion << ymin[chip] << ymax[chip]; overscanY[chip] << overscanyRegion; // Data Section QVector section; section << instData->cutx[chip]; section << instData->cutx[chip] + instData->sizex[chip] - 1; // sizex is not a coordinate, but the number of pixels along this axis. Hence -1 section << instData->cuty[chip]; section << instData->cuty[chip] + instData->sizey[chip] - 1; // sizey is not a coordinate, but the number of pixels along this axis. Hence -1 dataSection[chip] << section; } } QList> Controller::getNonlinearityCoefficients() { QList> coeffs; QString coeffsFileName = instrument_dir+"/"+instData->name+".nldat"; QFile coeffsFile(coeffsFileName); // Read the coefficients if( !coeffsFile.open(QIODevice::ReadOnly)) { // return empty list if file does not exist return coeffs; } QTextStream in(&coeffsFile); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty() || line.contains("#")) continue; // Extract the coefficients and put them into a QVector line = line.simplified(); QStringList values = line.split(" "); QVector vecData; for (auto &it : values) { vecData.push_back(it.toFloat()); } coeffs.append(vecData); } coeffsFile.close(); if (coeffs.length() != instData->numChips) { QMessageBox::warning(this, tr("Inconsistent number of nonlinearity coefficients"), tr("The file with nonlinearity coefficients,\n")+coeffsFileName+ tr("contains entries (lines) for")+QString::number(coeffs.length())+" detectors.\n"+ tr("However, ")+instData->name+tr(" has")+QString::number(instData->numChips)+tr(" detectors.")+ tr("Data processing will continue without non-linearity correction."), QMessageBox::Ok); coeffs.clear(); } return coeffs; } void Controller::resetErrorStatusReceived(QString dirName) { Data *data = getDataAll(dirName); if (data != nullptr) { data->resetSuccessProcessing(); } } QVector Controller::getBackgroundThresholds(const int loop, const bool twoPass, const QString DT, const QString DMIN, bool &doSourceDetection) { QVector thresholds; // No thresholds specified, or in first loop of twoPass mode: don't do source detection if (DT.isEmpty() || DMIN.isEmpty() || (twoPass && loop == 0)) { doSourceDetection = false; thresholds << "" << ""; // not evaluated later-on return thresholds; } // Thresholds specified: detection depends on whether we are in twopass mode or not else if (!twoPass || loop == 1) { // loop == 1 implies twoPass = true doSourceDetection = true; thresholds << DT << DMIN; return thresholds; } else { // should be cought by previous 'else if' emit messageAvailable("Controller::getBackgroundThresholds(): Code should never enter here!", "error"); criticalReceived(); successProcessing = false; doSourceDetection = false; thresholds << DT << DMIN; return thresholds; } } // Updates the processing status, and also creates a backup file on drive (if the FITS file exists) void Controller::updateImageAndData(MyImage *image, Data *data) { bool *s = nullptr; if (taskBasename == "HDUreformat") s = &image->processingStatus->HDUreformat; else if (taskBasename == "Processscience") s = &image->processingStatus->Processscience; else if (taskBasename == "Chopnod") s = &image->processingStatus->Chopnod; else if (taskBasename == "Background") s = &image->processingStatus->Background; else if (taskBasename == "Collapse") s = &image->processingStatus->Collapse; else if (taskBasename == "Starflat") s = &image->processingStatus->Starflat; else if (taskBasename == "Skysub") s = &image->processingStatus->Skysub; else { emit messageAvailable("Controller::updateProcessingStatus(): Invalid taskBasename. This is a bug!", "error"); criticalReceived(); return; } // Status of Data class becomes immediately false if the status of a single image is false if (image->successProcessing) { // Update the status (processing was successful) *s = true; QString statusNew = image->processingStatus->getStatusString(); // Update members in MyImage class image->processingStatus->statusString = statusNew; image->baseName = image->chipName + statusNew; // New pixel data are not yet on drive image->imageOnDrive = false; } else { *s = false; data->successProcessing = false; } } // The top level entry function for MainWindow to initiate a task void Controller::runTask() { if (!successProcessing) return; // Reset the process progress bar emit resetProgressBar(); // call the function by its string representation (needs a const char *) bool test = true; if (taskBasename == "processScience") { // Calls test = QMetaObject::invokeMethod(this, ("taskInternal"+taskBasename).toStdString().c_str(), Qt::DirectConnection, Q_ARG(QList, DT_SCIENCE)); } else { test = QMetaObject::invokeMethod(this, ("taskInternal"+taskBasename).toStdString().c_str(), Qt::DirectConnection); } if (!test) { emit messageAvailable("Controller::runTask(): Could not evaluate QMetaObject for " +taskBasename, "error"); criticalReceived(); return; } } // Identify the Data class that corresponds to directory dirName, and return a link to that class Data* Controller::getData(QList DT_x, QString dirName) { for (auto &it : DT_x) { if (QDir::cleanPath(it->dirName) == QDir::cleanPath(mainDirName + "/" + dirName)) { // check if it contains mastercalib data it->checkPresenceOfMasterCalibs(); if (it->isEmpty()) return nullptr; else return it; } } emit messageAvailable("Controller::getData(): Directory " + dirName + " not found in Data class for " + DT_x[0]->dirName, "error"); criticalReceived(); return nullptr; } // Identify the Data class that corresponds to directory dirName, and return a link to that class // Used if we don't know the top level category of that directory // TODO: Check what happens if we use e.g. the same science directory as a science directory as well as a flat directory. Prohibit this at software level? Data* Controller::getDataAll(QString dirName) { for (auto &DT_x : masterListDT) { for (auto &it : DT_x) { if (QDir::cleanPath(it->dirName) == QDir::cleanPath(mainDirName + "/" + dirName)) { // check if it contains mastercalib data it->checkPresenceOfMasterCalibs(); return it; } } } emit messageAvailable("Controller::getDataAll(): Directory " + dirName + " not found in Data classes.", "error"); criticalReceived(); return nullptr; } // Decide which data can (or cannot) be deleted from memory void Controller::memoryDecideDeletableStatus(Data *data, bool deletable) { for (int chip=0; chipnumChips; ++chip) { data->memorySetDeletable(chip, "dataBackupL1", deletable); } } QString Controller::getUserParamLineEdit(const QLineEdit *le) { QString value = le->text(); if (value == "") value = cdw->defaultMap[le->objectName()]; return value; } QString Controller::getUserParamCheckBox(const QCheckBox *cb) { if (cb->isChecked()) return "Y"; else return "N"; } QString Controller::getUserParamComboBox(const QComboBox *cb) { return cb->currentText(); } void Controller::pushBeginMessage(const QString idstring, const QString targetdir) { QString message = commentMap.value(idstring); emit messageAvailable("
##############################################", "output"); emit messageAvailable(message+" "+targetdir, "controller"); emit messageAvailable("##############################################
\n", "output"); } void Controller::pushEndMessage(const QString idstring, const QString targetdir) { QString message = commentMap.value(idstring); emit messageAvailable("
##############################################", "output"); emit messageAvailable(message+" "+targetdir+"... DONE.", "controller"); emit messageAvailable("##############################################
\n", "output"); } void Controller::updateMemoryPreference(bool isRAMminimized) { minimizeMemoryUsage = isRAMminimized; sendMemoryPreferenceToImages(DT_BIAS); sendMemoryPreferenceToImages(DT_DARK); sendMemoryPreferenceToImages(DT_FLATOFF); sendMemoryPreferenceToImages(DT_FLAT); sendMemoryPreferenceToImages(DT_SCIENCE); sendMemoryPreferenceToImages(DT_SKY); sendMemoryPreferenceToImages(DT_STANDARD); if (GLOBALWEIGHTS != nullptr) sendMemoryPreferenceToImages(DT_STANDARD); } void Controller::updateIntermediateDataPreference(QString intermediateDataPreference) { if (intermediateDataPreference == "Always") alwaysStoreData = true; else alwaysStoreData = false; } void Controller::criticalReceived() { abortProcess = true; emit messageAvailable("Abort.", "stop"); monitor->raise(); } void Controller::warningReceived() { monitor->raise(); } void Controller::messageAvailableReceived(QString message, QString type) { emit messageAvailable(message, type); } void Controller::appendOKReceived() { emit appendOK(); } void Controller::showMessageBoxReceived(QString trigger, QString part1, QString part2) { emit showMessageBox(trigger, part1, part2); } void Controller::updateVerbosity(int verbosityLevel) { verbosity = verbosityLevel; } void Controller::sendMemoryPreferenceToImages(QList DT_x) { if (DT_x.isEmpty()) return; // including chips the user does not want to use for (auto &data : DT_x) { for (int chip=0; chipinstData->numChips; ++chip) { for (auto &it : data->myImageList[chip]) { it->minimizeMemoryUsage = minimizeMemoryUsage; } } } } void Controller::restoreAllRawData() { // memory lock set in caller; NO IT IS NOT! // restore button deactivated while task is running #pragma omp parallel for num_threads(maxCPU) for (int i=0; idir.absolutePath() == QDir::homePath()) { QMessageBox::warning( this, "Dangerous data tree", "The full path to " + it->dirName+"is identical to your home directory!\nTHELI will not delete / restore any data in this directory."); continue; } else { it->restoreRAWDATA(); } } } if (GLOBALWEIGHTS != nullptr) GLOBALWEIGHTS->releaseAllMemory(); QDir globalweightsDir(mainDirName+"/GLOBALWEIGHTS/"); if (globalweightsDir.exists()) { emit messageAvailable("Deleting " + mainDirName+"/GLOBALWEIGHTS/" + "...", "controller"); globalweightsDir.removeRecursively(); } QDir weightsDir(mainDirName+"/WEIGHTS/"); if (weightsDir.exists()) { emit messageAvailable("Deleting " + mainDirName+"/WEIGHTS/" + "...", "controller"); weightsDir.removeRecursively(); } updateMasterList(); mainGUI->status.clearAllCheckBoxes(); cdw->ui->ARCpmRALineEdit->clear(); cdw->ui->ARCpmDECLineEdit->clear(); } void Controller::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("Controller::"+funcName+":
" + errorCodes->errorKeyMap.value(status), "error"); criticalReceived(); successProcessing = false; } } // Cannot be done above when data classes are defined (because memoryviewer has not been declared in mainwindow.cc when the controller is defined. void Controller::connectDataWithMemoryViewer() { for (auto &DT_x : masterListDT) { if (!DT_x.isEmpty()) { for (auto &it : DT_x) { connect(it, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); } } } if (globalweights_created && GLOBALWEIGHTS != nullptr) { connect(GLOBALWEIGHTS, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); } } void Controller::activationWarningReceived(QString imagestatus, QString drivestatus) { QMessageBox::warning( this, "THELI: Incoherent processing states", "This image has a different processing status (" + imagestatus + ") " +"than the currently active images (" + drivestatus + "). It cannot be reactivated like this.\n" +"To include this image in the processing, you must either restore the corresponding processing status for all active images, " "or close THELI and manually restore all suitable images, or start from the raw data."); } /* void Controller::decrementCurrentThreads(omp_lock_t &lock) { omp_set_lock(&lock); // --currentExternalThreads; --currentThreadsRunning; if (availableThreads < maxCPU) ++availableThreads; omp_unset_lock(&lock); } */ /* void Controller::incrementCurrentThreads(omp_lock_t &lock) { omp_set_lock(&lock); // ++currentExternalThreads; ++currentThreadsRunning; if (availableThreads > 0) --availableThreads; omp_unset_lock(&lock); } */ /* int Controller::reserveAvailableThreads(omp_lock_t &lock) { int numInternalThreads = 1; // Consume remaining available threads. while (availableThreads > 0) { omp_set_lock(&lock); ++numInternalThreads; --availableThreads; omp_unset_lock(&lock); // Give the other threads a chance QTest::qWait(100); } return numInternalThreads; } */ /* void Controller::makeThreadsAvailable(omp_lock_t &lock, int numberThreadsBlocked) { omp_set_lock(&lock); availableThreads += numberThreadsBlocked; omp_unset_lock(&lock); } */ /* void Controller::restoreData(MyImage *myImage, QString backupDirName) { // Moves an image from the backupDir to the current Dir QString currentPath = myImage->path; QString backupPath = myImage->path + "/" + backupDirName + "/"; // DO NOT use append() because it will also change the variable one appends to. QFile image(backupPath+"/"+myImage->name); if (!image.exists()) return; if (!image.rename(currentPath+"/"+myImage->name)) { QString command = "mv " + backupPath+"/"+myImage->name + currentPath+"/"+myImage->name; emit messageAvailable("CTRL: restoreData(): Could not execute the following operation:
" + command, "error"); criticalReceived(); } } */ /* int Controller::getInternalThreads(int chip) { QVector PARA(instData->numChips); maxExternalThreads; int i=1; while (i<=instData->numChips) { PARA[i] = ""; ++i; } // Assign chips to CPUs int k = 1; while (k <= maxExternalThreads) { int ACTUPROC = 1; while (ACTUPROC <= instData->numChips && k <= maxExternalThreads) { PARA[ACTUPROC].append(QString::number(k)); ++k; ++ACTUPROC; } } k = 1; QString nthread = ""; while (k <= instData->numChips) { int numthread = PARA[k].split(" ").length(); if (numthread == 0) numthread = 1; nthread.append(numthread); ++k; } return nthread.split(" ").at(chip); } */ /* void Controller::incrementProgress() { omp_set_lock(&progressLock); progress += progressStepSize; emit progressUpdate(progress); omp_unset_lock(&progressLock); } */ /* void Controller::incrementProgressHalfStep() { // omp_set_lock(&progressLock); progress += progressStepSize/2.; emit progressUpdate(progress); // omp_unset_lock(&progressLock); } */ /* void Controller::incrementProgressCombinedStep() { // omp_set_lock(&progressLock); progress += progressCombinedStepSize; emit progressUpdate(progress); // omp_unset_lock(&progressLock); } */ /* void Controller::rereadDataDir(QLineEdit *le, QList &DT_x) { dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); for (auto &data: DT_x) { delete data; } DT_x.clear(); parseDataDir(le, DT_x); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } */ /* void Controller::displayDriveSpace() { // Storage space in the main/home directory QString maindir = mainGUI->ui->setupMainLineEdit->text(); double GBtotal_data, GBfree_data, GBused_data; double GBtotal_home, GBfree_home, GBused_home; QStorageInfo storage_home(QDir::homePath()); if (storage_home.isValid() && storage_home.isReady()) { GBtotal_home = storage_home.bytesTotal()/1024./1024./1024.; GBfree_home = storage_home.bytesAvailable()/1024./1024./1024.; GBused_home = GBtotal_home - GBfree_home; } else { emit messageAvailable("Controller::displayDriveSpace(): Cannot determine home directory!", "error"); return; } QStorageInfo storage_data(maindir); if (storage_data.isValid() && storage_data.isReady()) { GBtotal_data = storage_data.bytesTotal()/1024./1024./1024.; GBfree_data = storage_data.bytesAvailable()/1024./1024./1024.; GBused_data = GBtotal_data - GBfree_data; } else { GBtotal_data = GBtotal_home; GBfree_data = GBfree_home; GBused_data = GBused_home; } mainGUI->driveProgressBar->setRange(0, GBtotal_data); QString datadiskstring = QString::number(GBfree_data,'f',2) + " GB left"; // check if the data disk warning should be activated if (GBfree_data <= mainGUI->diskwarnPreference/1024.) { // preference is given in MB if (!mainGUI->datadiskspace_warned) { mainGUI->datadiskspace_warned = true; if (maindir.isEmpty()) maindir = QDir::homePath(); QMessageBox::warning( this, "THELI: DATA DISK SPACE LOW", "The remaining disk space on\n\n" + maindir+"\n\nis less than your warning threshold of " + QString::number(mainGUI->diskwarnPreference)+" MB.\n" "The threshold can be set under Edit->Preferences in the main menu. " "This warning will not be shown anymore in this session, " "unless you update the threshold to a new value."); } } else mainGUI->datadiskspace_warned = false; if (GBfree_home <= 0.1) { if (!mainGUI->homediskspace_warned) { mainGUI->homediskspace_warned = true; QMessageBox::warning( this, "THELI: HOME DISK SPACE LOW", "THELI: You are running low (<100 MB) on disk space in your home directory!\n"); } } else mainGUI->homediskspace_warned = false; mainGUI->driveProgressBar->setFormat("Drive: "+datadiskstring); mainGUI->driveProgressBar->setValue(GBused_data); } */ /* void Controller::processExternalStdout() { QProcess *process = qobject_cast(sender()); QString stdout(process->readAllStandardOutput()); // QString stdout(externalProcess->readLine()); // emit messageAvailable(stdout, "normal"); } void Controller::processExternalStderr() { QProcess *process = qobject_cast(sender()); QString stderr(process->readAllStandardError()); emit messageAvailable(stderr, "normal"); } */ /* void Controller::splitterMemoryReceived(long memoryUsed) { #pragma omp atomic splitterMemoryUsed += memoryUsed; emit updateMemoryProgressBar(splitterMemoryUsed / 1024 / 1024); } */ /* void Controller::displayCPUload() { // int CPUload = myCPU->getCPUload(); float CPUload = myCPU->getCurrentValue(); QString CPUstring = QString::number(int(CPUload)) + " %"; mainGUI->cpuProgressBar->setFormat("CPU: "+CPUstring); mainGUI->cpuProgressBar->setValue(int(CPUload)); } void Controller::displayRAMload() { float RAMload = myRAM->getCurrentValue(); QString RAMstring = QString::number(long(RAMload)) + " MB"; mainGUI->memoryProgressBar->setFormat("RAM: %p% ("+RAMstring+")"); mainGUI->memoryProgressBar->setValue(int(RAMload)); } */ /* void Controller::displayMemoryTotalUsed() { // CHECK: in principle, the memoryLock should be sufficient to avoid crashes if (dataTreeUpdateOngoing) return; // Interferes with releaseMemory(), e.g. when memoryCurrentFootprint() evaluates the // capacity of a vector while it is being squeezed at the same time. // Cannot do this inside getMemoryTotalUsed() itself, because that is called by releasememory(), which in turn sets the lock omp_set_lock(&memoryLock); float totalMemory = getMemoryTotalUsed(); omp_unset_lock(&memoryLock); QString memoryString = QString::number(long(totalMemory)) + " MB"; mainGUI->memoryProgressBar->setFormat("RAM: %p% ("+memoryString+")"); mainGUI->memoryProgressBar->setValue(long(totalMemory)); } */ /* // crashes when used right at startup // CHECK: still crashes? QStringList Controller::getFilterList(QString scienceDir) { Data *scienceData = getData(DT_SCIENCE, scienceDir); QStringList filterList; QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); #pragma omp parallel for num_threads(maxCPU) for (int k=0; kloadHeader(); #pragma omp critical { if (!filterList.contains(it->filter)) filterList << it->filter; } } return filterList; } */ /* void Controller::progressUpdateReceived(float progress) { emit progressUpdate(progress); } */ // UNUSED /* void Controller::updateSingle() { dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); QLineEdit *le = qobject_cast(sender()); if (le == mainGUI->ui->setupMainLineEdit) mainDirName = le->text(); else if (le == mainGUI->ui->setupBiasLineEdit) parseDataDir(le, DT_BIAS); else if (le == mainGUI->ui->setupDarkLineEdit) parseDataDir(le, DT_DARK); else if (le == mainGUI->ui->setupFlatLineEdit) parseDataDir(le, DT_FLATOFF); else if (le == mainGUI->ui->setupFlatoffLineEdit) parseDataDir(le, DT_FLAT); else if (le == mainGUI->ui->setupScienceLineEdit) parseDataDir(le, DT_SCIENCE); else if (le == mainGUI->ui->setupSkyLineEdit) parseDataDir(le, DT_SKY); else if (le == mainGUI->ui->setupStandardLineEdit) parseDataDir(le, DT_STANDARD); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } */ THELI-3.1.3/src/processingInternal/controller.h000066400000000000000000000537361417631501300213760ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // The controller class keeps track of all data defined in the data directory tree, // and whether it is kept in memory or on disk, throughout the processing. // It also defines all the processing functions, kept separately in processing.cc #ifndef CONTROLLER_H #define CONTROLLER_H #include #include "data.h" #include "mask.h" #include "dockwidgets/memoryviewer.h" #include "dockwidgets/confdockwidget.h" #include "dockwidgets/monitor.h" #include "../threading/scampworker.h" #include "../threading/swarpworker.h" #include "../tools/fileprogresscounter.h" #include "photinst.h" #include "../iview/iview.h" #include "../query/query.h" #include "../tools/cpu.h" #include "../tools/ram.h" #include #include #include #include #include #include #include #include #include #include class MainWindow; // forward declaration to access GUI members class Data; // circular include directives triggered by memoryworker class Query; // circular include directives triggered by memoryworker class MemoryViewer; class Controller : public QMainWindow { Q_OBJECT private: bool taskRunning = false; QString thelidir; QString userdir; QMap commentMap; struct QPairSecondComparer { template bool operator()(const QPair & a, const QPair & b) const { return a.second < b.second; } }; QDir dir; QString dirName; QString tmpCoaddDir; Data *tmpCoaddData; // IView *checkplotViewer; FileProgressCounter *numberFileCounter; FileProgressCounter *sizeFileCounter; QString swarpCommand; QString coaddDirName; QString coaddScienceDir; QString scampScienceDir; QString anetDir; QString scampHeadersDir; QString scampPlotsDir; QString coaddUniqueID; QString scampCommand; QString sourceExtractorCommandOptions; QString scampDir; int processID; bool scampSolutionAcceptanceState = false; QVector photInstruments; QVector> overscanX; QVector> overscanY; QVector> dataSection; bool globalweights_created = false; long splitterMemoryUsed = 0; double rad = 3.1415926535 / 180.; float minCoaddSaturationValue = 1.e12; QString statusAtDistribute = ""; instrumentDataType altInstData; // For instruments with e.g. simultaneous optical and NIR detectors requiring different masks during HDU reformatting QMap headerDictionary; QMap filterDictionary; QMap instrumentDictionary; int recurseCounter = 0; // Processing functions void checkSuccessProcessing(const Data *data); // void decrementCurrentThreads(omp_lock_t &lock); QVector getBackgroundThresholds(const int loop, const bool twoPass, const QString DT, const QString DMIN, bool &doSourceDetection); void getDetectorSections(); QList > getNonlinearityCoefficients(); // void incrementCurrentThreads(omp_lock_t &lock); void memoryDecideDeletableStatus(Data *data, bool deletable); void parseDataDir(QLineEdit *le, QList &DT_x); void pushParallelizationToData(QList DT_x); void pushParallelizationToData(Data *data); // void rejectChipsWithBrightStars(QList backgroundList, QList > &brightStarList); // int reserveAvailableThreads(omp_lock_t &lock); void retrieveBrightStars(Data *data, QList> &brightStarList); // void makeThreadsAvailable(omp_lock_t &lock, int numberThreadsBlocked); void selectImagesDynamically(const QList &backgroundList, const double &mjd_ref); void selectImagesStatically(const QList &backgroundList, MyImage *scienceImage); void selectImagesFromSequence(QList &backgroundList, const int &nGroups, const int &nLength, const int ¤tExp); // Data handling // void restoreData(MyImage *myImage, QString backupDir); // Sky subtraction void skysubModel(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth); void skysubPolynomialFit(Data *scienceData); QList measureSkyInBlankRegions(Data *scienceData, QString method = ""); void skysubConstantFromArea(Data *scienceData); void skysubConstantReferenceChip(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth); void skysubConstantEachChip(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth); // Coaddition void coaddPrepare(QString filterArg); void coaddSmoothEdge(); void coaddPrepareProjectPM(QFile &headerFileOld, QString newHeaderName, QString refDE, double mjdobsZero, double mjdobsNow); void coaddPrepareProjectRotation(); void coaddPrepareBuildSwarpCommand(QString refRA, QString refDE); void coaddResampleBuildSwarpCommand(QString imageList, int i); void coaddCoadditionBuildSwarpCommand(QString imageList); void foldCoaddFits(); float coaddTexptime = 0.; float coaddSkyvalue = 0.; QString coaddFilter = ""; float coaddGain = 0.; double mjdStart = 0.; double mjdEnd = 0.; double mjdMedian = 0.; QString minDateObs = ""; // for the coadded image QString maxDateObs = ""; // for the coadded image // Astrometry bool manualCoordsUpdate(Data *scienceData, QString mode); void prepareScampRun(Data *scienceData); long prepareScampCats(Data *scienceData, long &totNumObjects); QString getUserParamLineEdit(const QLineEdit *le); QString getUserParamCheckBox(const QCheckBox *cb); QString getUserParamComboBox(const QComboBox *cb); void buildScampCommand(Data *scienceData); void sendMemoryPreferenceToImages(QList DT_x); int countBackgroundImages(QList list, QString baseName); // int getInternalThreads(int chip); void populateCommentMap(); void pushBeginMessage(const QString idstring, const QString targetdir); void pushConfigCoadd(); void pushConfigAstromphotom(); void pushConfigGetCatalogFromWeb(); void pushConfigGetCatalogFromImage(); void pushConfigCreatesourcecat(); void pushEndMessage(QString idstring, const QString targetdir); bool idChipsWithBrightStars(Data *skyData, QList > &brightStarList); void flagImagesWithBrightStars(const QList &backgroundList); void getNumberOfActiveImages(Data *&data); // void incrementProgress(); // void incrementProgressHalfStep(); // void incrementProgressCombinedStep(); // void rereadDataDir(QLineEdit *le, QList &DT_x); void doCrossCorrelation(Data *scienceData); long coaddCoadditionGetSize(); void splitScampHeaders(); void scampCalcFluxscale(); int getMaxPhotInst(); // void provideHeaderInfo(Data *scpublic QMainWindowienceData); void buildSourceExtractorCommandOptions(); void detectionInternal(Data *scienceData, QString minFWHM, QString maxFlag); void detectionSourceExtractor(Data *scienceData, QString minFWHM, QString maxFlag); void mergeInternal(Data *scienceData, QString minFWHM, QString maxFlag); void mergeSourceExtractor(Data *scienceData); void populateHeaderDictionary(); void populateFilterDictionary(); long makeListofAllImages(QList &allMyImages, Data *data); // void updateMyImagesWithScampSolution(Data *scienceData); void doImageQualityAnalysis(); void collectGaiaRaDec(MyImage *image, QVector &dec, QVector &ra, QVector > &output); void releaseMemory(float RAMneeded, int numThreads, QString mode = ""); long getNumObjectsScampCat(QString cat); void satisfyMaxMemorySetting(); long getNumObjectsSourceExtractorCat(QString cat); void emitSourceCountMessage(long &nobj, QString baseName); void printCfitsioError(QString funcName, int status); void updateImageAndData(MyImage *image, Data *data); void maskObjectsInSkyImagesPass1(const int chip, Data *skyData, Data *scienceData, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor); void maskObjectsInSkyImagesPass2(const int chip, Data *skyData, Data *scienceData, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor, const bool rescaleModel); bool filterBackgroundList(const int chip, Data *skyData, MyImage *it, QString &backExpList, const int nGroups, const int nLength, const int currentExposure, const QString mode); // void maskObjectsInSkyImagesPass1_newParallel(Data *skyData, Data *scienceData, const QList &backgroundList, // const bool twoPass, const QString dt, const QString dmin, const bool convolution, // const QString expFactor, const int threadID); // void maskObjectsInSkyImagesPass2_newParallel(Data *skyData, Data *scienceData, MyImage *combinedImage, const QList &backgroundList, // const bool twoPass, const QString dt, const QString dmin, const bool convolution, // const QString expFactor, const int chip, const bool rescaleModel, // const int threadID, const QString mode); void sendBackgroundMessage(const QString mode, const bool staticmodeldone, const QString basename, const int pass); /* void processBackgroundStatic(Data *scienceData, Data *skyData, const float nimg, QVector &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QVector &staticImagesWritten); void processBackgroundDynamic(Data *scienceData, Data *skyData, const float nimg, QVector &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QVector &staticImagesWritten); */ void processBackground(Data *scienceData, Data *skyData, const float nimg, QVector &numBackExpList, const QString dt, const QString dmin, const QString expFactor, const QString nlow1, const QString nhigh1, const QString nlow2, const QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QString mode, QVector &staticImagesWritten); void uniformMJDOBS(QDir &dir); void finalizeSplitter(Data *data); bool updateDataDirs(Data *data); void initAltInstrumentData(QString instrumentNameFullPath); void resetAltInstrumentData(); void testOverscan(QVector &overscan); void provideAlternativeMask(); void pushConfigHDUreformat(); void pushConfigProcessbias(); void pushConfigProcessdark(); void pushConfigProcessflat(); void pushConfigProcessflatoff(); void pushConfigBackground(); void pushConfigCollapse(); void pushConfigBinnedpreview(); void pushConfigGlobalweight(); void pushConfigIndividualweight(); void pushConfigSkysubModel(); void pushConfigSkysubConst(); void pushConfigSkysubPoly(); void flagLowDetectionImages(Data *scienceData, long &numExpRejected, long &numImgRejected); void doDataFitInRAM(const long nImages, const long storageSize); bool testResetDesire(const Data *data); void runAnet(Data *scienceData); void prepareAnetRun(Data *scienceData); long getNumAnetChips(QString ahead); long makeAnetHeaderList(Data *scienceData); bool setupBackgroundList(int chip, Data *skyData, const QString &chipName); void combineAllBackgroundUsabilityFlags(const QList &backgroundList); void getMinimumSaturationValue(); private slots: // void displayRAMload(); // void displayMemoryTotalUsed(); // void displayCPUload(); void displayProgress(); // void displayDriveSpace(); // The following can also be under 'private', but then the declaration must be preceded like this: // Q_INVOKABLE QString taskHDUreformat(); void taskInternalProcessbias(); void taskInternalProcessdark(); void taskInternalProcessflatoff(); void taskInternalProcessflat(); void taskInternalProcessscience(); void taskInternalBackground(); void taskInternalCollapse(); void taskInternalBinnedpreview(); void taskInternalGlobalweight(); void taskInternalIndividualweight(); void taskInternalCreatesourcecat(); void taskInternalSkysub(); void taskInternalCoaddition(); void taskInternalGetCatalogFromWEB(); void taskInternalGetCatalogFromIMAGE(); void taskInternalHDUreformat(); void taskInternalResolveTargetSidereal(); void taskInternalRestoreHeader(); // void taskInternalCopyZeroOrder(); void taskInternalAstromphotom(); void taskInternalSeparate(); // void processExternalStdout(); // void processExternalStderr(); void finishedPreparationReceived(); void waitForResamplingThreads(int threadID); void finishedScampReceived(); void fieldMatchedReceived(); void showScampCheckPlotsReceived(); void registerScampSolutionAcceptance(bool scampSolutionAccepted); void continueWithCopyZeroOrder(); void copyZeroOrder(); void swarpErrorFoundReceived(); void scampErrorFoundReceived(); void addToProgressBarReceived(const float differential); // void splitterMemoryReceived(long memoryUsed); public: explicit Controller(const instrumentDataType *instrumentData, QString statusold, ConfDockWidget *cdw, Monitor *processMonitor, MainWindow *parent = nullptr); ~Controller(); // Multi-threading (accessed from e.g. memory viewer) omp_lock_t lock; omp_lock_t memoryLock; omp_lock_t wcsLock; omp_lock_t genericLock; omp_lock_t progressLock; omp_lock_t backgroundLock; // QTimer *ramTimer; // QTimer *cpuTimer; QTimer *progressTimer; // QTimer *driveTimer; int maxCPU = 1; // Overall, maximum number of CPUs to be used int localMaxCPU = 1; // depending on how the parallelization is made, and how many images we have, we may run with fewer threads int maxExternalThreads = 1; // Maximum number of threads working on chips; equal or smaller than maxCPU int maxInternalThreads = 1; // Maximum number of threads working on images; equal or smaller than maxCPU - maxExternalThreads int maxThreadsIO = 1; // Maximum number of IO threads long maxRAM = 512; // Max RAM in MB available for processing int currentExternalThreads = 0; // The current number of external running threads (over different chips) int currentInternalThreads = 0; // The current number of internal running threads (over images of the same chip) int currentThreadsRunning = 0; int availableThreads = 1; bool useGPU = false; int verbosity = 0; bool userYield = false; bool userStop = false; bool userKill = false; bool abortProcess = false; // Triggered by critical() signals emitted anywhere bool swapWarningShown = false; bool dataTreeUpdateOngoing = false; QString currentSwarpProcess = ""; QString mainDirName; QString instrument_dir; Query *gaiaQuery; bool gaiaQueryDone = false; bool alwaysStoreData = false; bool minimizeMemoryUsage = false; float progress = 0.; long numActiveImages = 0; float progressStepSize = 0.; float progressHalfStepSize = 0.; float progressCombinedStepSize = 0.; QString taskBasename; QString instructions; QString backupDirName = ""; QString statusOld = ""; QString statusNew = ""; QString lastTaskExecuted = ""; // needed to detect whether a task is repeated or not (must restore memory accordingly) bool isTaskRepeated = false; // DT = "DataTree" // The lists contain multiple entries, e.g. if three different BIAS dirs are defined QList DT_BIAS; QList DT_DARK; QList DT_FLAT; QList DT_FLATOFF; QList DT_SCIENCE; QList DT_SKY; QList DT_STANDARD; QList> masterListDT; Data* GLOBALWEIGHTS = nullptr; Mask *mask = nullptr; Mask *altMask = nullptr; // for GROND types with different simultaneous detectors MainWindow *mainGUI; ConfDockWidget *cdw; const instrumentDataType *instData; Monitor *monitor; MemoryViewer *memoryViewer; bool successProcessing = true; // Reset externally to 'true' when clicking the 'start' button void mapDataTree(); void taskProcessbias(); void runTask(); Data* getData(QList DT_x, QString dirName); Data* getDataAll(QString dirName); QString manualCoordUpdateMode = ""; QVector workerThreads; QVector swarpWorkers; QVector threadsFinished; bool workersInit = false; bool workerThreadsInit = false; QThread *workerThreadPrepare = nullptr; QThread *workerThreadCoadd = nullptr; QThread *workerThread = nullptr; SwarpWorker *swarpWorker = nullptr; ScampWorker *scampWorker = nullptr; bool workerInit = false; bool workerThreadInit = false; Data *coaddScienceData; Data *scampScienceData; Data *currentData = nullptr; QString currentDirName = ""; QVector externalProcesses; QVector swarpCommands; QProcess *externalProcess; QByteArray *stdoutByteArray; QByteArray *stderrByteArray; // Function pointers; // Updated externally by MainWindow::updateControllerFunctors() float (*combineOverscan_ptr) (const QVector &, const QVector &, long); float (*combineBias_ptr) (const QVector &, const QVector &, long); float (*combineDark_ptr) (const QVector &, const QVector &, long); float (*combineFlatoff_ptr) (const QVector &, const QVector &, long); float (*combineFlat_ptr) (const QVector &, const QVector &, long); float (*combineBackground_ptr) (const QVector &, const QVector &, long); void checkForUnsavedImages(long &numUnsavedLatest, long &numUnsavedAll); void wipeDataTree(); void writeUnsavedImagesToDrive(bool includeBackup); // QStringList getFilterList(QString scienceDir); void downloadGaiaCatalog(Data *scienceData); void downloadGaiaCatalog(Data *scienceData, QString radius); void releaseAllMemory(); void restoreAllRawData(); void updateMasterList(); void connectDataWithMemoryViewer(); QLineEdit *getDataTreeLineEdit(Data *data); void getFieldCenter(Data *data, QString &alphaCenter, QString &deltaCenter); void populateInstrumentDictionary(); signals: void loadViewer(QString dirname, QString filter, QString mode); void messageAvailable(QString message, QString type); void appendOK(); void showMessageBox(QString trigger, QString part1, QString part2); void progressUpdate(float progress); void targetResolved(QString alpha, QString delta); void resetProgressBar(); void swarpStartResampling(); void swarpStartCoaddition(); void swarpStartSwarpfilter(); void swarpStartUpdate(); void showScampCheckPlots(); void scienceDataDirUpdated(QString allDir); void clearMemoryView(); void populateMemoryView(); void stopFileProgressTimer(); void addBackupDirToMemoryviewer(QString scienceDir); void loadAbsZP(QString coaddImagePath, float maxVal); void updateMemoryProgressBar(long splitterMemory); void forceFinish(); void refreshMemoryViewer(); public slots: void activationWarningReceived(QString imagestatus, QString drivestatus); void updateAll(); // void updateSingle(); void loadPreferences(); void updateMemoryPreference(bool isRAMminimized); void updateIntermediateDataPreference(QString intermediateDataPreference); void criticalReceived(); void warningReceived(); void messageAvailableReceived(QString message, QString type); void appendOKReceived(); void showMessageBoxReceived(QString trigger, QString part1, QString part2); void updateVerbosity(int verbosityLevel); // void progressUpdateReceived(float progress); void dataTreeEditedReceived(); void newProjectLoadedReceived(); void coaddResample(); void coaddSwarpfilter(); void coaddCoaddition(); void coaddUpdate(); void rereadScienceDataDirReceived(); void setMemoryLockReceived(bool locked); void setWCSLockReceived(bool locked); void absZeroPointCloseReceived(); void resetErrorStatusReceived(QString dirName); }; #endif // CONTROLLER_H THELI-3.1.3/src/processingInternal/data.cc000066400000000000000000003554301417631501300202560ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "data.h" #include "mask.h" #include "../myimage/myimage.h" #include "../functions.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../preferences.h" #include "../instrumentdata.h" #include "../threading/memoryworker.h" #include "../processingStatus/processingStatus.h" #include "fitsio.h" #include #include #include #include #include #include #include #include #include #include #include // Ctor, given an absolute path name (dirName), status string, and optionally chip number // It creates a list of all matching images in that directory, and also reads some // essential FITS header keywords. Data::Data(const instrumentDataType *instrumentData, Mask *detectorMask, QString maindirname, QString subdirname, int *verbose) : instData(instrumentData) { emit messageAvailable("DATA: Setting up "+subdirname, "data"); initEnvironment(thelidir, userdir); resetSuccessProcessing(); if (QDir(maindirname) == QDir::home()) { emit messageAvailable("For safety reasons, your home directory is not permitted as the main directory.", "error"); emit critical(); return; } omp_init_lock(&progressLock); mainDirName = maindirname; subDirName = subdirname; dirName = mainDirName + "/" + subDirName; myImageList.resize(instData->numChips); combinedImage.resize(instData->numChips); dataInitialized = false; verbosity = verbose; // globalMask.resize(instData->numChips); // Pointer to the detector masks defined in the top-level controller; // We don't need a separate entity for each 'Data' instance mask = detectorMask; // Get the recorded processing status from the .processingStatus file (if any) processingStatus = new ProcessingStatus(dirName, this); processingStatus->readFromDrive(); QString backupStatus = processingStatus->statusString; backupStatus.chop(1); pathBackupL1 = dirName + "/" + backupStatus + "_IMAGES"; dir.setPath(dirName); if (!dir.exists()) { emit messageAvailable("DATA: Could not create Data structure for "+mainDirName+"/"+subDirName, "error"); emit critical(); return; } // start fresh clearImageInfo(); // Check whether this directory contains RAW data (and thus must be processed by HDUreformat first) if (subDirName != "GLOBALWEIGHTS") { // crashes otherwise when creating globalweights if (checkForRawData()) return; } if (subDirName == "GLOBALWEIGHTS") { numMasterCalibs = 0; numImages = 0; for (int chip=0; chipnumChips; ++chip) { // The list is fully populated, even for chips the user might decide not to use myImageList[chip].clear(); // in case we run globalweights several times QStringList filter; filter << "globalweight*_"+QString::number(chip+1)+".fits"; QStringList fitsFiles = dir.entryList(filter); for (auto &it : fitsFiles) { MyImage *myImage = new MyImage(dirName, it, "", chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->readFILTER(dirName+"/"+it); myImage->imageOnDrive = true; myImageList[chip].append(myImage); ++numImages; connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::errorOccurred, this, &Data::errorOccurredInMyImage); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); // Use a direct connection to execute the slot in the signaler's thread, not the receiver's thread connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } } if (numImages < instData->numChips && numImages > 0) { emit messageAvailable("DATA: " + QString::number(numImages) + " found, expected "+QString::number(instData->numChips), "warning"); emit warning(); } dataInitialized = true; return; } // Fill the list of MyImage types of individual images and master calibration files in this data directory QStringList filter; filter << "*.fits"; QStringList allFitsFiles = dir.entryList(filter); numImages = allFitsFiles.length(); numMasterCalibs = 0; // The master calibration FITS files (if any). (i.e. if we are reading a calibration directory) for (int chip=0; chipnumChips; ++chip) { QStringList filter; filter << subDirName+"_"+QString::number(chip+1)+".fits"; QStringList fitsFiles = dir.entryList(filter); if (!fitsFiles.isEmpty()) { // Only one entry in this QStringList because it is the master MyImage *myImage = new MyImage(dirName, fitsFiles.at(0), "", chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->imageOnDrive = true; combinedImage[chip] = myImage; ++numMasterCalibs; connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } } if (numMasterCalibs == instData->numChips) { hasAllMasterCalibs = true; dataInitialized = true; } if (numMasterCalibs < instData->numChips && numMasterCalibs > 0) { emit messageAvailable("DATA: " + QString::number(numMasterCalibs) + " found, expected "+QString::number(instData->numChips), "warning"); } // The other images (minus master calibs etc), i.e. the science exposures numImages = 0; for (int chip=0; chipnumChips; ++chip) { QStringList filter; filter << "*_"+QString::number(chip+1)+processingStatus->statusString+".fits"; QStringList fitsFiles = dir.entryList(filter); // TODO: when splitting data, we must use a filter that does not contain the _chip string (raw data) // if list == empty then reset string and reload for (auto &it : fitsFiles) { bool skip = false; // skip master calibs if (it == subDirName+"_"+QString::number(chip+1)+".fits") skip = true; if (skip) continue; MyImage *myImage = new MyImage(dirName, it, processingStatus->statusString, chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->readFILTER(dirName+"/"+it); myImage->imageOnDrive = true; myImage->pathBackupL1 = pathBackupL1; myImage->baseNameBackupL1 = myImage->chipName + backupStatus; QFile weight(myImage->weightPath+"/"+myImage->weightName+".fits"); if (weight.exists()) myImage->weightOnDrive = true; myImageList[chip].append(myImage); if (!uniqueChips.contains(chip+1)) uniqueChips.push_back(chip+1); connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } // Add deactivated images QStringList deactiveDirList; deactiveDirList << "/inactive/" << "/inactive/badStatistics/" << "/inactive/badBackground/" << "/inactive/lowDetections/" << "/inactive/noAstrometry/"; for (auto &pathExtension : deactiveDirList) { QDir deactiveDir(dirName+pathExtension); QStringList deactiveFilter; deactiveFilter << "*.fits"; // selects all images, not just those of a specific chip QStringList files = deactiveDir.entryList(deactiveFilter); for (auto &it : files) { // check if the image belongs to the currently processed chip. If not, continue; QFileInfo fi(dirName+pathExtension+"/"+it); QString rootName = fi.completeBaseName(); rootName.truncate(rootName.lastIndexOf('_')); QString chipName = rootName+"_"+QString::number(chip+1); QString status = processingStatus->extractStatusFromFilename(it); if (chipName+status+".fits" != it) continue; // Ok, image belongs to current chip QString deactiveBackupStatus = status; deactiveBackupStatus.chop(1); QString deactivePathBackupL1 = dirName + "/" + deactiveBackupStatus + "_IMAGES"; MyImage *myImage = new MyImage(dirName, it, status, chip+1, mask->globalMask[chip], verbosity); myImage->pathExtension = pathExtension; myImage->setParent(this); myImage->readFILTER(deactiveDir.absolutePath()+"/"+it); myImage->imageOnDrive = true; myImage->pathBackupL1 = deactivePathBackupL1; myImage->baseNameBackupL1 = myImage->chipName + deactiveBackupStatus; myImage->weightPath = dirName+"/../WEIGHTS/"; QFile weight(myImage->weightPath+"/"+myImage->weightName+".fits"); if (weight.exists()) myImage->weightOnDrive = true; if (pathExtension == "inactive/badStatistics/") myImage->activeState = MyImage::BADSTATS; else if (pathExtension == "inactive/badBackground/") myImage->activeState = MyImage::BADBACK; else if (pathExtension == "inactive/lowDetections/") myImage->activeState = MyImage::LOWDETECTION; else if (pathExtension == "inactive/noAstrometry/") myImage->activeState = MyImage::NOASTROM; else myImage->activeState = MyImage::INACTIVE; myImageList[chip].append(myImage); if (!uniqueChips.contains(chip+1)) uniqueChips.push_back(chip+1); connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } } numImages += myImageList[chip].length(); } if (numImages > 0) dataInitialized = true; // Sort the vector with the chip numbers (no particular reason, yet) std::sort(uniqueChips.begin(), uniqueChips.end()); // Parallelization is set externally by controller; // Listen to images // establish_connections(); } Data::~Data() { for (auto &it: combinedImage) { delete it; it = nullptr; } deleteMyImageList(); omp_destroy_lock(&progressLock); } // Upon launch, check if the status on record matches the FITS files on drive bool Data::checkStatusConsistency() { // only do this if (!processingStatus->doesStatusFileExist()) return true; // Figure out a chip that must be present (not excluded by the user int testChip = -1; for (int chip=0; chipnumChips; ++chip) { if (!instData->badChips.contains(chip)) { testChip = chip; break; } } if (testChip == -1) { qDebug() << __func__ << "error: no data left after filtering"; } if (dataType == "SCIENCE" || dataType == "SKY" || dataType == "STD") { QStringList expectedFileList = dir.entryList(QStringList() << "*_"+QString::number(testChip+1)+processingStatus->statusString+".fits"); QStringList observedFileList = dir.entryList(QStringList() << "*_"+QString::number(testChip+1)+"P*.fits"); // write found status to disk. Controller will then retry if necessary if (expectedFileList.isEmpty() && !observedFileList.isEmpty()) { processingStatus->inferStatusFromFilenames(); processingStatus->statusToBoolean(processingStatus->statusString); processingStatus->writeToDrive(); return false; } } return true; } bool Data::checkForRawData() { // Only checking .fits files. Everything else ("*.fit", "*.cr2", "*.fz" etc) it is clear that we have raw data (or other files) QStringList filter = {"*.fits"}; QStringList filter2 = {"*.fits", "*.fit", "*.FIT", "*.fz", "*.cr2", "*.CR2", "*.arw", "*.ARW", "*.dng", "*.DNG", "*.nef", "*.NEF", "*.pef", "*.PEF"}; dir.setFilter(QDir::Files); QStringList fileNames = dir.entryList(filter); // Contains processed images and potential raw data QStringList allFileNames = dir.entryList(filter2); // Everything int numRawFiles = 0; for (QString &allFileName : allFileNames) { if (!allFileName.endsWith(".fits")) ++numRawFiles; // Does not matter whether imaging data or other stuff } int numProcessedFiles = 0; for (auto &fileName : fileNames) { fitsfile *fptr; int status = 0; QString name = dirName + "/" + fileName; fits_open_file(&fptr, name.toUtf8().data(), READONLY, &status); long thelipro = 0; fits_read_key_lng(fptr, "THELIPRO", &thelipro, nullptr, &status); if (status == KEY_NO_EXIST) { ++numRawFiles; status = 0; } else { ++numProcessedFiles; } fits_close_file(fptr, &status); } if (numProcessedFiles == 0 && numRawFiles > 0) { processingStatus->deleteFromDrive(); processingStatus->reset(); return true; } else if (numProcessedFiles == 0 && numRawFiles == 0) return true; else if (numProcessedFiles > 0 && numRawFiles == 0) return false; else { processingStatus->deleteFromDrive(); processingStatus->reset(); // TODO: this does not show! emit showMessageBox("DATA::RAW_AND_PROCESSED_FOUND", dirName, ""); // qDebug() << "Data::checkForRawData(): " << subDirName << numProcessedFiles << numRawFiles; // qDebug() << "Both processed and RAW files were found. This status is not allowed"; // (numProcessedFiles > 0 && numRawFiles > 0) { // TODO: this does not show! emit messageAvailable(dirName + " : Both processed and RAW files were found. This status is not allowed. You must clean the directory manually.", "error"); emit critical(); successProcessing = false; return false; } } void Data::broadcastNumberOfFiles() { emit messageAvailable(subDirName + ": " + QString::number(numImages)+" images initialized", "data"); if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF" || dataType == "FLAT") { emit messageAvailable(subDirName + ": " + QString::number(numMasterCalibs)+" master "+dataType+" images initialized", "data"); } } // Needed for aborting a task void Data::setSuccess(bool state) { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->successProcessing = state; } successProcessing = state; } } void Data::writeUnsavedImagesToDrive(bool includeBackup) { emit resetProgressBar(); /* * TODO: Run it as a separate process * CRASHES, because processes are started by the controller, which then immediately calls the destructor. * Better if we can wait for the processes and then delete 'data', e.g. if handled by controller directly workerThread = new QThread(this); worker = new MyWorker(this); workerInit = true; workerThreadInit = true; worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MyWorker::DataDumpImagesToDrive); QObject::connect(worker, &MyWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); workerThread->wait(); */ // freezes the GUI while running ... progressStepSize = 1. / float(numImages); emit resetProgressBar(); populateExposureList(); #pragma omp parallel for num_threads(maxCPU) for (long i=0; iimageOnDrive) { it->writeImage(); it->imageOnDrive = true; it->emitModelUpdateNeeded(); if (includeBackup) { it->writeImageBackupL1(); it->writeImageBackupL2(); it->writeImageBackupL3(); } #pragma omp atomic *progress += progressStepSize; } } } emit progressUpdate(100.); } bool Data::checkTaskRepeatStatus(QString taskBasename) { isTaskRepeated = false; // Check the Data class. If the current task matches the status, then the task is being repeated if (taskBasename == "HDUreformat" && processingStatus->HDUreformat) isTaskRepeated = true; else if (taskBasename == "Processscience" && processingStatus->Processscience) isTaskRepeated = true; else if (taskBasename == "Chopnod" && processingStatus->Chopnod) isTaskRepeated = true; else if (taskBasename == "Background" && processingStatus->Background) isTaskRepeated = true; else if (taskBasename == "Collapse" && processingStatus->Collapse) isTaskRepeated = true; else if (taskBasename == "Starflat" && processingStatus->Starflat) isTaskRepeated = true; else if (taskBasename == "Skysub" && processingStatus->Skysub) isTaskRepeated = true; // Check that all images have the same status myImageList[instData->validChip][0]->checkTaskRepeatStatus(taskBasename); bool imageStatus = myImageList[instData->validChip][0]->isTaskRepeated; for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->checkTaskRepeatStatus(taskBasename); if (imageStatus != it->isTaskRepeated) { emit messageAvailable(dirName + " : Data::checkTaskRepeatStatus(): Inconsistent processing status detected among images!
You must clean-up the data directory manually. Restart recommended.", "error"); emit critical(); it->successProcessing = false; successProcessing = false; return false; } } } // If the Data class status does not match the image status, then map the image status onto the Data class if (isTaskRepeated != imageStatus) { // Map the imaging status onto the Data structure emit messageAvailable(dirName + " : Data::checkTaskRepeatStatus(): Inconsistent processing status detected between images and Data class. Reset to image status", "warning"); emit warning(); processingStatus->statusToBoolean(myImageList[instData->validChip][0]->processingStatus->statusString); processingStatus->getStatusString(); } // Now check if we can actually retrieve all the data with the previous status bool success = true; if (isTaskRepeated) { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { // If the image is not in memory, check if it is on disk if (!it->backupL1InMemory) { QString fileName = it->pathBackupL1 + "/" + it->baseNameBackupL1 + ".fits"; QFile file(fileName); if (it->backupL1OnDrive && !file.exists()) success = false; else if (!it->backupL1OnDrive && !file.exists()) success = false; else if (!it->backupL1OnDrive && file.exists()) { it->backupL1OnDrive = true; if (*verbosity > 2) emit messageAvailable(dirName + " : Data::checkTaskRepeatStatus(): Fixed wrong backup status flag, file was found on drive.", "warning"); } } } } if (!success) { emit showMessageBox("Data::BACKUP_DATA_NOT_FOUND", "",""); } } return success; } void Data::checkPresenceOfMasterCalibs() { // Check if master calibration FITS files are present int numMasterCalibs = 0; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; QStringList filter; filter << subDirName+"_"+QString::number(chip+1)+".fits"; QStringList fitsFiles = dir.entryList(filter); if (!fitsFiles.isEmpty()) ++numMasterCalibs; } if (numMasterCalibs == instData->numUsedChips) hasAllMasterCalibs = true; else hasAllMasterCalibs = false; } void Data::populateExposureList() { if (*verbosity > 0) emit messageAvailable(subDirName + " : Collecting metadata from images ...", "data"); // Create a list of unique MJDOBS QVector mjdList; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { // TODO: this is only necessary if the GUI is launched and files have not been read yet! // There should be a member boolean that keeps track of this if (!it->headerInfoProvided) it->loadHeader(); if (!mjdList.contains(it->mjdobs)) mjdList.append(it->mjdobs); } } // Sort list of mjdobs std::sort(mjdList.begin(), mjdList.end()); exposureList.clear(); exposureList.resize(mjdList.length()); // Collect all MyImages that belong to one mjdobs long expNumber = 0; for (auto &mjdobs : mjdList) { for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (it->mjdobs == mjdobs) { exposureList[expNumber].append(it); } } } ++expNumber; } emit appendOK(); } void Data::resetGlobalWeight(QString filter) { // CHECK: not sure whether i need to exclude badChips here if (myImageList.isEmpty()) return; for (int chip=0; chipnumChips; ++chip) { int removeIndex = 0; int i = 0; bool remove = false; for (auto &it: myImageList[chip]) { if (filter == it->filter) { removeIndex = i; remove = true; break; } ++i; } if (remove) { myImageList[chip][removeIndex]->freeAll(); myImageList[chip].removeAt(removeIndex); } } } void Data::loadCombinedImage(const int chip) { if (!successProcessing) return; if (userStop || userKill) return; if (*verbosity > 0 && !combinedImage.at(chip)->imageInMemory) { emit messageAvailable("Chip " + QString::number(chip+1) + " : Loading master "+ subDirName + " ...", "data"); } bool determineMode = false; // Must be threadsafe only if running process science as a first taskafter GUI re-launch combinedImage[chip]->readImageThreadSafe(determineMode); // Do we have the mode already (i.e. this function was executed previously for this chip) if (!combinedImage[chip]->modeDetermined) { // the mode determination will fail if we have mostly integer values (e.g. darks) if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { // mode doesn't work, as all values are very very narrowly distributed around a single value (which might be integer on top of that) combinedImage[chip]->skyValue = meanMask(combinedImage[chip]->dataCurrent, mask->globalMask[chip]); } else { combinedImage[chip]->skyValue = modeMask(combinedImage[chip]->dataCurrent, "stable", mask->globalMask[chip])[0]; } if (*verbosity > 0) { emit messageAvailable(subDirName + " : Master calib mean : "+QString::number(combinedImage[chip]->skyValue, 'f', 3), "data"); } } combinedImage[chip]->modeDetermined = true; combinedImage[chip]->imageInMemory = true; successProcessing = combinedImage[chip]->successProcessing; } // Usually, the mode / SKYVALUE is computed when applying the master BIAS/FLAT // However, a user might skip these steps, and then the mode remains undetermined void Data::checkModeIsPresent() { if (!successProcessing) return; #pragma omp parallel for num_threads(maxCPU) for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->getMode(true); } } } void Data::resetSuccessProcessing() { successProcessing = true; if (!dataInitialized) return; for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->successProcessing = true; } } } // Used for creating master calibrators void Data::combineImagesCalib(int chip, float (*combineFunction_ptr) (const QVector &, const QVector &, long), const QString nlowString, const QString nhighString, const QString dirName, const QString subDirName, const QString dataType) { if (!successProcessing) return; if (userStop || userKill) return; if (*verbosity > 0) emit messageAvailable(subDirName + " : Combining images for chip "+QString::number(chip+1)+" ...", "data"); int nlow = nlowString.toInt(); // returns 0 for empty string (desired) int nhigh = nhighString.toInt(); // returns 0 for empty string (desired) int numImages = myImageList.at(chip).length(); // Delete an old master calibration frame if it exists if (!deleteFile(subDirName+"_"+QString::number(chip+1)+".fits", dirName)) { emit messageAvailable(subDirName + " : Data::combineImgesCalib(): Could not delete old master calibration file!", "error"); emit critical(); successProcessing = false; return; } if (nhigh+nlow >= numImages) { emit messageAvailable("Number of low and high pixels rejected is equal or larger than the number of available images.", "error"); emit critical(); successProcessing = false; return; } if (numImages <= 3) { emit messageAvailable("Only "+QString::number(numImages)+" exposures are used to compute the combined master calibration file. More are recommended.", "warning"); emit warning(); } // Get image geometry from first image in list long n = myImageList.at(chip).at(0)->naxis1; long m = myImageList.at(chip).at(0)->naxis2; if (n == 0 || m == 0) { emit messageAvailable(subDirName + " : Data::combineImgesCalib(): Could not determine size of combined image.", "error"); emit critical(); successProcessing = false; return; } long dim = n*m; // Container for the temporary pixel stack // Instantiate a MyImage object for the combined set of images. // It does not create a FITS object yet. // Delete the instance if it exists already from a previous run of this task to not (re)create it // if (combinedImage[chip] != nullptr) delete combinedImage[chip]; if (combinedImage.at(chip) == nullptr) { MyImage *combinedImageDummy = new MyImage(dirName, subDirName+"_"+QString::number(chip+1)+".fits", "", chip+1, mask->globalMask[chip], verbosity); connect(combinedImageDummy, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(combinedImageDummy, &MyImage::critical, this, &Data::pushCritical); connect(combinedImageDummy, &MyImage::warning, this, &Data::pushWarning); connect(combinedImageDummy, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(combinedImageDummy, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(combinedImageDummy, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); combinedImage[chip] = combinedImageDummy; } combinedImage[chip]->naxis1 = n; combinedImage[chip]->naxis2 = m; combinedImage[chip]->dataCurrent.resize(dim); combinedImage[chip]->dataCurrent.squeeze(); // shed excess memory combinedImage[chip]->wcs = new wcsprm(); combinedImage[chip]->initWCS(); // loop over all pixels, and images; rescaling is optional QVector goodIndex; goodIndex.reserve(numImages); // Also checks whether the mode is within valid range (for calibrators): QVector rescaleFactors = getNormalizedRescaleFactors(chip, goodIndex, "forCalibration"); if (rescaleFactors.isEmpty()) { // we should never enter here. Error handling in getNormalizedRescaleFactors() successProcessing = false; return; } long ngood = goodIndex.length(); if (nhigh+nlow >= ngood) { emit messageAvailable("The number of nlow and nhigh rejected pixels is equal to or larger than the number of input exposures. Using zero instead", "warning"); nlow = 0; nhigh = 0; } QString goodImages; int k = 0; for (auto &gi : goodIndex) { goodImages.append(myImageList[chip][gi]->baseName + ": " + QString::number(myImageList[chip][gi]->skyValue, 'f', 3) + " e-, rescaled with " + QString::number(rescaleFactors[k], 'f', 3)); if (k"); ++k; } QString rescaled = ""; if (!rescaleFlag) rescaled = ", without rescaling, "; if (*verbosity > 0) emit messageAvailable(subDirName + " : Calculating master "+dataType+" for chip "+QString::number(chip+1) + rescaled + " from :
"+goodImages, "image"); if (*verbosity > 0) emit messageAvailable(subDirName + " : Median combination running ...", "data"); // 45% of the progress counter is reserved for combining the images. We update the progress bar for every 10% of these 45% float localProgressStepSize = 0.45 / 10. / instData->numUsedChips * 100.; int progCount = 1; // runs from 1 to 10; long progCountComparison = dim / 10; // works on dataCurrent dim = combinedImage.at(chip)->dataCurrent.length(); // Crashed by stack.append(), but not when running through valgrind (no multi-threading)? // Update: does not crash anymore ... (at least for single-chip cameras) // TODO: more efficient with semaphore if numcpu and numchips divide with remainder //#pragma omp parallel for num_threads(maxCPU) if (instData->numChips == 1) //int localMaxThreads = maxCPU/instData->numChips; // if (instData->numChips > maxCPU) localMaxThreads = 1; // QList imglist = myImageList[chip]; omp_set_nested(false); // somehow not yet threadsafe! // we still parallelise though for single-chip cameras: int localMaxThreads = 1; // NOT THREADSAFE // if (instData->numChips == 1) localMaxThreads = maxCPU; #pragma omp parallel for num_threads(localMaxThreads) firstprivate(rescaleFactors) // firstprivate(imglist, goodIndex, rescaleFactors) for (long i=0; i stack; stack.reserve(ngood); long k = 0; for (auto &gi : goodIndex) { // if clause: needed because objectmask can be empty and the lookup will segfault if (myImageList[chip][gi]->objectMaskDone) { if (!myImageList[chip][gi]->objectMask[i]) { stack.append(myImageList.at(chip).at(gi)->dataCurrent.at(i) * rescaleFactors[k]); } } else { stack.append(myImageList.at(chip).at(gi)->dataCurrent.at(i) * rescaleFactors[k]); } /* if (imglist[gi]->objectMaskDone) { if (!imglist[gi]->objectMask[i]) { stack.append(imglist[gi]->dataCurrent[i] * rescaleFactors[k]); } } else { stack.append(imglist[gi]->dataCurrent[i] * rescaleFactors[k]); } */ ++k; } // auto &stackedPixel = combinedImage[chip]->dataCurrent[pix]; combinedImage[chip]->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); // stackedPixel = combineFunction_ptr(stack, QVector(), ngood); // Increment the progressBar every 10 % if (i+1 == progCount * progCountComparison) { #pragma omp atomic *progress += localProgressStepSize; // emit addToProgressBar(localProgressStepSize); ++progCount; } } combinedImage[chip]->imageInMemory = true; successProcessing = true; combinedImage[chip]->emitModelUpdateNeeded(); } void Data::resetStaticModel() { staticModelDone.clear(); staticModelDone.resize(instData->numChips); for (auto &it : staticModelDone) it = false; } // Used for creating a background model void Data::combineImages(const int chip, const QString nlowString, const QString nhighString, const QString currentImage, const QString mode, const QString dirName, const QString subDirName, QVector &dataStaticModelDone) { if (!successProcessing) return; if (userStop || userKill) return; if (mode == "static" && dataStaticModelDone[chip]) return; QString rescaled = ""; if (!rescaleFlag) rescaled = ", without rescaling, "; if (*verbosity > 0) emit messageAvailable(subDirName + " : Combining these images" +rescaled+" for " +currentImage + " : ", "data"); // Get image geometry from first image in list that has its size measured long n = 0; long m = 0; for (auto &back : myImageList.at(chip)) { if (back->useForBackground) { n = back->naxis1; m = back->naxis2; break; } } if (n == 0 || m == 0) { emit messageAvailable(subDirName + " : Data::combineImges(): Could not determine size of combined image.", "error"); emit critical(); successProcessing = false; return; } long dim = n*m; int nlow = nlowString.toInt(); // returns 0 for empty string int nhigh = nhighString.toInt(); // returns 0 for empty string int numImages = myImageList.at(chip).length(); if (nhigh+nlow >= numImages) { emit messageAvailable("Number of low and high pixels rejected is equal or larger than the number of available images.", "error"); emit critical(); successProcessing = false; return; } // Instantiate a MyImage object for the combined set of images. It does not create a FITS object yet. // if (combinedImage[chip] != nullptr) delete combinedImage[chip]; if (combinedImage.at(chip) == nullptr) { // re-using previously created object MyImage *masterCombined = new MyImage(dirName, currentImage, "", chip+1, mask->globalMask[chip], verbosity); connect(masterCombined, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(masterCombined, &MyImage::critical, this, &Data::pushCritical); connect(masterCombined, &MyImage::warning, this, &Data::pushWarning); connect(masterCombined, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(masterCombined, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(masterCombined, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); combinedImage[chip] = masterCombined; combinedImage[chip]->wcs = new wcsprm(); combinedImage[chip]->wcsInit = true; } combinedImage[chip]->naxis1 = n; combinedImage[chip]->naxis2 = m; combinedImage[chip]->dataCurrent.resize(dim); combinedImage[chip]->dataCurrent.squeeze(); // loop over all pixels, and images; rescaling is optional QVector goodIndex; goodIndex.reserve(numImages); QVector rescaleFactors = getNormalizedRescaleFactors(chip, goodIndex, "forBackground"); if (rescaleFactors.isEmpty()) { // we should never enter here. Error handling in getNormalizedRescaleFactors() successProcessing = false; return; } QString goodImages; #pragma omp critical // QString thread safety it->chipname could be accessed simultaneously { int k = 0; for (auto &gi : goodIndex) { goodImages.append(myImageList[chip][gi]->chipName + ": " + QString::number(myImageList[chip][gi]->skyValue, 'f', 3) + " e-, rescaled with " + QString::number(rescaleFactors[k], 'f', 3)); if (k"); ++k; } } if (*verbosity > 0) emit messageAvailable(goodImages, "image"); if (*verbosity > 0) emit messageAvailable(subDirName + " : Median combination running ...", "data"); // works on dataBackupLx (?) long ngood = goodIndex.length(); if (nhigh+nlow >= ngood) { emit messageAvailable("The number of nlow and nhigh rejected pixels is equal to or larger than the number of input exposures. Using zero instead", "warning"); nlow = 0; nhigh = 0; } // int localMaxThreads = maxCPU/instData->numChips; // if (instData->numChips > maxCPU) localMaxThreads = 1; if (instData->numChips > 1) { QList stack; // Not thread safe // long ngood = goodIndex.length(); // stack.reserve(ngood); // #pragma omp parallel for num_threads(localMaxThreads) for (long i=0; i stack; // stack.reserve(ngood); long k = 0; for (auto &gi : goodIndex) { if (myImageList[chip][gi]->objectMaskDone) { // needed because objectmask can be empty and the lookup will segfault if (!myImageList[chip][gi]->objectMask[i]) { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } } else { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } ++k; } combinedImage[chip]->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); stack.clear(); } } // Single chip: we can use inner parallelization! // UPDATE: identical to the section above, just 'stack' is declared inside the for loop and not outside else { // NOPE! we cannot, still crashing sometimes // #pragma omp parallel for num_threads(localMaxThreads) firstprivate(rescaleFactors) for (long i=0; i stack; long k = 0; for (auto &gi : goodIndex) { if (myImageList[chip][gi]->objectMaskDone) { // needed because objectmask can be empty and the lookup will segfault if (!myImageList[chip][gi]->objectMask[i]) { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } } else { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } ++k; } combinedImage[chip]->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); } } if (mode == "static") dataStaticModelDone[chip] = true; combinedImage[chip]->imageInMemory = true; successProcessing = true; } /* // Used for creating a background model void Data::combineImages_newParallel(int chip, MyImage *masterCombined, QList &backgroundList, QString nlowString, QString nhighString, QString currentImage, QString mode, const QString subDirName) { if (!successProcessing) return; if (userStop || userKill) return; if (mode == "static" && staticModelDone[chip]) return; masterCombined->setBackgroundLock(true); QString rescaled = ""; if (!rescaleFlag) rescaled = ", without rescaling, "; if (*verbosity > 0) emit messageAvailable(subDirName + " : Combining these images" +rescaled+" for " +currentImage + " : ", "data"); int nlow = nlowString.toInt(); // returns 0 for empty string (desired) int nhigh = nhighString.toInt(); // returns 0 for empty string (desired) // Get image geometry from first image in list that has its size measured long n = 0; long m = 0; for (auto &back : backgroundList) { if (back->useForBackground) { n = back->naxis1; m = back->naxis2; break; } } if (n == 0 || m == 0) { emit messageAvailable(subDirName + " : Data::combineImges(): Could not determine size of combined image.", "error"); emit critical(); successProcessing = false; return; } long dim = n*m; // Container for the temporary pixel stack int numImages = backgroundList.length(); // Instantiate a MyImage object for the combined set of images. // It does not create a FITS object yet. // Delete the instance if it exists already from a previous run of this task to not (re)create it // if (combinedImage[chip] != nullptr) delete combinedImage[chip]; connect(masterCombined, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(masterCombined, &MyImage::critical, this, &Data::pushCritical); connect(masterCombined, &MyImage::warning, this, &Data::pushWarning); connect(masterCombined, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(masterCombined, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(masterCombined, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); masterCombined->naxis1 = n; masterCombined->naxis2 = m; masterCombined->dataCurrent.resize(dim); masterCombined->dataCurrent.squeeze(); // loop over all pixels, and images; rescaling is optional QVector goodIndex; goodIndex.reserve(numImages); // Also checks whether the mode is within valid range (for calibrators): QVector rescaleFactors = getNormalizedRescaleFactors(chip, goodIndex, "forBackground"); if (rescaleFactors.isEmpty()) { // we should never enter here. Error handling in getNormalizedRescaleFactors() successProcessing = false; return; } QString goodImages; int k = 0; for (auto &gi : goodIndex) { MyImage *it = backgroundList[gi]; goodImages.append(it->chipName + ": " + QString::number(it->skyValue,'f',3) + " e-, rescaled with " + QString::number(rescaleFactors[k],'f',3)); if (k"); ++k; } if (*verbosity > 0) emit messageAvailable(goodImages, "image"); if (*verbosity > 0) emit messageAvailable(subDirName + " : Median combination running ...", "data"); // works on dataBackupLx (?) dim = masterCombined->dataCurrent.length(); // int localMaxThreads = maxCPU/instData->numChips; // if (instData->numChips > maxCPU) localMaxThreads = 1; // for some unknown reason this parallelization results in a massive memory chaos. somewhere, something is overflowing and I just can't figure out where. QList stack; // long ngood = goodIndex.length(); // stack.reserve(ngood); // #pragma omp parallel for num_threads(localMaxThreads) for (long i=0; i stack; // stack.reserve(ngood); long k = 0; for (auto &gi : goodIndex) { // Not sure why I have included the requirement on dataBackupL1[i] != 0. // For flat-fielded data (not sky subtracted), the pixel values should always be positive. Commented out for the time being // if (!backgroundList[gi]->objectMask[i] && backgroundList[gi]->dataBackupL1[i] > 0.) { // stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); // } // } // else { // if (backgroundList[gi]->dataBackupL1[i] > 0.) { // stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); // } // } // Crash caused by dataBackgroundL1. Stack, rescaleFactors, backgroundList[gi] MyImages are all fine. // It appears to be the actual data vectors, but the debugger shows that everything gets mixed up. if (backgroundList[gi]->objectMaskDone) { // needed because objectmask can be empty and the lookup will segfault if (!backgroundList[gi]->objectMask[i]) { stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); } } else { stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); } ++k; } masterCombined->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); stack.clear(); // stackedPixel = combineFunction_ptr(stack, QVector(), ngood); } masterCombined->imageInMemory = true; successProcessing = true; masterCombined->setBackgroundLock(false); } */ void Data::getModeCombineImages(int chip) { if (!successProcessing) return; if (userStop || userKill) return; if (combinedImage[chip]->modeDetermined) return; // Get the mean / mode of the combined image if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { // mode doesn't work, as all values are very very narrowly distributed around a single value (which might be integer on top of that) combinedImage[chip]->skyValue = meanMask(combinedImage[chip]->dataCurrent, mask->globalMask[chip]); // if (*verbosity > 0) emit messageAvailable("Mean of chip "+QString::number(chip+1) + " for master "+dataType + " : " // + QString::number(combinedImage[chip]->skyValue) + " e-", "data"); } else { combinedImage[chip]->skyValue = modeMask(combinedImage[chip]->dataCurrent, "stable", mask->globalMask[chip])[0]; // if (*verbosity > 0) emit messageAvailable("Mode of chip "+QString::number(chip+1) + " for master "+dataType + " : " // + QString::number(combinedImage[chip]->skyValue) + " e-", "data"); } combinedImage[chip]->modeDetermined = true; successProcessing = true; } void Data::reportModeCombineImages() { // Report the mean / mode of the combined image QString report = ""; if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { report = "Statistics (mean) for master "+dataType+" :
"; } else { report = "Statistics (mode) for master "+dataType+" :
"; } for (int chip=0; chipnumChips; ++chip) { if (!successProcessing) { if (!userStop && !userKill) { report.append("Chip " + QString::number(chip+1) + " : failed
"); } } else { if (instData->badChips.contains(chip)) { report.append("Chip " + QString::number(chip+1) + " : Bad detector, skipped.
"); } else { report.append("Chip " + QString::number(chip+1) + " : " + QString::number(combinedImage[chip]->skyValue, 'f', 3) + " e-
"); } } } emit messageAvailable(report, "data"); } QVector Data::getNormalizedRescaleFactors(int chip, QVector &goodIndex, QString mode) { long nImages = myImageList[chip].length(); QVector rescaleFactors; rescaleFactors.reserve(nImages); goodIndex.reserve(nImages); if (userStop || userKill) return rescaleFactors; if (mode == "forBackground") { for (auto &it: myImageList[chip]) { if (it->useForBackground && !it->modeDetermined) { emit messageAvailable("Data::getNormalizedRescaleFactors(): Mode should have been determined in taskInternal()!", "error"); emit critical(); successProcessing = false; return rescaleFactors; // empty } } } if (!rescaleFlag) { // Combining a BIAS or DARK long j=0; for (auto &it : myImageList.at(chip)) { if (it->validMode) { rescaleFactors.append(1.0); goodIndex.append(j); } else { if (*verbosity > 0) emit messageAvailable(it->chipName + " : Not used, mode outside user limits : " + QString::number(it->skyValue), "warning"); } ++j; } return rescaleFactors; } else if (mode == "forCalibration") { // Combining a FLAT long j=0; for (auto &it : myImageList.at(chip) ) { if (it->validMode) { rescaleFactors.append(it->skyValue); goodIndex.append(j); } else { if (*verbosity > 0) emit messageAvailable(it->chipName + " : Not used, mode outside user limits : " + QString::number(it->skyValue), "warning"); } ++j; } } else if (mode == "forBackground") { // Combining a SCIENCE / SKY image long j=0; for (auto &it : myImageList.at(chip) ) { if (it->useForBackground) { rescaleFactors.append(it->skyValue); goodIndex.append(j); } ++j; } } else { emit messageAvailable("Data::getNormalizedRescaleFactors(): Invalid operating mode: " + mode, "error"); emit critical(); } // Rescale modes relative to mean mode float meanMode = meanMask(rescaleFactors); for (auto &it : rescaleFactors) it = meanMode / it; return rescaleFactors; } // copy the master flat field, threshold it void Data::initGlobalWeight(int chip, Data *flatData, QString filter, bool sameWeight, QString flatMin, QString flatMax) { if (!successProcessing) return; // myImageList[chip].clear(); QString globalWeightName = "globalweight_"+instData->name+"_"+filter+"_"+QString::number(chip+1)+".fits"; MyImage *myImage = new MyImage(mainDirName, globalWeightName, "", chip+1, mask->globalMask[chip], verbosity); // myImage->setParent(this); myImage->filter = filter; myImage->path = mainDirName+"/GLOBALWEIGHTS/"; myImage->naxis1 = instData->sizex[chip]; myImage->naxis2 = instData->sizey[chip]; connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); // Potential masking long i=0; float flatMinVal = 0.; float flatMaxVal = 1.e9; QString thresholds = ", no thresholding"; if (!flatMin.isEmpty() && !flatMax.isEmpty()) { flatMinVal = flatMin.toFloat(); flatMaxVal = flatMax.toFloat(); thresholds = ", thresholds = ["+flatMin+", "+flatMax+"]"; } else if (!flatMin.isEmpty()) { flatMinVal = flatMin.toFloat(); thresholds = ", thresholds = ["+flatMin+", unlimited]"; } else if (!flatMax.isEmpty()) { flatMaxVal = flatMax.toFloat(); thresholds = ", thresholds = [unlimited, "+flatMax+"]"; } // Initiate with the flat field, or unity everywhere if (!sameWeight) { if (flatData == nullptr) { emit messageAvailable("No FLAT data defined. Initializing globalweight for chip " + QString::number(chip+1) + " with constant value 1.0", "warning"); emit warning(); long dim = instData->sizex[chip] * instData->sizey[chip]; myImage->dataCurrent.fill(1.0, dim); } else { if (flatData->successProcessing) { if (*verbosity > 0) emit messageAvailable("Initializing globalweight for chip " + QString::number(chip+1) + " from master flat"+thresholds, "data"); // done before calling this function // if (!flatData->combinedImage[chip]->imageInMemory) flatData->combinedImage[chip]->setupDataInMemorySimple(true); myImage->dataCurrent = flatData->combinedImage[chip]->dataCurrent; // shallow copy } } } else { if (*verbosity > 0) emit messageAvailable("Initializing globalweight for chip " + QString::number(chip+1) + " with constant value 1.0", "data"); long dim = instData->sizex[chip] * instData->sizey[chip]; myImage->dataCurrent.fill(1.0, dim); myImage->dataCurrent.resize(dim); // CHECK: do we still need that given the previous line? myImage->dataCurrent.squeeze(); // shed excess memory } for (auto &it: myImage->dataCurrent) { if (it < flatMinVal || it > flatMaxVal || mask->globalMask[chip][i]) { it = 0.; } ++i; } myImage->imageInMemory = true; myImageList[chip].append(myImage); } // Threshold the global weight based on clipping values for the current combined image void Data::thresholdGlobalWeight(int chip, const Data *comparisonData, const QString filter, const QString threshMin, const QString threshMax) { if (!successProcessing) return; if (comparisonData == nullptr) return; if (!comparisonData->successProcessing) return; if (threshMin.isEmpty() && threshMax.isEmpty()) return; if (userStop || userKill) return; float threshMinVal = -1.e9; float threshMaxVal = 1.e9; QString thresholds = ""; if (!threshMin.isEmpty() && !threshMax.isEmpty()) { threshMinVal = threshMin.toFloat(); threshMaxVal = threshMax.toFloat(); thresholds = "[threshMin, threshMax]"; } else if (!threshMin.isEmpty()) { threshMinVal = threshMin.toFloat(); thresholds = "["+threshMin+", unlimited]"; } else if (!threshMax.isEmpty()) { threshMaxVal = threshMax.toFloat(); thresholds = "[unlimited, "+threshMax+"]"; } if (*verbosity > 0) emit messageAvailable("Thresholding chip "+QString::number(chip+1)+ " of globalweight, " +comparisonData->dataType + " must be within "+ thresholds, "data"); for (auto &it: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == it->filter) { // done before calling this function // if (!comparisonData->combinedImage[chip]->imageInMemory) comparisonData->combinedImage[chip]->setupDataInMemorySimple(true); long k = 0; for (auto &jt: it->dataCurrent) { float compVal = comparisonData->combinedImage[chip]->dataCurrent[k]; if (compVal < threshMinVal || compVal > threshMaxVal) { jt = 0.; } ++k; } } } } void Data::detectDefects(int chip, Data *comparisonData, const QString filter, const bool sameWeight, const QString defectKernel, const QString defectRowTol, const QString defectColTol, const QString defectClusTol) { if (!successProcessing) return; if (sameWeight) return; if (defectKernel.isEmpty()) return; if (defectRowTol.isEmpty() && defectColTol.isEmpty() && defectClusTol.isEmpty()) return; if (!comparisonData->successProcessing) return; if (userStop || userKill) return; QString params = "kernel size = "+defectKernel; if (!defectClusTol.isEmpty()) params += (" clusTol = "+defectClusTol); if (!defectRowTol.isEmpty()) params += (" rowTol = "+defectRowTol); if (!defectColTol.isEmpty()) params += (" colTol = "+defectColTol); if (*verbosity > 0) emit messageAvailable("Defect detection for chip "+QString::number(chip+1)+": "+params, "data"); // Smooth the flatfield int filtersize = defectKernel.toInt(); QString splinemode = "spline"; comparisonData->combinedImage[chip]->backgroundModel(filtersize, splinemode); // Normalize the flat field by the smoothed image long n = comparisonData->combinedImage.at(chip)->naxis1; long m = comparisonData->combinedImage.at(chip)->naxis2; QVector divImage(n*m); long i = 0; for (auto &it : divImage) { it = comparisonData->combinedImage.at(chip)->dataCurrent.at(i) / comparisonData->combinedImage.at(chip)->dataBackground.at(i); ++i; } comparisonData->combinedImage[chip]->releaseBackgroundMemory(); // Bad clusters if (!defectClusTol.isEmpty()) { for (auto &gw: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == gw->filter) { i = 0; for (auto &it : divImage) { if ( fabs(it-1.0) > defectClusTol.toFloat()) gw->dataCurrent[i] = 0.; ++i; } } } } // Bad rows float kappa = 1.5; if (!defectRowTol.isEmpty()) { QVector column1D = collapse_x(divImage, comparisonData->combinedImage[chip]->globalMask, comparisonData->combinedImage[chip]->objectMask, kappa, n, m, "1Dmodel"); for (auto &gw: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == gw->filter) { long badIndex = 0; // Set all rows to zero where the row index in column1D is outside the thresholds for (auto &it : column1D) { if ( fabs(it-1.0) > defectRowTol.toFloat()) { for (long i=0; idataCurrent[i+n*badIndex] = 0.; } ++badIndex; } } } } // Bad cols if (!defectColTol.isEmpty()) { QVector row1D = collapse_y(divImage, comparisonData->combinedImage[chip]->globalMask, comparisonData->combinedImage[chip]->objectMask, kappa, n, m, "1Dmodel"); for (auto &gw: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == gw->filter) { long badIndex = 0; // Set all columns to zero where the column index in row1D is outside the thresholds for (auto &it : row1D) { if ( fabs(it-1.0) > defectColTol.toFloat()) { for (long j=0; jdataCurrent[badIndex+n*j] = 0.; } ++badIndex; } } } } } void Data::applyMask(int chip, QString filter) { for (auto &it: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == it->filter) { long i = 0; for (auto &jt: it->dataCurrent) { if (mask->globalMask.at(chip).at(i)) { jt = 0.; } ++i; } } } } void Data::writeGlobalWeights(int chip, QString filter) { if (!successProcessing) return; if (*verbosity > 0) emit messageAvailable("Writing globalweight for chip " + QString::number(chip+1), "data"); if (instData->bayer.isEmpty()) { for (auto &gw: myImageList[chip]) { if (filter == gw->filter) { gw->writeImage(gw->path + "/" + gw->name, filter); } } } else { QString name; // WARNING! The following assumes that "B" is the filter of the first image in scienceData->myImageList. // The order in which we insert the images in processingCalibration is therefore important! for (auto &gw: myImageList[chip]) { // Create 3 FITS files name = "globalweight_"+instData->name+"_B_"+QString::number(chip+1)+".fits"; gw->writeImage(gw->path + "/" + name, "B"); name = "globalweight_"+instData->name+"_G_"+QString::number(chip+1)+".fits"; gw->writeImage(gw->path + "/" + name, "G"); name = "globalweight_"+instData->name+"_R_"+QString::number(chip+1)+".fits"; gw->writeImage(gw->path + "/" + name, "R"); } // Duplicate the gw image twice in myImageList: if (myImageList[chip].length() == 1) { MyImage *gw2 = new MyImage(mainDirName+"/GLOBALWEIGHTS/", "globalweight_"+instData->name+"_G_"+QString::number(chip+1)+".fits", "", chip+1, mask->globalMask[chip], verbosity); gw2->filter = "G"; gw2->dataCurrent = myImageList[chip][0]->dataCurrent; connect(gw2, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(gw2, &MyImage::critical, this, &Data::pushCritical); connect(gw2, &MyImage::warning, this, &Data::pushWarning); connect(gw2, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(gw2, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(gw2, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); MyImage *gw3 = new MyImage(mainDirName+"/GLOBALWEIGHTS/", "globalweight_"+instData->name+"_R_"+QString::number(chip+1)+".fits", "", chip+1, mask->globalMask[chip], verbosity); gw3->filter = "R"; gw3->dataCurrent = myImageList[chip][0]->dataCurrent; connect(gw3, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(gw3, &MyImage::critical, this, &Data::pushCritical); connect(gw3, &MyImage::warning, this, &Data::pushWarning); connect(gw3, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(gw3, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(gw3, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); myImageList[chip].append(gw2); myImageList[chip].append(gw3); } } } void Data::getGainNormalization() { if (!successProcessing) return; if (userStop || userKill) return; // Calculate the gain normalization factor. // The gains are normalized to the chip with the lowest effective gain // (the one with brightest image in a FLAT) QVector gainNormalization; QVector tmpNormalizationData; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) { gainNormalization << 1.0; // a dummy value to maintain the vector's structure (need one entry per chip) continue; } if (combinedImage[chip]->modeDetermined) { gainNormalization << combinedImage[chip]->skyValue; tmpNormalizationData << combinedImage[chip]->skyValue; } else { emit messageAvailable("Controller::getGainNormalization(): mode was not determined in flat!", "error"); emit critical(); successProcessing = false; return; } } float maxVal = maxVec_T(gainNormalization); if (*verbosity > 0 && instData->numChips>1) emit messageAvailable("Gain normalization factors (multi-chip cameras):", "data"); for (int chip=0; chipnumChips; ++chip) { QString space = " "; if (chip > 9) space = ""; if (instData->badChips.contains(chip)) { if (*verbosity > 0) emit messageAvailable("Chip "+QString::number(chip+1) + space + " : Bad detector, skipped.", "ignore"); continue; } gainNormalization[chip] /= maxVal; combinedImage[chip]->gainNormalization = gainNormalization[chip]; if (*verbosity > 0) emit messageAvailable("Chip "+QString::number(chip+1) + space + " : " + QString::number(gainNormalization[chip], 'f', 6), "ignore"); } } void Data::protectMemory() { for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { it->protectMemory(); } if (combinedImage[chip] != nullptr) { combinedImage[chip]->protectMemory(); } } } void Data::unprotectMemory(int chip) { for (auto &it : myImageList[chip]) { it->unprotectMemory(); } if (combinedImage[chip] != nullptr) { combinedImage[chip]->unprotectMemory(); } } void Data::unprotectMemoryForBackground(int chip) { for (auto &it : myImageList[chip]) { it->unprotectMemoryForBackground(); } } float Data::releaseMemory(float RAMneededThisThread, float RAMneededAllThreads, float currentTotalMemoryUsed, QString mode) { // Return if we have enough RAM available // qDebug() << RAMneededThisThread << RAMneededAllThreads << maxRAM << currentTotalMemoryUsed; if (RAMneededAllThreads < maxRAM - currentTotalMemoryUsed) return -1.; // Free RAM // Simply loop over data structure and free everything that is set to deletable, irrespective of chip, starting with lowest priority QStringList datalist; datalist << "dataBackground" << "dataBackupL3" << "dataBackupL2" << "dataBackupL1" << "dataWeight" << "dataCurrent"; float RAMfreed = 0.; // We release memory in a different order, depending on the process: // If creating master calibrators, we release the previous master calibs and then the raw data. // If we calibrate the science data, we release the raw data in the calibrators first, and then the combined images if (mode == "calibrator") { releaseMemoryCombined(RAMfreed, RAMneededThisThread); releaseMemoryIndividual(datalist, RAMfreed, RAMneededThisThread); } else { releaseMemoryIndividual(datalist, RAMfreed, RAMneededThisThread); releaseMemoryDebayer(RAMfreed, RAMneededThisThread); releaseMemoryCombined(RAMfreed, RAMneededThisThread); } return RAMfreed; } void Data::releaseAllMemory() { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { if (it == nullptr) continue; else it->freeData("all"); } if (combinedImage[chip] == nullptr) continue; else combinedImage[chip]->freeData("all"); } emit globalModelUpdateNeeded(); } void Data::releaseMemoryIndividual(const QStringList &datalist, float &RAMfreed, const float RAMneededThisThread) { for (auto &datatype : datalist) { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { RAMfreed += it->freeData(datatype); if (RAMfreed > RAMneededThisThread) break; } if (RAMfreed > RAMneededThisThread) break; } if (RAMfreed > RAMneededThisThread) break; } } void Data::releaseMemoryDebayer(float &RAMfreed, const float RAMneededThisThread) { if (!currentlyDebayering) return; for (int chip=0; chipnumChips; ++chip) { for (auto &it : bayerList[chip]) { RAMfreed += it->freeData("dataCurrent"); if (RAMfreed > RAMneededThisThread) break; } if (RAMfreed > RAMneededThisThread) break; } } void Data::releaseMemoryCombined(float &RAMfreed, const float RAMneededThisThread) { // Release memory occupied by combined images for (int chip=0; chipnumChips; ++chip) { // if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF" || dataType == "FLAT") { // If executed without data structure having loaded a combined image (or if it wasn't created yet) // it would crash, because none of the class members were instantiated if (combinedImage[chip] == nullptr) continue; RAMfreed += combinedImage[chip]->freeData("dataBackground"); RAMfreed += combinedImage[chip]->freeData("dataBackupL1"); RAMfreed += combinedImage[chip]->freeData("dataCurrent"); // } if (RAMfreed > RAMneededThisThread) break; } } void Data::setMemoryLockReceived(bool locked) { emit setMemoryLock(locked); } void Data::setWCSLockReceived(bool locked) { emit setWCSLock(locked); } // Set which data can (or cannot) be deleted from memory void Data::memorySetDeletable(int chip, QString dataX, bool deletable) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(dataX + " for chip " + QString::number(chip+1) + " marked 'deletable'", "data"); for (auto &it : myImageList[chip]) { if (dataX == "dataCurrent") it->dataCurrent_deletable = deletable; else if (dataX == "dataBackupL1") it->dataBackupL1_deletable = deletable; else if (dataX == "dataBackupL2") it->dataBackupL2_deletable = deletable; else if (dataX == "dataBackupL3") it->dataBackupL3_deletable = deletable; else if (dataX == "dataWeight") it->dataWeight_deletable = deletable; } successProcessing = true; } void Data::writeCombinedImage(int chip) { if (!successProcessing) return; if (userStop || userKill) return; QString name = dirName+"/"+subDirName+"_"+QString::number(chip+1)+".fits"; float exptime = myImageList[chip][0]->exptime; QString filter = myImageList[chip][0]->filter; bool addGainNormalization = true; if (*verbosity > 0) emit messageAvailable("Writing "+subDirName+"_"+QString::number(chip+1)+".fits", "data"); combinedImage[chip]->writeImage(name, filter, exptime, addGainNormalization); successProcessing = combinedImage[chip]->successProcessing; } void Data::writeBackgroundModel(const int &chip, const QString &mode, const QString &basename, bool &staticImageWritten) { if (!successProcessing) return; if (userStop || userKill) return; if (mode == "static" && staticImageWritten) return; QDir backgroundDir(dirName+"/BACKGROUND/"); backgroundDir.mkdir(dirName+"/BACKGROUND/"); float exptime = myImageList[chip][0]->exptime; QString filter = myImageList[chip][0]->filter; bool addGainNormalization = false; QString shortName; if (mode == "static") shortName = subDirName+"/BACKGROUND/"+subDirName+"_"+QString::number(chip+1)+".fits"; else shortName = subDirName+"/BACKGROUND/"+basename+".back.fits"; QString name = mainDirName+"/"+shortName; if (*verbosity > 0) emit messageAvailable("Writing "+mode+" background model "+shortName, "data"); combinedImage[chip]->writeImage(name, filter, exptime, addGainNormalization); if (mode == "static") staticImageWritten = true; successProcessing = combinedImage[chip]->successProcessing; } /* void Data::writeBackgroundModel_newParallel(int chip, MyImage *combinedBackgroundImage, QString mode, QString basename, int threadID, omp_lock_t &backLock, bool &staticImageWritten) { if (!successProcessing) return; if (userStop || userKill) return; if (mode == "static" && staticImageWritten) return; QDir backgroundDir(dirName+"/BACKGROUND/"); backgroundDir.mkdir(dirName+"/BACKGROUND/"); float exptime = myImageList[chip][0]->exptime; QString filter = myImageList[chip][0]->filter; bool addGainNormalization = false; if (mode == "dynamic") { QString shortName = subDirName+"/BACKGROUND/"+basename+".back.fits"; QString name = mainDirName+"/"+shortName; if (*verbosity > 0) emit messageAvailable("Writing "+mode+" background model "+shortName, "data"); combinedBackgroundImage->writeImage(name, filter, exptime, addGainNormalization); successProcessing = combinedBackgroundImage->successProcessing; } else { // static mode // We need a lock so that the model for a given chip is written only once // Some paranoia with checks concerning the state of the model and thread safety. if (staticImageWritten) return; omp_set_lock(&backLock); if (!staticImageWritten) { QString shortName = subDirName+"/BACKGROUND/"+subDirName+"_"+QString::number(chip+1)+".fits"; QString name = mainDirName+"/"+shortName; if (*verbosity > 0) emit messageAvailable("Writing "+mode+" background model "+shortName, "data"); combinedBackgroundImage->writeImage(name, filter, exptime, addGainNormalization); successProcessing = combinedBackgroundImage->successProcessing; staticImageWritten = true; } omp_unset_lock(&backLock); } } */ void Data::resetUserAbort() { userYield = false; userStop = false; userKill = false; } void Data::resetObjectMasking() { // Reset object masks from a potential previous pass if (*verbosity > 0) emit messageAvailable("Resetting object masks ...", "data"); for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->resetObjectMasking(); } } } // only used for debayering void Data::repopulate(int chip, QList replacementList) { for (auto &it : myImageList[chip]) { it->freeAll(); // delete it; // Must not delete in case of debayering!!! will cause crash in DataModel } myImageList[chip].clear(); for (auto &it : replacementList) { myImageList[chip].append(it); } } void Data::populate(QString statusString) { if (*verbosity > 2) emit messageAvailable(subDirName + " : Initializing images ...", "data"); // Read either raw or processed images (master calibs are handled in the c'tor) numImages = 0; #pragma omp parallel for num_threads(maxCPU) firstprivate(dirName, subDirName, statusString) for (int chip=0; chipnumChips; ++chip) { QStringList filter; filter << "*_"+QString::number(chip+1)+statusString+".fits"; QStringList fitsFiles = dir.entryList(filter); // TODO: when splitting data, we must use a filter that does not contain the _chip string (raw data) // if list == empty then reset string and reload myImageList[chip].clear(); for (auto &it : fitsFiles) { bool skip = false; // skip master calibs and normalized flats if (it == subDirName+"_"+QString::number(chip+1)+".fits") skip = true; if (skip) continue; MyImage *myImage = new MyImage(dirName, it, statusString, chip+1, mask->globalMask[chip], verbosity); // myImage->setParent(this); connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); myImage->imageOnDrive = true; myImageList[chip].append(myImage); #pragma omp critical { if (!uniqueChips.contains(chip+1)) uniqueChips.push_back(chip+1); } } #pragma omp atomic numImages += myImageList[chip].length(); } // Sort the vector with the chip numbers (no particular reason, yet) std::sort(uniqueChips.begin(), uniqueChips.end()); if (*verbosity > 0) emit messageAvailable(subDirName + " : " + QString::number(numImages) + " Images initialized ...", "data"); } void Data::countUnsavedImages(long &numUnsavedLatest, long &numUnsavedBackup) { for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList.at(chip)) { if (!it->imageOnDrive) ++numUnsavedLatest; if (it->backupL1InMemory && !it->backupL1OnDrive) ++numUnsavedBackup; if (it->backupL2InMemory && !it->backupL2OnDrive) ++numUnsavedBackup; if (it->backupL3InMemory && !it->backupL3OnDrive) ++numUnsavedBackup; } } } bool Data::isEmpty() { if (myImageList.isEmpty()) return true; bool empty = true; for (int chip=0; chipnumChips; ++chip) { empty = myImageList.at(chip).isEmpty() & empty; } if (empty) return true; else return false; } void Data::clearImageInfo() { imageInfo.baseName.clear(); imageInfo.fullName.clear(); imageInfo.naxis1.clear(); imageInfo.naxis2.clear(); imageInfo.filter.clear(); imageInfo.mjdobs.clear(); imageInfo.chip.clear(); } bool Data::collectMJD() { if (!successProcessing) return false; // Get the MJD for all images in all chips if it hasn't been read yet // (e.g., if the user starts THELI and continues some processing) // The FITS handles are always present in MyImage, even if it hasn't been read yet if (*verbosity > 0) emit messageAvailable("Retrieving Modified Julian Dates ...
", "data"); bool duplicateFound = false; // The MJD is the same for all chips, hence we could just test it for chip 1. // But if one of the images of chip 1 was removed because it was bad, then this would break down; // Therefore, read it for every chip in every exposure #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(subDirName) for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; QVector mjdData; mjdData.reserve(myImageList[chip].length()); if (duplicateFound) continue; for (auto &it : myImageList[chip]) { // if (!it->hasMJDread) { // it->imageFITS->getMJD(); it->getMJD(); // it->mjdobs = it->imageFITS->mjdobs; // it->hasMJDread = true; // } if (*verbosity == 3) emit messageAvailable(it->chipName + " : MJD-OBS = " +QString::number(it->mjdobs, 'f', 12), "image"); mjdData.append(it->mjdobs); } if (!duplicateFound && hasDuplicates_T(mjdData)) { // QmessageBox displayed only once (cannot break from loop because of omp parallel) emit showMessageBox("Data::DUPLICATE_MJDOBS", subDirName, ""); duplicateFound = true; } } if (duplicateFound) return false; else return true; } // The background header correction tasks needs a number of header keywords // before processing the actual exposures bool Data::getPointingCharacteristics() { if (!successProcessing) return false; if (*verbosity > 0) emit messageAvailable("Retrieving pointing characteristics for "+subDirName + " ...", "data"); QVector crval1Exposure; QVector crval2Exposure; QVector crval1Vertex; QVector crval2Vertex; // we include unused chips here because otherwise any centroids our boundaries might be biased for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->loadHeader(); crval1Exposure << it->wcs->crval[0]; crval2Exposure << it->wcs->crval[1]; crval1Vertex << it->alpha_ll; crval1Vertex << it->alpha_lr; crval1Vertex << it->alpha_ul; crval1Vertex << it->alpha_ur; crval2Vertex << it->delta_ll; crval2Vertex << it->delta_lr; crval2Vertex << it->delta_ul; crval2Vertex << it->delta_ur; } } RAcenter = straightMedian_T(crval1Exposure, false); DECcenter = straightMedian_T(crval2Exposure, false); // Declination double crval2Min = minVec_T(crval2Vertex); double crval2Max = maxVec_T(crval2Vertex); double crval2Radius = 60.*(crval2Max - crval2Min) / 2.; // Right ascension double crval1Min = minVec_T(crval1Vertex); double crval1Max = maxVec_T(crval1Vertex); // Did we cross the origin (qualitative check)? // If yes, then we need to correct the values if (crval1Max - crval1Min > 350.) { for (auto &it : crval1Vertex) { if (it > 180.) it -= 180.; } crval1Min = minVec_T(crval1Vertex); crval1Max = maxVec_T(crval1Vertex); } double crval1Radius = 60.*(crval1Max - crval1Min) / 2. * cos(DECcenter*rad); // Maximum search radius, plus 10% safety margin searchRadius = 1.1*sqrt(crval1Radius*crval1Radius + crval2Radius*crval2Radius); if (RAcenter == -100. || DECcenter == -100. || searchRadius == -100.) return false; else return true; } bool Data::hasImages() { if (numImages == 0) { emit showMessageBox("Data::IMAGES_NOT_FOUND", processingStatus->statusString, dirName); emit critical(); return false; } else return true; } void Data::resetProcessbackground() { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->resetObjectMasking(); it->hasBrightStarsChecked = false; it->backgroundModelDone = false; it->segmentationDone = false; it->maskExpansionDone = false; it->backupCopyBackgroundMade = false; it->leftBackgroundWindow = false; // possibly squeeze some of the data vectors, but then we'd just need to reserve them again [...] } } } void Data::cleanBackgroundModelStatus() { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->resetObjectMasking(); it->backgroundModelDone = false; it->segmentationDone = false; it->maskExpansionDone = false; } } } QVector Data::getKeyFromAllImages(const QString key) { if (*verbosity > 1) emit messageAvailable("Retrieving key " + key + " for images in " + subDirName + " ...", "data"); // dumping everything to a double vector QVector data; for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { if (!it->metadataTransferred) it->loadHeader(); // needed if data requested immediately after launch if (key == "CRVAL1") data << it->wcs->crval[0]; else if (key == "CRVAL2") data << it->wcs->crval[1]; else if (key == "CRPIX1") data << it->wcs->crpix[0]; else if (key == "CRPIX2") data << it->wcs->crpix[1]; else if (key == "NAXIS1") data << it->naxis1; else if (key == "NAXIS2") data << it->naxis2; else if (key == "CORNERS_CRVAL1") { data << it->alpha_ll; data << it->alpha_lr; data << it->alpha_ul; data << it->alpha_ur; } else if (key == "CORNERS_CRVAL2") { data << it->delta_ll; data << it->delta_lr; data << it->delta_ul; data << it->delta_ur; } else if (key == "DATE-OBS") { double tmp = dateobsToDecimal(it->dateobs); // Only append if dateobs is valid (we won't have data taken before the year 1000) if (tmp > 1000.) data << tmp; } } } return data; } void Data::modelUpdateReceiver(QString chipName) { emit modelUpdateNeeded(chipName); } void Data::pushMessageAvailable(QString message, QString type) { emit messageAvailable(message, type); } void Data::pushCritical() { emit critical(); } void Data::pushWarning() { emit warning(); } int Data::identifyClusters(QString toleranceString) { if (!successProcessing) return 0; // This routine detects associations of images that are overlapping, and assigns a unique number int groupNumber = 0; int groupNumberOld = 0; float tolerance = 0.; if (!toleranceString.isEmpty()) tolerance = toleranceString.toFloat() / 60.; // Initiate the first of all images myImageList[instData->validChip][0]->groupNumber = groupNumber; for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { it->loadHeader(); } } bool unassigned = true; int loop = 0; while (unassigned) { // Loop over all images to see if they overlap with the current image for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { // Jump over images that have been assigned already if (loop > 0 && it->groupNumber == groupNumberOld) continue; // Check distance of all other images to the current image, and update their groupNumber if matching findOverlappingImages(it, tolerance); } } // Check if images remain unassigned groupNumberOld = groupNumber; unassigned = checkForUnassignedImages(groupNumber); ++loop; } if (*verbosity >= 0) { if (groupNumber == 0) { emit messageAvailable("A single image association was identified. It is left unchanged.", "data"); } else { emit messageAvailable(QString::number(groupNumber+1)+" image associations identified ...", "data"); } } return groupNumber; } void Data::doImagesOverlap(const MyImage &imgRef, MyImage &imgTest, const float tolerance) { if (!successProcessing) return; double alpha1 = rad * imgRef.wcs->crval[0]; double delta1 = rad * imgRef.wcs->crval[1]; double alpha2 = rad * imgTest.wcs->crval[0]; double delta2 = rad * imgTest.wcs->crval[1]; double dDelta = delta2 - delta1; double dAlpha = alpha2 - alpha1; // Haversine formula to calculate angular distance between two points on a sphere double distance = 2.*asin( sqrt( pow(sin(dDelta/2.),2) + cos(delta1)*cos(delta2)*pow(sin(dAlpha/2.),2))) / rad; if (distance <= 2.* instData->radius + tolerance) imgTest.groupNumber = imgRef.groupNumber; } void Data::findOverlappingImages(const MyImage *img, const float tolerance) { if (!successProcessing) return; for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { // If unassigned, check overlap and if positive, assign same group number if (it->groupNumber == -1) { doImagesOverlap(*img, *it, tolerance); } } } } bool Data::checkForUnassignedImages(int &groupNumber) { if (!successProcessing) return false; bool unassigned = false; for (int chip=0; chipnumChips; ++chip) { bool breaked = false; for (auto &it : myImageList[chip]) { if (it->groupNumber == -1) { unassigned = true; // Another group exists, increase group counter, and start group ++groupNumber; it->groupNumber = groupNumber; breaked = true; break; } } if (breaked) break; } return unassigned; } // Restores FITS images from backupDirName; replaces dataCurrent with dataBackup (if in memory) void Data::restoreBackupLevel(QString backupDirName) { emit messageAvailable("Restoring "+backupDirName + " images ...", "data"); if (backupDirName == "_IMAGES") { emit messageAvailable("Inconsistency detected in backup structure. This is likely a bug.", "error"); emit critical(); return; } QDir backupDir(dirName+"/"+backupDirName); // Qt 5.7 compatibility backupDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); if (!backupDir.exists() || backupDir.count() == 0) { emit messageAvailable(dirName+"/"+backupDirName+": No backup FITS files found, restoring memory only.", "data"); } /* * QT5.9 if (!backupDir.exists() || backupDir.isEmpty()) { emit messageAvailable(dirName+"/"+backupDirName+": No backup FITS files found, restoring memory only.", "data"); } */ // Remove all currently present FITS files removeCurrentFITSfiles(); // CASE 1: Restore the raw data if (backupDirName == "RAWDATA") { restoreRAWDATA(); return; } // CASE 2: Data in memory (and on drive) // Comparing output from QDir::absolutePath() because it removes double // and trailing / QDir d1(pathBackupL1); QDir d2(pathBackupL2); QDir d3(pathBackupL3); QDir dc(dirName+"/"+backupDirName); bool success = true; QString newStatusRAM = ""; if (d1.absolutePath() == dc.absolutePath()) success = success && restoreFromBackupLevel("L1", newStatusRAM); else if (d2.absolutePath() == dc.absolutePath()) success = success && restoreFromBackupLevel("L2", newStatusRAM); else if (d3.absolutePath() == dc.absolutePath()) success = success && restoreFromBackupLevel("L3", newStatusRAM); // qDebug() << "success = " << success << newStatusRAM; // Leave if there was an error during file operations if (!success) { emit messageAvailable("Data::restoreBackupLevel(): Error restoring FITS files from " + backupDirName, "error"); emit critical(); return; } else { // If newStatusRAM has changed then the operation was successful, and we can remove the directory if (!newStatusRAM.isEmpty()) { if (backupDir != QDir::home()) backupDir.removeRecursively(); emit statusChanged(newStatusRAM); emit updateModelHeaderLine(); return; } } // qDebug() << "BLEVEL CASE3"; // CASE 3: We are still here. That means the user selected a backup dir on drive that is not mapped in one of the backup levels restoreFromDirectory(backupDirName); } void Data::removeCurrentFITSfiles() { QStringList fitsFileNames = dir.entryList(QStringList() << "*.fits"); for (auto &it : fitsFileNames) { QFile fitsFile(dirName+"/"+it); if (!fitsFile.remove()) { emit messageAvailable("Could not delete " + it + "! Manual cleanup required.", "error"); emit critical(); } } } void Data::removeCatalogs() { // Remove all scamp, SourceExtractor and .anet catalogs. Keep the iview catalogs // Used when recreating source catalogs QDir catalogDir(dirName + "/cat/"); QStringList catFileNames = catalogDir.entryList(QStringList() << "*.cat" << "*.scamp" << "*.anet" ); for (auto &it : catFileNames) { QFile catFile(dirName+"/cat/"+it); if (!catFile.remove()) { emit messageAvailable("Could not delete " + it, "warning"); emit warning(); } } } // Reflecting backup parameters in Data after successful processing void Data::transferBackupInfo() { if (!successProcessing) return; MyImage *it = myImageList[instData->validChip][0]; pathBackupL1 = it->pathBackupL1; pathBackupL2 = it->pathBackupL2; pathBackupL3 = it->pathBackupL3; statusBackupL1 = it->statusBackupL1; statusBackupL2 = it->statusBackupL2; statusBackupL3 = it->statusBackupL3; } // Reset status (when restoring original data) void Data::resetBackupInfo() { processingStatus->statusString = ""; pathBackupL1 = ""; pathBackupL2 = ""; pathBackupL3 = ""; statusBackupL1 = ""; statusBackupL2 = ""; statusBackupL3 = ""; } // Used if data is restored from a backup dir alone, i.e. data are not present in RAM in any backup level void Data::restoreFromDirectory(QString backupDirName) { // Check if any data can be restored QDir backupDir(dirName+"/"+backupDirName); if (!backupDir.exists()) { emit messageAvailable("Data::restoreFromDirectory(): " + subDirName+"/"+backupDirName+" does not exist, no data were restored or deleted.", "error"); emit critical(); return; } backupDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); // Qt 5.7 compatibility // if (backupDir.isEmpty()) { Qt 5.9 if (backupDir.count() == 0) { emit messageAvailable(subDirName+"/"+backupDirName+" is empty, no data were restored or deleted.", "error"); emit critical(); return; } // Remove all currently present FITS files removeCurrentFITSfiles(); QString newStatusDrive = ""; if (backupDirName == "RAWDATA") newStatusDrive = ""; else newStatusDrive = backupDirName.split("_").at(0); processingStatus->statusToBoolean(newStatusDrive); processingStatus->getStatusString(); processingStatus->writeToDrive(); if (!moveFiles("*.fits", dirName+"/"+backupDirName, dirName)) { emit messageAvailable(backupDirName + " : Restoring failed for some or all FITS files", "error"); emit critical(); return; } else { // Paranoia check (afaik this can never happen, but nonetheless ...) if (backupDirName == QDir::homePath()) { emit messageAvailable("Data::restoreFromDirectory(): STOP: Was about to remove your home directory! This should never happen.", "error"); emit critical(); return; } if (!backupDir.removeRecursively()) { emit messageAvailable("Data::restoreFromDirectory(): Could not completely remove " + backupDirName, "error"); emit critical(); return; } } emit statusChanged(newStatusDrive); emit updateModelHeaderLine(); } // Returns false if anything goes wrong with the file operations bool Data::restoreFromBackupLevel(QString level, QString &newStatusRAM) { long i = 0; bool success = true; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it: myImageList[chip]) { // Continue if no backup data in RAM if (level == "L1") success = success && it->makeL1Current(); else if (level == "L2") success = success && it->makeL2Current(); else if (level == "L3") success = success && it->makeL3Current(); emit it->modelUpdateNeeded(it->chipName); if (i==0) newStatusRAM = it->processingStatus->statusString; QString statusTmp2 = it->processingStatus->statusString; if (statusTmp2 != newStatusRAM) { emit messageAvailable("Data::restoreBackupLevel(): Inconsistent processing status detected in RAM", "error"); emit critical(); return false; } ++i; } } // Obsolete images have been removed. Now also remove the corresponding backup directories. // Some paranoia making sure we don't accidentally delete the user's home directory. if (level == "L1") { QDir backupL3(pathBackupL3); if (!pathBackupL3.isEmpty() && backupL3 != QDir::home()) backupL3.removeRecursively(); } if (level == "L2") { QDir backupL1(pathBackupL1); QDir backupL3(pathBackupL3); if (!pathBackupL1.isEmpty() && backupL1 == QDir::home()) backupL1.removeRecursively(); if (!pathBackupL3.isEmpty() && backupL3 == QDir::home()) backupL3.removeRecursively(); } if (level == "L3") { QDir backupL1(pathBackupL1); QDir backupL2(pathBackupL2); if (!pathBackupL1.isEmpty() && backupL1 == QDir::home()) backupL1.removeRecursively(); if (!pathBackupL2.isEmpty() && backupL2 != QDir::home()) backupL2.removeRecursively(); } transferBackupInfo(); processingStatus->statusToBoolean(newStatusRAM); processingStatus->getStatusString(); processingStatus->writeToDrive(); return success; } void Data::restoreRAWDATA() { QDir rawdataDir(dirName+"/RAWDATA"); if (!rawdataDir.exists()) { emit messageAvailable(subDirName+"/RAWDATA does not exist, "+subDirName+" remains unmodified.", "note"); emit warning(); return; } rawdataDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); // Qt 5.7 compatibility // if (rawdataDir.isEmpty()) { Qt 5.9 if (rawdataDir.count() == 0) { emit messageAvailable(subDirName+"/RAWDATA is empty, "+subDirName+" remains unmodified.", "note"); emit warning(); return; } // Protect RAWDATA by moving it if (!rawdataDir.rename(dirName+"/RAWDATA", mainDirName+"/"+subDirName+"_rawdata")) { emit messageAvailable("Could not create temporary directory "+mainDirName+"/"+subDirName+"_rawdata!", "error"); emit critical(); return; } emit messageAvailable("Restoring " + dirName+"/RAWDATA ...", "data"); // Paranoia check (afaik this can never happen, but nonetheless ...) if (dirName == QDir::homePath()) { emit messageAvailable("Data::restoreRAWDATA(): STOP: Was about to remove your home directory! This should never happen.", "error"); emit critical(); return; } // remove current dir dir.removeRecursively(); // restore rawdataDir.rename(mainDirName+"/"+subDirName+"_rawdata", dirName); emit setMemoryLock(true); releaseAllMemory(); resetBackupInfo(); myImageList.clear(); combinedImage.clear(); myImageList.resize(instData->numChips); combinedImage.resize(instData->numChips); dataInitialized = false; emit globalModelUpdateNeeded(); // CHECK: not necessarily threadsafe, depending on the thread in which the slot gets executed emit setMemoryLock(false); QString newStatus = ""; processingStatus->deleteFromDrive(); processingStatus->reset(); // processingStatus->writeToDrive(); emit statusChanged(newStatus); emit updateModelHeaderLine(); } void Data::emitStatusChanged() { emit statusChanged(processingStatus->statusString); emit updateModelHeaderLine(); } bool Data::hasMatchingPartnerFiles(QString testDirName, QString suffix, bool abort) { if (!successProcessing) return false; // This function checks whether e.g. all science exposures have a weight, or astrometric header // List of images QStringList imageList; if (suffix == ".scamp") { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { if (!imageList.contains(it->rootName) && it->activeState == MyImage::ACTIVE) { imageList.append(it->rootName); } } } } else { for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList[chip]) { if (it->activeState == MyImage::ACTIVE) imageList.append(it->chipName); } } } // List of reference data (weights, catalogs, headers, etc ...) QDir testDir(testDirName); QStringList notMatched; QStringList filter("*"+suffix); QStringList testList = testDir.entryList(filter); testList.replaceInStrings(suffix,""); imageList.sort(); testList.sort(); // If entries are equal, or list1 is fully contained in list2, then we can leave // Equal? if (imageList.operator ==(testList)) { return true; } else { // Fully contained? for (auto & it : imageList) { // If not contained in list2, add it to the list of missing items if (!testList.contains(it)) notMatched << it; } } if (notMatched.isEmpty()) return true; else { QString missingItems; int i = 0; for (auto &it: notMatched) { if (i>19) { missingItems.append("...\n"); break; // Do not show more than 20 items } missingItems.append(it); // missingItems.append(suffix); missingItems.append("\n"); ++i; } if (abort) { emit messageAvailable(subDirName + " : Not all images have matching "+suffix+ " files!", "error"); emit critical(); successProcessing = false; } else { emit messageAvailable(subDirName + " : Not all images have matching "+suffix+ " files!", "warning"); emit warning(); } long nbad = notMatched.length(); if (suffix.contains("weight")) { emit showMessageBox("Data::WEIGHT_DATA_NOT_FOUND", QString::number(nbad), missingItems); } else if (suffix.contains("head")) { emit showMessageBox("Data::HEADER_DATA_NOT_FOUND", QString::number(nbad), missingItems); } else if (suffix.contains("scamp")) { emit showMessageBox("Data::SCAMP_CATS_NOT_FOUND", QString::number(nbad), missingItems); } return false; } } void Data::criticalFromQueryReceived() { successProcessing = false; } bool Data::doesCoaddContainRaDec(const QString &refRA, const QString &refDEC) { if (refRA.isEmpty() && refDEC.isEmpty()) return true; // Start assuming that no chip of a multi-chip camera contains this coordinate. If a single chip does contain it, we can break and exit bool containsRADEC = false; for (int chip=0; chipnumChips; ++chip) { for (auto &it : myImageList.at(chip)) { if (it->containsRaDec(refRA, refDEC)) { containsRADEC = true; break; } } } return containsRADEC; } // Data is listening to all its MyImages /* void Data::establish_connections() { for (int chip=0; chipnumChips; ++chip) { for (auto &image : myImageList[chip]) { connect(image, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); } } } */ void Data::deleteMyImageList() { if (myImageList.isEmpty()) return; for (int chip=0; chipnumChips; ++chip) { for (auto &it: myImageList[chip]) { delete it; it = nullptr; } } } /* void Data::forceStatus(int chip, QString status) { for (auto &it : myImageList[chip]) { it->processingStatus->statusString = status; } } */ /* void Data::getFixedHeaderKeys(QString filename, QStringList &badImages) { if (userStop || userKill) return; long naxis1 = 0; long naxis2; QString filter = "UNKNOWN"; double mjdobs = 0.; fitsfile *fptr = nullptr; int status = 0; fits_open_file(&fptr, filename.toUtf8().data(), READONLY, &status); if (!status) { char *filterName = new char(filename.length()+10); fits_read_key_lng(fptr, "NAXIS1", &naxis1, NULL, &status); fits_read_key_lng(fptr, "NAXIS2", &naxis2, NULL, &status); fits_read_key_dbl(fptr, "MJD-OBS", &mjdobs, NULL, &status); fits_read_key_str(fptr, "FILTER", filterName, NULL, &status); if (status && !badImages.contains(filename)) { badImages.push_back(filename); imageInfo.naxis1.push_back(0); imageInfo.naxis2.push_back(0); imageInfo.mjdobs.push_back(0.); imageInfo.filter.push_back("UNKNOWN"); } else { filter = QString(filterName); imageInfo.naxis1.push_back(naxis1); imageInfo.naxis2.push_back(naxis2); imageInfo.mjdobs.push_back(mjdobs); imageInfo.filter.push_back(filter); // qDebug() << qSetRealNumberPrecision(12) << mjdobs; } delete filterName; filterName = nullptr; } fits_close_file(fptr, &status); if (status) { emit messageAvailable(subDirName + " : Data::getFixedHeaderKeys(): Could not read NAXIS1/2, MJD-OBS, and/or FILTER in" + filename, "error"); printCfitsioError("getFixedHeaderKeys()", status); } } */ // Reads relevant keywords from the headers /* bool Data::getHeaders() { QStringList badImages; for (auto &it : imageInfo.fullName) { getFixedHeaderKeys(dirName+"/"+it, badImages); } if (!badImages.isEmpty()) { // Truncate (in case of lots of images) QString summary = truncateImageList(badImages,10); emit messageAvailable(tr("Could not read one or more of the following keywords:
NAXIS1, NAXIS2, FILTER, MJD-OBS")+ tr("
Add the keywords manually, or the remove the corrupted images.
")+summary, "error"); emit critical(); emit showMessageBox("Data::CANNOT_READ_HEADER_KEYS", summary, ""); return false; } else { return true; } } */ // Calculates the median geometry for the images of a chip. // Identifies outliers and moves them to a 'badGeometry/' sub-directory // UNUSED /* QString Data::checkGeometry() { if (!successProcessing) return ""; QStringList badImages; for (auto &chip : uniqueChips) { // Find images matching that chip, extract their geometries QStringList imageList = collectNamesForChip(chip); QVector tmp1; QVector tmp2; for (auto &it : imageList) { tmp1.push_back(imageInfo.naxis1[mapName.value(it)]); tmp2.push_back(imageInfo.naxis2[mapName.value(it)]); } // Median image geometry for chip 'chip': int medianNaxis1 = straightMedian_T(tmp1); int medianNaxis2 = straightMedian_T(tmp2); mapNaxis1.insert(chip, medianNaxis1); mapNaxis2.insert(chip, medianNaxis2); // Collect images whose geometry deviates from the median geometry for (auto &it : imageList) { if (imageInfo.naxis1[mapName.value(it)] != medianNaxis1 || imageInfo.naxis2[mapName.value(it)] != medianNaxis2) { badImages << it; } } } if (badImages.isEmpty()) return "success"; // What to do with the bad images QString summary = truncateImageList(badImages, 10); emit messageAvailable(subDirName + " : WARNING: The 2D dimensions of the following images deviate from the median dimension:
" +summary+"
"+ "This can be a result of inconsistent binning or readout modes.
" "THELI can move these images to a 'badGeometries/' sub-directory " "and re-attempt the process. Alternatively, you can cancel and inspect the data yourself " "before trying again.\n", "warning"); QMessageBox msgBox; msgBox.setText(tr("ERROR: The 2D dimensions of the following images deviate from the median dimension:")); msgBox.setInformativeText(summary+ "This can be a result of inconsistent binning or readout modes. " "THELI can move these images to a 'badGeometries/' sub-directory " "and re-attempt the process. Alternatively, you can cancel and inspect the data yourself " "before trying again.\n"); QAbstractButton *pButtonOk = msgBox.addButton(tr("Move images and re-try"), QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton()==pButtonOk) { // make a "badGeometry" sub-directory QString badDirName = dirName+"/badGeometry/"; QDir badDir(badDirName); badDir.mkpath(badDirName); // move selected images to badstats for (auto &it : badImages ) { QFile badFile(dirName+"/"+it); if (!badFile.rename(badDirName+"/"+it)) { emit messageAvailable(subDirName + " : Data::checkGeometry(): Could not execute the following operation:
"+ "mv " + dirName+"/"+it + badDirName+"/"+it, "error"); emit critical(); return "cancel"; } } return "recurse"; } else { return "cancel"; } } */ /* void Data::incrementCurrentThreads(int ¤tThreads, omp_lock_t &lock) { omp_set_lock(&lock); ++currentThreads; omp_unset_lock(&lock); } void Data::decrementCurrentThreads(int ¤tThreads, omp_lock_t &lock) { omp_set_lock(&lock); --currentThreads; omp_unset_lock(&lock); } */ /* void Data::getModeCombineImagesBackground(int chip, MyImage *image) { if (!successProcessing) return; if (userStop || userKill) return; if (image->modeDetermined) return; // Get the mean / mode of the combined image if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { // mode doesn't work, as all values are very very narrowly distributed around a single value (which might be integer on top of that) image->skyValue = meanMask(image->dataCurrent, mask->globalMask[chip]); } else { image->skyValue = modeMask(image->dataCurrent, "stable", mask->globalMask[chip])[0]; } image->modeDetermined = true; successProcessing = true; } */ /* void Data::writeGlobalflags(int chip, QString filter) { if (*verbosity > 0) emit messageAvailable("Writing globalflag for chip " + QString::number(chip+1), "data"); // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; long naxis1 = instData->sizex[chip]; long naxis2 = instData->sizey[chip]; long nelements = naxis1*naxis2; unsigned int *array = new unsigned int[nelements]; for (long i=0; iname+"_"+filter+"_"+QString::number(chip+1)+".fits"; // Overwrite file if it exists globalFlagName = "!"+globalFlagName; fits_create_file(&fptr, globalFlagName.toUtf8().data(), &status); fits_create_img(fptr, bitpix, naxis, naxes, &status); fits_write_img(fptr, TBYTE, fpixel, nelements, array, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError("writeGlobalflags()", status); } */ /* float Data::memoryNeeded(int chip) { float footprint = 0; for (auto &it: myImageList[chip]) { footprint += it->dataCurrent.size() * sizeof(float); } return footprint / 1024. / 1024.; } */ /* float Data::memoryCurrentFootprint(bool globalweights) { float footprint = 0.; // Storage (in MB) used for all images currently held in memory // CHECK: crashes here when clicking the project reset button right after launching the GUI. // still crashes despite this if-clause. MyImageList[chip] seems undefined (innermost for loop) if (processingStatus == nullptr || !processingStatus->HDUreformat || !dataInitialized) return 0.; // MyImageList undefined, or no data loaded yet // For an unknown reason, I cannot access myImageList for GLOBALWEIGHTS when changing a project; memoryprogressbar then crashes the UI if (!globalweights) { if (!myImageList.isEmpty()) { // e.g. if RAWDATA are restored for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it: myImageList[chip]) { footprint += it->dataCurrent.capacity() * sizeof(float); footprint += it->dataBackupL1.capacity() * sizeof(float); footprint += it->dataBackupL2.capacity() * sizeof(float); footprint += it->dataBackupL3.capacity() * sizeof(float); footprint += it->dataMeasure.capacity() * sizeof(float); footprint += it->objectMask.capacity() * sizeof(bool); footprint += it->dataWeight.capacity() * sizeof(float); footprint += it->dataWeightSmooth.capacity() * sizeof(float); footprint += it->dataBackground.capacity() * sizeof(float); footprint += it->dataSegmentation.capacity() * sizeof(long); } } } // Also check for debayered images that are not yet in the nominal myimage list if (!bayerList.isEmpty()) { for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it: bayerList[chip]) { footprint += it->dataCurrent.capacity() * sizeof(float); } } } } if (!combinedImage.isEmpty()) { for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; // Crashes if equal to nullptr if (combinedImage[chip] != nullptr) { footprint += combinedImage[chip]->dataCurrent.capacity() * sizeof(float); } } } return footprint /= (1024 * 1024); } */ // UNUSED // Force free // should use the controller's 'lock' /* void Data::memoryFreeDataX(int chip, QString dataX) { // if (!successProcessing) return; QVector empty {}; if (dataX != "combined") { long memReleased = myImageList[chip][0]->dataCurrent.length()*4*myImageList[chip].length(); if (*verbosity > 1) emit messageAvailable("Freeing "+QString::number(memReleased) + " MB", "data"); for (auto &it : myImageList[chip]) { if (dataX == "dataCurrent") it->dataCurrent.swap(empty); else if (dataX == "dataBackupL1") it->dataBackupL1.swap(empty); else if (dataX == "dataBackupL2") it->dataBackupL2.swap(empty); else if (dataX == "dataBackupL3") it->dataBackupL3.swap(empty); else if (dataX == "dataWeight") it->dataWeight.swap(empty); } } else { long memReleased = combinedImage[chip]->dataCurrent.length()*4; if (*verbosity > 1) emit messageAvailable("Freeing "+QString::number(memReleased) + " MB", "data"); combinedImage[chip]->dataCurrent.swap(empty); } // successProcessing = true; } */ /* bool Data::setModeFlag(int chip, QString min, QString max) { if (!successProcessing) return false; QString thresholds = "[" + min + "," + max + "]"; for (auto &it : myImageList[chip] ) { // Try and read image; readImage() returns true immediately if image is already in memory // if (!(it->readImage())) return false; // if (!it->modeDetermined) { // qDebug() << "QDEBUG: Data::setModeFlag(): Error: Mode should have been determined."; // return false; // } if (!min.isEmpty()) { if (it->skyValue < min.toFloat()) { it->validMode = false; } } if (!max.isEmpty()) { if (it->skyValue > max.toFloat()) it->validMode = false; } if (!it->validMode) { if (*verbosity > 0) emit messageAvailable(it->baseName + " : Mode "+it->skyValue+" is outside user-defined thresholds " + thresholds + ". Image will be ignored when calculating master calibs.", "data"); } } return true; } */ // UNUSED /* bool Data::writeImages(int chip, QString statusString) { if (!successProcessing) return false; if (userStop || userKill) return false; bool success = true; // unused for (auto &it : myImageList[chip]) { it->processingStatus->statusString = statusString; it->writeImage(); } return success; } */ /* QString Data::getMasterFilename(QString type, int chip) { return mainDirName+"/"+type+"/"+type+"_"+QString::number(chip+1)+".fits"; } */ /* QVector Data::getOverscanArea(QString axis, int chip) { QVector overscanArea; // X-axis if (axis == "x") { QVector min = instData->overscan_xmin; QVector max = instData->overscan_xmax; if (!min.isEmpty() && !max.isEmpty()) { overscanArea << min[chip]; overscanArea << max[chip]; } } // Y-axis if (axis == "y") { QVector min = instData->overscan_ymin; QVector max = instData->overscan_ymax; if (!min.isEmpty() && !max.isEmpty()) { overscanArea << min[chip]; overscanArea << max[chip]; } } return overscanArea; } */ /* QStringList Data::collectNamesForChip(int chip) { QStringList names; long k = 0; for (auto &it: imageInfo.chip) { if (it == chip) names << imageInfo.fullName[k]; ++k; } return names; } */ // UNUSED /* bool Data::containsUnsavedImages() { for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (!it->imageOnDrive) return false; } } return true; } */ /* QStringList Data::collectNamesForFilter(QString filter) { QStringList names; long k = 0; for (auto &it: imageInfo.filter) { if (it == filter) names << imageInfo.fullName[k]; ++k; } return names; } */ /* void Data::pushErrorOccurred() { emit errorOccurredInMyImage(); } */ /* void Data::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("Data::"+funcName+":
" + subDirName + " : " + errorCodes->errorKeyMap.value(status), "error"); emit critical(); } } */ THELI-3.1.3/src/processingInternal/data.h000066400000000000000000000270011417631501300201060ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // The 'data' class keeps the references to all FITS images // encountered in a single directory. // It triggers a 'read-from-disk' when an image is required for some task. // It dumps images to disk if memory runs low or if the user requests it. // It defines the various processing functions that can operate on the data. // The processing functions read and update the successProcessing flag for each chip // (similar to the cfitsio status flag) #ifndef DATA_H #define DATA_H #include "mask.h" #include "../myimage/myimage.h" #include "../instrumentdata.h" #include "../processingStatus/processingStatus.h" #include #include #include #include #include #include #include class Data : public QObject { Q_OBJECT public: explicit Data(const instrumentDataType *instrumentData, Mask *detectorMask, QString maindirname, QString subdirname, int *verbose); ~Data(); struct ImageInfo { QStringList fullName; QStringList baseName; QStringList filter; QList chip; QList naxis1; QList naxis2; QList mjdobs; }; ImageInfo imageInfo; Mask *mask; ProcessingStatus *processingStatus = nullptr; const instrumentDataType *instData; bool successProcessing = true; QDir dir; QString dirName = ""; QString status = ""; QString statusAfterProcessing = ""; QString mainDirName = ""; QString subDirName = ""; QString dataType = ""; QMap mapName; QMap mapNaxis1; QMap mapNaxis2; bool userYield = false; bool userStop = false; bool userKill = false; double rad = 3.1415926535 / 180.; omp_lock_t progressLock; float *progress; long numActiveImages = 0; float progressStepSize = 0.; float progressCombinedStepSize = 0.; // Pointing characteristics double RAcenter = -100.; double DECcenter = -100.; double searchRadius = -100.; // Multi-threading; params set externally by 'controller' int maxCPU = 1; // Overall, maximum number of CPUs to be used int maxExternalThreads = 1; // Maximum number of threads working on chips; equal or smaller than maxCPU int maxInternalThreads = 1; // Maximum number of threads working on images; equal or smaller than maxCPU - maxExternalThreads int maxThreadsIO = 1; // Maximum number of IO threads long maxRAM = 0; // Max amount of RAM available for processing (MB) int currentExternalThreads = 0; // The current number of external running threads (over different chips) int currentInternalThreads = 0; // The current number of internal running threads (over images of the same chips) bool useGPU = false; int *verbosity; bool dataInitialized = false; bool isTaskRepeated = false; QVector staticModelDone; bool currentlyDebayering = false; // A 2D list, 1st axis has one entry for each chip. // The 2nd axis keeps references to all FITS files of that chip (in memory or on disk) QVector> myImageList; // A list of all images per chip [chip][image] QVector> bayerList; // A list of all debayered images (only needed for memory calculations) QVector> exposureList; // A list of all images per exposure [exposure][chip] // A list of master calibration files, one for each chip (if applicable for this structure) QVector combinedImage; QString pathBackupL1 = ""; QString pathBackupL2 = ""; QString pathBackupL3 = ""; QString statusBackupL1 = ""; QString statusBackupL2 = ""; QString statusBackupL3 = ""; float maskValue = -1e9; long numImages = 0; long numMasterCalibs = 0; bool hasAllMasterCalibs = false; QVector uniqueChips; // length: numChips // QString checkGeometry(); bool hasImages(); // bool getHeaders(); void clearImageInfo(); // QStringList collectNamesForChip(int chip); // QStringList collectNamesForFilter(QString filter); // void maskInit(Mask &mask, long n, long m); // QVector getOverscanArea(QString axis, int chip); // QString getMasterFilename(QString type, int chip); // Processing functions void combineImagesCalib(int chip, float (*combineFunction_ptr) (const QVector &, const QVector &, long), const QString nlow, const QString nhigh, const QString dirName, const QString subDirName, const QString dataType); void combineImages(const int chip, const QString nlowString, const QString nhighString, const QString currentImage, const QString mode, const QString dirName, const QString subDirName, QVector &dataStaticModelDone); // void combineImages_newParallel(int chip, MyImage *masterCombined, QList &backgroundList, QString nlow, QString nhigh, QString currentImage, QString mode, const QString subDirName); void deleteMyImageList(); // void forceStatus(int chip, QString status); void loadCombinedImage(int chip); void populate(QString statusString); void repopulate(int chip, QList replacementList); // void resetDataCurrentToBackup(int chip); // bool setModeFlag(int chip, QString min, QString max); void writeCombinedImage(int chip); // bool writeImages(int chip, QString statusString); void resetUserAbort(); // Flags that control whether a task is actually executed (or skipped) // These are set externally by the controller // bool overscanFlag = false; // bool biasFlag = false; // bool darkFlag = false; // bool flatoffFlag = false; // bool flatFlag = false; bool rescaleFlag = false; // Whether the images in this group have to be rescaled to the same mode when combining them (FLAT: yes, BIAS: no) // Memory functions // float memoryCurrentFootprint(bool globalweights = false); // float memoryNeeded(int chip); // void memoryFreeDataX(int chip, QString dataX); void memorySetDeletable(int chip, QString dataX, bool deletable); void getGainNormalization(); bool getPointingCharacteristics(); void initGlobalWeight(int chip, Data *flatData, QString filter, bool sameWeight, QString flatMin, QString flatMax); void resetGlobalWeight(QString filter); void thresholdGlobalWeight(int chip, const Data *comparisonData, const QString filter, const QString threshMin, const QString threshMax); void detectDefects(int chip, Data *flatData, const QString scienceFilter, const bool sameWeight, const QString defectKernel, const QString defectRowTol, const QString defectColTol, const QString defectClusTol); void writeGlobalWeights(int chip, QString filter); bool collectMJD(); // Reset functions for the taskInternal processes void resetProcessbackground(); void resetObjectMasking(); void populateExposureList(); void getModeCombineImages(int chip); QVector getKeyFromAllImages(const QString key); void checkPresenceOfMasterCalibs(); void reportModeCombineImages(); void countUnsavedImages(long &numUnsavedLatest, long &numUnsavedAll); // bool containsUnsavedImages(); void writeUnsavedImagesToDrive(bool includeBackup); void broadcastNumberOfFiles(); int identifyClusters(QString toleranceString); void setSuccess(bool state); void resetSuccessProcessing(); float releaseMemory(float RAMneededThisThread, float RAMneededAllThreads, float currentTotalmemoryUsed, QString mode = ""); void protectMemory(); void unprotectMemory(int chip); void releaseAllMemory(); void restoreBackupLevel(QString backupDirName); void transferBackupInfo(); void restoreFromDirectory(QString backupDirName); bool restoreFromBackupLevel(QString level, QString &newStatusRAM); void restoreRAWDATA(); bool checkStatusConsistency(); void emitStatusChanged(); bool hasMatchingPartnerFiles(QString testDirName, QString suffix, bool abort = true); bool checkTaskRepeatStatus(QString taskBasename); void resetStaticModel(); void writeBackgroundModel(const int &chip, const QString &mode, const QString &basename, bool &staticImageWritten); // void getModeCombineImagesBackground(int chip, MyImage *image); // void writeBackgroundModel_newParallel(int chip, MyImage *combinedBackgroundImage, QString mode, QString basename, // int threadID, omp_lock_t &backLock, bool &staticImageWritten); void cleanBackgroundModelStatus(); bool checkForRawData(); void applyMask(int chip, QString filter); void resetBackupInfo(); void removeCatalogs(); bool doesCoaddContainRaDec(const QString &refRA, const QString &refDEC); void unprotectMemoryForBackground(int chip); void checkModeIsPresent(); bool isEmpty(); public slots: void setMemoryLockReceived(bool locked); void setWCSLockReceived(bool locked); void modelUpdateReceiver(QString chipName); void pushMessageAvailable(QString message, QString type); void pushWarning(); void pushCritical(); void criticalFromQueryReceived(); // void pushErrorOccurred(); private: QString thelidir; QString userdir; bool workerInit = false; bool workerThreadInit = false; float maskVal = -1.e9; // void incrementCurrentThreads(int ¤tThreads, omp_lock_t &lock); // void decrementCurrentThreads(int ¤tThreads, omp_lock_t &lock); // void getFixedHeaderKeys(QString filename, QStringList &badImages); QVector getNormalizedRescaleFactors(int chip, QVector &goodIndex, QString mode); // void printCfitsioError(QString funcName, int status); void doImagesOverlap(const MyImage &imgRef, MyImage &imgTest, const float tolerance); bool checkForUnassignedImages(int &groupNumber); void findOverlappingImages(const MyImage *img, float tolerance); void releaseMemoryCombined(float &RAMfreed, const float RAMneededThisThread); void releaseMemoryIndividual(const QStringList &datalist, float &RAMfreed, const float RAMneededThisThread); void removeCurrentFITSfiles(); void releaseMemoryDebayer(float &RAMfreed, const float RAMneededThisThread); private slots: signals: void modelUpdateNeeded(QString chipName); // Passed through from MyImage: void messageAvailable(QString message, QString type); void showMessageBox(QString trigger, QString part1, QString part2); void appendOK(); void critical(); void warning(); void progressUpdate(float progress); void addToProgressBar(float differential); void resetProgressBar(); void setMemoryLock(bool locked); void setWCSLock(bool locked); void globalModelUpdateNeeded(); void updateModelHeaderLine(); void statusChanged(QString newStatus); void errorOccurredInMyImage(); }; #endif // DATA_H THELI-3.1.3/src/processingInternal/dictionaries.cc000066400000000000000000000550751417631501300220240ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include #include #include void Controller::populateHeaderDictionary() { // The mandatory THELI header keywords, and possible corresponding key names in the raw data of other instruments // headerDictionary.insert("CTYPE1", {"CTYPE1"}); // Forced, hence not read from headers // headerDictionary.insert("CTYPE2", {"CTYPE2"}); // Forced, hence not read from headers headerDictionary.insert("CRPIX1", {"CRPIX1", "J_CRPIX1"}); headerDictionary.insert("CRPIX2", {"CRPIX2", "J_CRPIX2"}); headerDictionary.insert("CD1_1", {"CD1_1", "J_CD1_1"}); headerDictionary.insert("CD1_2", {"CD1_2", "J_CD1_2"}); headerDictionary.insert("CD2_1", {"CD2_1", "J_CD2_1"}); headerDictionary.insert("CD2_2", {"CD2_2", "J_CD2_2"}); headerDictionary.insert("CDELT1", {"CDELT1"}); headerDictionary.insert("CDELT2", {"CDELT2"}); headerDictionary.insert("CRVAL1", {"CRVAL1", "RA", "OBJCTRA", "MEANRA", "OBSRA", "CRVAL1A", "RA-D", "RA_DEG", "RA-HOURS", "RASTRNG", "TELRA"}); headerDictionary.insert("CRVAL2", {"CRVAL2", "DEC", "OBJCTDEC", "MEANDEC", "OBSDEC", "CRVAL2A", "DEC-D", "DEC_DEG", "DECSTRNG", "TELDEC"}); headerDictionary.insert("RADESYS", {"RADESYS", "RADECSYS"}); headerDictionary.insert("OBJECT", {"OBJECT", "QUEUEID", "TARGET", "TARGNAME"}); headerDictionary.insert("AIRMASS", {"AIRMASS", "AMSTART", "HIERARCH ESO TEL AIRM START", "SECZ", "FZ_MP", "TELAM"}); headerDictionary.insert("EXPTIME", {"EXPTIME", "EXPOSURE", "EXPOS", "EXPOSED", "EXP_TIME", "TTIME"}); headerDictionary.insert("EQUINOX", {"EQUINOX", "EPOCH", "RADECEQ", "TELEP"}); headerDictionary.insert("DATE-OBS", {"DATE-OBS", "DATEOBS", "DATE_OBS", "DATE_BEG", "DATE", "UTSHUT", "TIME"}); headerDictionary.insert("MJD-OBS", {"MJD-OBS", "MJD_OBS"}); headerDictionary.insert("NAMPS", {"NAMPS"}); headerDictionary.insert("GAIN", {"EGAIN", "GAIN", "HIERARCH ESO DET CHIP GAIN", "HIERARCH ESO DET OUT1 CONAD", "HIERARCH ESO DET OUT-1 ADU"}); // careful with gain and inverse gain! headerDictionary.insert("FILTER", {"FILTER", "FILTER1", "FILTER2", "FILTER3", "FILTER01", "FILTER02", "FILTER03", "FILTERID", "FILT1", "FILT2", "FILTERS", "FILTNAME", "SUBSET", "HIERARCH ESO INS FILT1 NAME", "HIERARCH ESO INS FILT2 NAME", "HIERARCH ESO INS FILT3 NAME", "HIERARCH ESO INS FILT4 NAME", "HIERARCH ESO INS OPTI-2 NAME", "AFT", "ALFLTNM", "FAFLTNM", "FBFLTNM", "FILTRE", "FLTRNAME", "PFMFNAME", "WFFBAND", "ACAMFSLI", "ACAMWH1", "ACAMWH2", "INGF1NAM", "INGF2NAM", "LIRF1NAM", "LIRF2NAM", "NCFLTNM1", "NCFLTNM2"}); // Other keywords of interest (to calculate others, or preserve information) headerDictionary.insert("INSTRUME", {"INSTRUME", "DETECTOR"}); headerDictionary.insert("PC1_1", {"PC1_1"}); headerDictionary.insert("PC1_2", {"PC1_2"}); headerDictionary.insert("PC2_1", {"PC2_1"}); headerDictionary.insert("PC2_2", {"PC2_2"}); headerDictionary.insert("DATE", {"DATE", "DATE-OBS", "DATEOBS", "UT-DATE"}); headerDictionary.insert("TIME", {"EXPSTART", "TIME", "TIME-OBS", "UT", "UT-TIME", "UTSTART", "UT-STR", "TELUT"}); headerDictionary.insert("LST", {"LST", "LST-OBS", "LSTHDR", "LST_OBS", "OBS-LST", "SD_TIME", "ST"}); headerDictionary.insert("DIT", {"EXP1TIME", "EXPCOADD", "EXPTIME", "HIERARCH ESO DET DIT", "ITIME", "K_DETEP1", "TRUITIME", "DIT"}); headerDictionary.insert("NDIT", {"COADD", "COADDONE", "COADDS", "COAVERAG", "HIERARCH ESO DET NDIT", "NCOADD", "NDIT"}); // headerDictionary.insert("IMAGEID", {}); // headerDictionary.insert("GABODSID", {}); // headerDictionary.insert("ZP", {}); // headerDictionary.insert("COEFF", {}); /* * ABOUT GAIN: * FourStar has a GAIN keyword, but the correct one is EGAIN" */ } // Used to replace long filter names by short ones void Controller::populateFilterDictionary() { // FLAMINGOS2 filterDictionary.insert("DK_G0807+J_G0802", "DARK"); filterDictionary.insert("DK_G0807", "DARK"); filterDictionary.insert("J_G0802", "J"); filterDictionary.insert("H_G0803", "H"); filterDictionary.insert("Ks_G0804", "Ks"); filterDictionary.insert("Y_G0811", "Y"); filterDictionary.insert("J-lo_G0801", "Jlo"); filterDictionary.insert("JH_G0809", "JH"); filterDictionary.insert("HK_G0806_good", "HK"); // GSAOI filterDictionary.insert("Blocked1_G1114", "DARK"); filterDictionary.insert("Blocked2_G1128", "DARK"); filterDictionary.insert("Z_G1101", "Z"); filterDictionary.insert("J_G1102", "J"); filterDictionary.insert("H_G1103", "H"); filterDictionary.insert("Kprime_G1104", "Kp"); filterDictionary.insert("Kshort_G1105", "Ks"); filterDictionary.insert("K_G1106", "K"); filterDictionary.insert("Jcont_G1107", "Jc"); filterDictionary.insert("Hcont_G1108", "Hc"); filterDictionary.insert("CH4short_G1109", "CH4s"); filterDictionary.insert("CH4long_G1110", "CH4l"); filterDictionary.insert("Kcntshrt_G1111", "Kcs"); filterDictionary.insert("Kcntlong_G1112", "Kcl"); filterDictionary.insert("HeI1083_G1115", "HeI"); filterDictionary.insert("PaG_G1116", "PaG"); filterDictionary.insert("PaB_G1117", "PaB"); filterDictionary.insert("FeII_G1118", "FeII"); filterDictionary.insert("H2(1-0)_G1121", "H210"); filterDictionary.insert("BrG_G1122", "BrG"); filterDictionary.insert("H2(2-1)_G1123", "H221"); filterDictionary.insert("CO2360_G1124", "CO2360"); // NIRI filterDictionary.insert("H_G0203", "H"); filterDictionary.insert("J_G0202", "J"); filterDictionary.insert("Kshort_G0205", "Ks"); filterDictionary.insert("Y_G0241", "Y"); filterDictionary.insert("Lprime_G0207", "Lp"); // MOIRCS filterDictionary.insert("J_SUB", "J"); // GROND_OPT filterDictionary.insert("grond_g", "g"); filterDictionary.insert("grond_r", "r"); filterDictionary.insert("grond_i", "i"); filterDictionary.insert("grond_z", "z"); // MOSCA@NOT filterDictionary.insert("U_Bes361_62", "U"); filterDictionary.insert("B_Bes428_108", "B"); filterDictionary.insert("V_Bes536_89", "V"); filterDictionary.insert("R_Bes646_124", "R"); filterDictionary.insert("I_int817_163", "I"); filterDictionary.insert("u_SDSS353_55", "u"); filterDictionary.insert("g_SDSS480_145", "g"); filterDictionary.insert("r_SDSS618_148", "r"); filterDictionary.insert("i_SDSS771_171", "i"); filterDictionary.insert("z_SDSS832_LP", "z"); // WFI@MPGESO filterDictionary.insert("BBB99_ESO842", "B"); filterDictionary.insert("BBV89_ESO843", "V"); filterDictionary.insert("BBRc162_ESO844", "Rc"); filterDictionary.insert("BBB/123_ESO878", "Bnew"); filterDictionary.insert("BBI/203_ESO879", "I"); filterDictionary.insert("BBIclwp_ESO845", "Ic"); filterDictionary.insert("BBIcIwp_ESO845", "Ic"); filterDictionary.insert("BBU38_ESO841", "U38"); filterDictionary.insert("BBU50_ESO877", "U50"); // IMACS filterDictionary.insert("Sloan_u", "u"); filterDictionary.insert("Sloan_g", "g"); filterDictionary.insert("Sloan_r", "r"); filterDictionary.insert("Sloan_i", "i"); filterDictionary.insert("Sloan_z", "z"); // MOSAIC-III filterDictionary.insert("Usparek1029", "U"); filterDictionary.insert("Uk1001", "U"); filterDictionary.insert("BHarrisk1002", "B"); filterDictionary.insert("VHarrisk1003", "V"); filterDictionary.insert("RHarrisk1004", "R"); filterDictionary.insert("INearly-Mouldk1005", "I"); filterDictionary.insert("CWashingtonk1006", "C"); filterDictionary.insert("MWashingtonk1007", "M"); filterDictionary.insert("haH-alphak1009", "Ha"); filterDictionary.insert("ha4H-alpha+4nmk1010", "Ha+4"); filterDictionary.insert("ha8H-alpha+8nmk1011", "Ha+8"); filterDictionary.insert("ha12H-alpha+12nmk1012", "Ha+12"); filterDictionary.insert("ha16H-alpha+16nmk1013", "SII"); filterDictionary.insert("O3OIIIN2k1014", "OIII"); filterDictionary.insert("OoffOIII+30nmk1015", "OIII+30"); filterDictionary.insert("gSDSSk1017", "g"); filterDictionary.insert("rSDSSk1018", "r"); filterDictionary.insert("iSDSSk1019", "i"); filterDictionary.insert("zSDSSk1020", "z"); filterDictionary.insert("OoffOIII+30nmk1030", "OIII+30"); filterDictionary.insert("OoffOIII+30nmk1031", "OIII+30"); filterDictionary.insert("gdDECcamk1035", "gd"); filterDictionary.insert("rdDECcamk1036", "rd"); filterDictionary.insert("zdDECcamk1038", "zd"); filterDictionary.insert("VRk1039", "VR"); filterDictionary.insert("UnSteidelk1041", "U"); filterDictionary.insert("GnSteidelk1042", "B"); filterDictionary.insert("RsSteidelk1043", "R"); filterDictionary.insert("UssolidUk1044", "U"); filterDictionary.insert("UdDeyk1045", "U"); filterDictionary.insert("815815_v2k1046", "820B"); filterDictionary.insert("823823_v2k1047", "820R"); filterDictionary.insert("337BATCk1051", "337_BATC"); filterDictionary.insert("390BATCk1052", "390_BATC"); filterDictionary.insert("420BATCk1053", "420_BATC"); filterDictionary.insert("454BATCk1054", "454_BATC"); filterDictionary.insert("493BATCk1055", "493_BATC"); filterDictionary.insert("527BATCk1056", "527_BATC"); filterDictionary.insert("579BATCk1057", "579_BATC"); filterDictionary.insert("607BATCk1058", "607_BATC"); filterDictionary.insert("666BATCk1059", "666_BATC"); filterDictionary.insert("705BATCk1060", "705_BATC"); filterDictionary.insert("755BATCk1061", "755_BATC"); filterDictionary.insert("802BATCk1062", "802_BATC"); filterDictionary.insert("848BATCk1063", "848_BATC"); filterDictionary.insert("918BATCk1064", "918_BATC"); filterDictionary.insert("973BATCk1065", "973_BATC"); // SAMI filterDictionary.insert("s0012rSDSS+s0012", "r"); // MEGACAM@LCO filterDictionary.insert("u,gblk", "u"); filterDictionary.insert("g,gblk", "g"); filterDictionary.insert("r,gblk", "r"); filterDictionary.insert("i,gblk", "i"); filterDictionary.insert("z,gblk", "z"); filterDictionary.insert("gblk,u", "u"); filterDictionary.insert("gblk,g", "g"); filterDictionary.insert("gblk,r", "r"); filterDictionary.insert("gblk,i", "i"); filterDictionary.insert("gblk,z", "z"); // GMOS filterDictionary.insert("u_G0308", "u"); filterDictionary.insert("u_G0332", "u"); filterDictionary.insert("g_G0301", "g"); filterDictionary.insert("g_G0325", "g"); filterDictionary.insert("r_G0303", "r"); filterDictionary.insert("r_G0326", "r"); filterDictionary.insert("i_G0302", "i"); filterDictionary.insert("i_G0327", "i"); filterDictionary.insert("z_G0304", "z"); filterDictionary.insert("z_G0328", "z"); filterDictionary.insert("Ha_G0336", "Ha"); filterDictionary.insert("Ha_G0310", "Ha"); filterDictionary.insert("HaC_G0337", "HaC"); filterDictionary.insert("HaC_G0311", "HaC"); filterDictionary.insert("SII_G0335", "SII"); filterDictionary.insert("SII_G0317", "SII"); filterDictionary.insert("OIII_G0338", "OIII"); filterDictionary.insert("OIII_G0318", "OIII"); filterDictionary.insert("OIIIC_G0339", "OIIIC"); filterDictionary.insert("OIIIC_G0319", "OIIIC"); filterDictionary.insert("OVI_G0345", "OVI"); filterDictionary.insert("OVI_G0347", "OVI"); filterDictionary.insert("OVIC_G0346", "OVIC"); filterDictionary.insert("OVIC_G0348", "OVIC"); filterDictionary.insert("HeII_G0320", "HeII"); filterDictionary.insert("HeII_G0340", "HeII"); filterDictionary.insert("HeIIC_G0321", "HeIIC"); filterDictionary.insert("HeIIC_G0341", "HeIIC"); // LDSS3 filterDictionary.insert("g_Sloan", "g"); filterDictionary.insert("r_Sloan", "r"); filterDictionary.insert("i_Sloan", "i"); filterDictionary.insert("z_Sloan", "z"); // HSC filterDictionary.insert("HSC-g", "g"); filterDictionary.insert("HSC-r", "r"); filterDictionary.insert("HSC-i", "i"); filterDictionary.insert("HSC-z", "z"); filterDictionary.insert("HSC-r2", "r"); filterDictionary.insert("HSC-i2", "i"); filterDictionary.insert("HSC-Y", "Y"); // filterDictionary.insert(, ); } void Controller::populateInstrumentDictionary() { instrumentDictionary.insert("ACAM@WHT", "ACAM"); instrumentDictionary.insert("ACS@HST", ""); instrumentDictionary.insert("ALFOSC@NOT", ""); instrumentDictionary.insert("ALTAU16M@VYSOS06", ""); instrumentDictionary.insert("AltaU42_HIGHRES@ASV", ""); instrumentDictionary.insert("AltaU42_LOWRES@ASV", ""); instrumentDictionary.insert("ApogeeAlta@PROMPT4", ""); instrumentDictionary.insert("ApogeeAlta@PROMPT5", ""); instrumentDictionary.insert("CFH12K@CFHT", ""); instrumentDictionary.insert("CFH12K@CFHT99", ""); instrumentDictionary.insert("DECam@CTIO", ""); instrumentDictionary.insert("DEIMOS_1AMP@KECK", "DEIMOS"); instrumentDictionary.insert("DEIMOS_2AMP@KECK", "DEIMOS"); instrumentDictionary.insert("Direct_4k_SWOPE@LCO", "Direct_4Kx4K-4"); // must replace a '/' in the INSTRUME keyword with '_ instrumentDictionary.insert("Direct_2k_DUPONT@LCO", "Direct_SITe2K-1"); // must replace a '/' in the INSTRUME keyword with '_' instrumentDictionary.insert("EFOSC2@ESO3.6m", "EFOSC"); instrumentDictionary.insert("EFOSC2@NTT", "EFOSC"); instrumentDictionary.insert("EFOSC2_2x2@ESO3.6m", "EFOSC"); instrumentDictionary.insert("EFOSC2_2x2@NTT", "EFOSC"); instrumentDictionary.insert("EMIR@GTC", ""); instrumentDictionary.insert("EMMI_BIMG@NTT", ""); instrumentDictionary.insert("EMMI_RILD@NTT", ""); instrumentDictionary.insert("ENZIAN_CAS@HOLI_1M", ""); instrumentDictionary.insert("ESI@KECK", "ESI"); instrumentDictionary.insert("FL03_LCOGT@CTIO", ""); instrumentDictionary.insert("FL04_LCOGT@CTIO", ""); instrumentDictionary.insert("FLAMINGOS2@GEMINI", "F2"); instrumentDictionary.insert("FLI-PL16801@WISE", ""); instrumentDictionary.insert("FORS1_199904-200703@VLT", "FORS1"); instrumentDictionary.insert("FORS1_E2V_2x2@VLT", "FORS1"); instrumentDictionary.insert("FORS2_200004-200203@VLT", "FORS2"); instrumentDictionary.insert("FORS2_E2V_2x2@VLT", "FORS2"); instrumentDictionary.insert("FORS2_MIT_1x1@VLT", "FORS2"); instrumentDictionary.insert("FORS2_MIT_2x2@VLT", "FORS2"); instrumentDictionary.insert("FourStar@LCO", "FourStar"); instrumentDictionary.insert("FourStar_Chips1+4@LCO", "FourStar"); instrumentDictionary.insert("GMOS-N-EEV-3ports@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-N-EEV-6ports@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-N-HAM@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-N-HAM_1x1@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-S-EEV@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S-HAM@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S-HAM_1x1@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S-HAM_4x4@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S_EEV_GeMS@GEMINI", "GMOS-S"); instrumentDictionary.insert("GOODMAN_1x1@SOAR", ""); instrumentDictionary.insert("GOODMAN_2x2@SOAR", ""); instrumentDictionary.insert("GPC1@PS1", ""); instrumentDictionary.insert("GROND_NIR@MPGESO", "GROND"); instrumentDictionary.insert("GROND_OPT@MPGESO", "GROND"); instrumentDictionary.insert("GSAOI@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_1k@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP1@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP2@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP3@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP4@GEMINI", "GSAOI"); instrumentDictionary.insert("HAWKI@VLT", "HAWKI"); instrumentDictionary.insert("HDI@KPNO_0.9m", "hdi"); instrumentDictionary.insert("HSC@SUBARU", "Hyper Suprime-Cam"); instrumentDictionary.insert("IMACS_F2_NEW@LCO", "IMACS Short-Camera"); instrumentDictionary.insert("IMACS_F2_OLD@LCO", ""); instrumentDictionary.insert("IMACS_F4_NEW@LCO", "IMACS Long-Camera"); instrumentDictionary.insert("IMACS_F4_NEW_2x2@LCO", "IMACS Long-Camera"); instrumentDictionary.insert("IMACS_F4_OLD@LCO", ""); instrumentDictionary.insert("INGRID@WHT", ""); instrumentDictionary.insert("IRCS_HIGHRES@SUBARU", ""); instrumentDictionary.insert("IRCS_LOWRES@SUBARU", ""); instrumentDictionary.insert("ISAAC@VLT", ""); instrumentDictionary.insert("ISPI@CTIO", ""); instrumentDictionary.insert("KTMC@CTIO", ""); instrumentDictionary.insert("LAICA@CAHA", ""); instrumentDictionary.insert("LAICA_2x2@CAHA", ""); instrumentDictionary.insert("LBC_BLUE@LBT", ""); instrumentDictionary.insert("LBC_RED@LBT", ""); instrumentDictionary.insert("LDSS3_from201402@LCO", "LDSS3-C"); instrumentDictionary.insert("LDSS3_2004-201401@LCO", ""); instrumentDictionary.insert("LIRIS@WHT", "LIRIS"); instrumentDictionary.insert("LIRIS_POL@WHT", "LIRIS"); instrumentDictionary.insert("LORRI@NewHorizons", ""); instrumentDictionary.insert("LRIS_BLUE@KECK", "LRISBLUE"); instrumentDictionary.insert("LRIS_RED@KECK", "LRIS"); instrumentDictionary.insert("MEGACAM_2x2@LCO", "megacam"); instrumentDictionary.insert("MEGAPRIME@CFHT", ""); instrumentDictionary.insert("MEGAPRIME_ELIXIR@CFHT", ""); instrumentDictionary.insert("MEROPE@MERCATOR", ""); instrumentDictionary.insert("MMIRS@LCO", ""); instrumentDictionary.insert("MOIRCS_200406-200806@SUBARU", "MOIRCS"); instrumentDictionary.insert("MOIRCS_200807-201505@SUBARU", "MOIRCS"); instrumentDictionary.insert("MOIRCS_201512-today@SUBARU", "MOIRCS"); instrumentDictionary.insert("MOSAIC-III_4@KPNO_4m", "Mosaic3"); instrumentDictionary.insert("MOSAIC-III@KPNO_4m", "Mosaic3"); instrumentDictionary.insert("MOSAIC-II_15@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_16@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_16_old@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_8@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_8_2x2@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-I_old@KPNO_0.9m", ""); instrumentDictionary.insert("MOSAIC-I_old@KPNO_4.0m", ""); instrumentDictionary.insert("MOSCA_2x2@NOT", "MOSAIC 4*2kx2k"); instrumentDictionary.insert("MOSFIRE@KECK", ""); instrumentDictionary.insert("NACO@VLT", "NAOS+CONICA"); instrumentDictionary.insert("NACOSDI@VLT", ""); instrumentDictionary.insert("NEWFIRM@CTIO", "NEWFIRM"); instrumentDictionary.insert("NEWFIRM@KPNO_4m", "NEWFIRM"); instrumentDictionary.insert("NICI@GEMINI", ""); instrumentDictionary.insert("NICS@TNG", ""); instrumentDictionary.insert("NIRC2@KECK", ""); instrumentDictionary.insert("NIRI@GEMINI", "NIRI"); instrumentDictionary.insert("NOTcam_highres@NOT", ""); instrumentDictionary.insert("NOTcam_lowres@NOT", ""); instrumentDictionary.insert("OASIS4x4@WHT", ""); instrumentDictionary.insert("OASIS@WHT", ""); instrumentDictionary.insert("OMEGACAM@VST", "OMEGACAM"); instrumentDictionary.insert("OSIRIS@GTC", ""); instrumentDictionary.insert("OSIRIS_F3@SOAR", ""); instrumentDictionary.insert("OSIRIS_F7@SOAR", ""); instrumentDictionary.insert("Omega2000@CAHA", ""); instrumentDictionary.insert("PANIC@LCO", ""); instrumentDictionary.insert("PANIC_OLD_4det@CAHA2.2", ""); instrumentDictionary.insert("PAUCam@WHT", ""); instrumentDictionary.insert("PFC_new@WHT", ""); instrumentDictionary.insert("PFC_old@WHT", "Prime Imaging"); instrumentDictionary.insert("PF_QHY2x2", "QHY CCD QHY600M-929ba64"); instrumentDictionary.insert("PICCD@WISE", ""); instrumentDictionary.insert("PISCES@LBT", ""); instrumentDictionary.insert("PISCO@LCO", "PISCO"); instrumentDictionary.insert("RetroCam_SWOPE@LCO", "RetroCam"); instrumentDictionary.insert("RetroCam_DUPONT@LCO", "RetroCam"); instrumentDictionary.insert("SAMI_2x2@SOAR", "SAM"); instrumentDictionary.insert("SDSS", ""); instrumentDictionary.insert("SITe@TLS", ""); instrumentDictionary.insert("SOFI@NTT", ""); instrumentDictionary.insert("SOI@SOAR", "SOI"); instrumentDictionary.insert("SPARTAN@SOAR", ""); instrumentDictionary.insert("SUSI1@NTT", "SUSI"); instrumentDictionary.insert("SUSI2_2x2@NTT", ""); instrumentDictionary.insert("SUSI2old_2x2@NTT", ""); instrumentDictionary.insert("SWOPE@LCO", ""); instrumentDictionary.insert("SuprimeCam_200101-200104@SUBARU", "SuprimeCam"); instrumentDictionary.insert("SuprimeCam_200105-200807@SUBARU", "SuprimeCam"); instrumentDictionary.insert("SuprimeCam_200808-201705@SUBARU", "SuprimeCam"); instrumentDictionary.insert("SuprimeCam_200808-201705_SDFRED@SUBARU", "SuprimeCam"); instrumentDictionary.insert("TRECS@GEMINI", "TReCS"); instrumentDictionary.insert("TRIPOL_1x1@SAAO", ""); instrumentDictionary.insert("TRIPOL_2x2@SAAO", ""); instrumentDictionary.insert("Tek2K@CTIO", ""); instrumentDictionary.insert("VIMOS@VLT", "VIMOS"); instrumentDictionary.insert("VIRCAM@VISTA", ""); instrumentDictionary.insert("VISIR@VLT", ""); instrumentDictionary.insert("WFC@INT", "WFC"); instrumentDictionary.insert("WFC_2x2@INT", "WFC"); instrumentDictionary.insert("WFC_IPHAS@INT", "WFC"); instrumentDictionary.insert("WFCCD_WF4K_DUPONT", "WFCCD_WF4K-1"); instrumentDictionary.insert("WFI@AAT", ""); instrumentDictionary.insert("WFI@MPGESO", "WFI"); instrumentDictionary.insert("WFI@SSO_40inch", ""); instrumentDictionary.insert("WFI_2x2_2006@MPGESO", ""); instrumentDictionary.insert("WFI_2x2_2017@MPGESO", ""); instrumentDictionary.insert("WHIRC@WIYN", "WHIRC"); instrumentDictionary.insert("WIRC@Hale", ""); instrumentDictionary.insert("WIRCam@CFHT", ""); instrumentDictionary.insert("Y4KCam@CTIO", ""); // instrumentDictionary.insert(); } THELI-3.1.3/src/processingInternal/displayconfig.cc000066400000000000000000000464201417631501300221740ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "../dockwidgets/confdockwidget.h" #include "../dockwidgets/monitor.h" #include "ui_confdockwidget.h" #include void Controller::populateCommentMap() { commentMap.clear(); commentMap.insert("HDUreformat", "HDU reformatting"); commentMap.insert("Processbias", "Processing biases in"); commentMap.insert("Processdark", "Processing darks in"); commentMap.insert("Processflatoff", "Processing flat off/darks in"); commentMap.insert("Processflat", "Processing flats in"); commentMap.insert("Processscience", "Debiasing and flatfielding data in"); commentMap.insert("Chopnod", "Doing chopnod background correction for"); commentMap.insert("Background", "Applying background model to"); commentMap.insert("Collapse", "Applying collapse correction to"); commentMap.insert("Binnedpreview", "Creating binned previews for"); commentMap.insert("Globalweight", "Creating global weights for"); commentMap.insert("Individualweight", "Creating individual weights for"); commentMap.insert("Separate", "Separating different targes in"); commentMap.insert("Absphotindirect", "Performing indirect absolute photometry"); commentMap.insert("Createsourcecat", "Creating source catalogs for"); commentMap.insert("GetCatalogFromWEB", "Downloading astrometric reference catalog for"); commentMap.insert("GetCatalogFromIMAGE", "Extracting astrometric reference catalog for"); commentMap.insert("Astromphotom", "Calculating astrometric solution for"); commentMap.insert("Resolvetarget", "Resolving target coordinates for"); commentMap.insert("RestoreHeader", "Restoring original astrometry in images for"); commentMap.insert("CopyZeroOrder", "Updating images with 0th order WCS solution for"); commentMap.insert("ImageQuality", "Analyzing image quality for"); commentMap.insert("SkysubModel", "Subtracting the sky for"); commentMap.insert("SkysubConst", "Subtracting the sky for"); commentMap.insert("SkysubPoly", "Subtracting the sky for"); commentMap.insert("Coaddition", "Performing coaddition for"); commentMap.insert("CoaddSmoothWeights", "Smoothing edges in weight maps for"); commentMap.insert("CoaddPrepare", "Preparing coaddition for"); commentMap.insert("CoaddResample", "Resampling images for"); commentMap.insert("CoaddSwarpFilter", "Outlier filtering for"); commentMap.insert("CoaddCoadd", "Coaddition images for"); commentMap.insert("CoaddUpdate", "Updating header of coadd.fits for"); } void Controller::pushConfigHDUreformat() { QString config; config = ""; config += "Overscan correction = "+ boolToString(cdw->ui->overscanCheckBox->isChecked()) + "
"; config += "Overscan method = "+ cdw->ui->overscanMethodComboBox->currentText() + "
"; config += "Nonlinearity correction = "+ boolToString(cdw->ui->nonlinearityCheckBox->isChecked()) + "
"; config += "Point crosstalk correction = "+ boolToString(cdw->ui->normalxtalkCheckBox->isChecked()) + "
"; config += "Point crosstalk amplitude = "+ cdw->ui->normalxtalkAmplitudeLineEdit->text() + "
"; config += "Row crosstalk correction = "+ boolToString(cdw->ui->rowxtalkCheckBox->isChecked()) + "
"; config += "Row crosstalk amplitude = "+ cdw->ui->rowxtalkAmplitudeLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessbias() { QString config; config = ""; config += "Number of low rejected pixels / stack = " + cdw->ui->biasNlowLineEdit->text() + "
"; config += "Number of high rejected pixels / stack = " + cdw->ui->biasNhighLineEdit->text() + "
"; config += "Min mode allowed [e-] = " + cdw->ui->biasMinLineEdit->text() + "
"; config += "Max mode allowed [e-] = " + cdw->ui->biasMaxLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessdark() { QString config; config = ""; config += "Number of low rejected pixels / stack = " + cdw->ui->darkNlowLineEdit->text() + "
"; config += "Number of high rejected pixels / stack = " + cdw->ui->darkNhighLineEdit->text() + "
"; config += "Min mode allowed [e-] = " + cdw->ui->darkMinLineEdit->text() + "
"; config += "Max mode allowed [e-] = " + cdw->ui->darkMaxLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessflat() { QString config; QString note1 = ""; QString note2 = ""; if (!cdw->ui->flatMinLineEdit->text().isEmpty()) note1 = " (NOTE: before DARK / FLATOFF subtraction!)"; if (!cdw->ui->flatMaxLineEdit->text().isEmpty()) note2 = " (NOTE: before DARK / FLATOFF subtraction!)"; config = ""; config += "Number of low rejected pixels / stack = " + cdw->ui->flatNlowLineEdit->text() + "
"; config += "Number of high rejected pixels / stack = " + cdw->ui->flatNhighLineEdit->text() + "
"; config += "Min mode allowed [e-] = " + cdw->ui->flatMinLineEdit->text() + note1 + "
"; config += "Max mode allowed [e-] = " + cdw->ui->flatMaxLineEdit->text() + note2 + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessflatoff() { QString config; config = ""; config += "Number of low rejected pixels / stack = " + cdw->ui->flatoffNlowLineEdit->text() + "
"; config += "Number of high rejected pixels / stack = " + cdw->ui->flatoffNhighLineEdit->text() + "
"; config += "Min mode allowed [e-] = " + cdw->ui->flatoffMinLineEdit->text() + "
"; config += "Max mode allowed [e-] = " + cdw->ui->flatoffMaxLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigBackground() { QString mode = " (STATIC)"; if (cdw->ui->BACwindowLineEdit->text() != "0") mode = " (DYNAMIC)"; QString config; config = ""; config += "Detection threshold (DT) = " + cdw->ui->BACDTLineEdit->text() + "
"; config += "Detection min area (DMIN) = " + cdw->ui->BACDMINLineEdit->text() + "
"; config += "Two-pass background model = " + boolToString(cdw->ui->BAC2passCheckBox->isChecked()) + "
"; config += "Convolve detections before masking = " + boolToString(cdw->ui->BACconvolutionCheckBox->isChecked()) + "
"; config += "Mask expansion factor = " + cdw->ui->BACmefLineEdit->text() + "
"; config += "Combination method = " + cdw->ui->BACmethodComboBox->currentText() + "
"; config += "Number of low rejected pixels (1st pass) = " + cdw->ui->BAC1nlowLineEdit->text() + "
"; config += "Number of high rejected pixels (1st pass) = " + cdw->ui->BAC1nhighLineEdit->text() + "
"; config += "Number of low rejected pixels (2nd pass) = " + cdw->ui->BAC2nlowLineEdit->text() + "
"; config += "Number of high rejected pixels (2nd pass) = " + cdw->ui->BAC2nhighLineEdit->text() + "
"; config += "Reject detectors with stars brighter than [mag] = " + cdw->ui->BACmagLineEdit->text() + "
"; config += "Minimum distance from detector edge ['] = " + cdw->ui->BACdistLineEdit->text() + "
"; config += "Correction method = " + cdw->ui->BACapplyComboBox->currentText() + "
"; config += "Model smoothing kernel width [pixel] = " + cdw->ui->BACbacksmoothscaleLineEdit->text() + "
"; config += "Rescale model to individual exposure = " + boolToString(cdw->ui->BACrescaleCheckBox->isChecked()) + "
"; config += "Window size = " + cdw->ui->BACwindowLineEdit->text() + mode + "
"; config += "Min useful window size = " + cdw->ui->BACminWindowLineEdit->text() + "
"; config += "Max gap size [hour] = " + cdw->ui->BACgapsizeLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigCollapse() { QString config; config = ""; config += "Detection threshold (DT) = " + cdw->ui->COCDTLineEdit->text() + "
"; config += "Detection min area (DMIN) = " + cdw->ui->COCDMINLineEdit->text() + "
"; config += "Mask expansion factor = " + cdw->ui->COCmefLineEdit->text() + "
"; config += "Rejection threshold [sigma] = " + cdw->ui->COCrejectLineEdit->text() + "
"; config += "Collapse direction = " + cdw->ui->COCdirectionComboBox->currentText() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigBinnedpreview() { QString config; config = ""; config += "Binning factor = " + cdw->ui->BIPSpinBox->text() + "
"; config += "Reject outliers = " + boolToString(cdw->ui->BIPrejectCheckBox->isChecked()) + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigGlobalweight() { QString config; config = ""; config += "Same weight for all pixels = " + boolToString(cdw->ui->CGWsameweightCheckBox->isChecked()) + "
"; config += "Min value allowed for BIAS / DARK [e-] = " + cdw->ui->CGWdarkminLineEdit->text() + "
"; config += "Max value allowed for BIAS / DARK [e-] = " + cdw->ui->CGWdarkmaxLineEdit->text() + "
"; config += "Min value allowed for norm. FLAT [e-] = " + cdw->ui->CGWflatminLineEdit->text() + "
"; config += "Max value allowed for norm. FLAT [e-] = " + cdw->ui->CGWflatmaxLineEdit->text() + "
"; config += "Min value allowed for background model [e-] = " + cdw->ui->CGWbackminLineEdit->text() + "
"; config += "Max value allowed for background model [e-] = " + cdw->ui->CGWbackmaxLineEdit->text() + "
"; config += "Defect detection in FLAT: Kernel size = " + cdw->ui->CGWflatsmoothLineEdit->text() + "
"; config += "Defect detection in FLAT: Row tolerance = " + cdw->ui->CGWflatrowtolLineEdit->text() + "
"; config += "Defect detection in FLAT: Column tolerance = " + cdw->ui->CGWflatcoltolLineEdit->text() + "
"; config += "Defect detection in FLAT: Cluster tolerance = " + cdw->ui->CGWflatclustolLineEdit->text() + "
"; config += "Defect detection in BACK: Kernel size for = " + cdw->ui->CGWbacksmoothLineEdit->text() + "
"; config += "Defect detection in BACK: Row tolerance = " + cdw->ui->CGWbackrowtolLineEdit->text() + "
"; config += "Defect detection in BACK: Column tolerance = " + cdw->ui->CGWbackcoltolLineEdit->text() + "
"; config += "Defect detection in BACK: Cluster tolerance = " + cdw->ui->CGWbackclustolLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigIndividualweight() { QString config; config = ""; config += "Min value allowed in image [e-] = " + cdw->ui->CIWminaduLineEdit->text() + "
"; config += "Max value allowed in image [e-] = " + cdw->ui->CIWmaxaduLineEdit->text() + "
"; config += "Detection aggressiveness for cosmics = " + cdw->ui->CIWaggressivenessLineEdit->text() + "
"; config += "Mask blooming spikes = " + boolToString(cdw->ui->CIWmaskbloomingCheckBox->isChecked()) + "
"; config += "Blooming spike min value [e-] = " + cdw->ui->CIWbloomMinaduLineEdit->text() + "
"; config += "Blooming spike dynamic range [e-] = " + cdw->ui->CIWbloomRangeLineEdit->text() + "
"; config += "Mask persistent pixels = " + boolToString(cdw->ui->CIWpersistenceCheckBox->isChecked()) + "
"; config += "Maximum lookback time [min] = " + cdw->ui->CIWpersistenceTimescaleLineEdit->text() + "
"; config += "Persistence trigger level [e-] = " + cdw->ui->CIWpersistenceMinaduLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigCreatesourcecat() { QString config; config = ""; config += "Detection threshold (DT) = " + cdw->ui->CSCDTLineEdit->text() + "
"; config += "Detection min area (DMIN) = " + cdw->ui->CSCDMINLineEdit->text() + "
"; config += "DEBLEND = " + cdw->ui->CSCmincontLineEdit->text() + "
"; config += "Minimum FWHM [pixel] = " + cdw->ui->CSCFWHMLineEdit->text() + "
"; config += "Convolve detections = " + boolToString(cdw->ui->CSCconvolutionCheckBox->isChecked()) + "
"; config += "Max FLAG = " + cdw->ui->CSCmaxflagLineEdit->text() + "
"; config += "Saturation [e-] = " + cdw->ui->CSCsaturationLineEdit->text() + "
"; config += "Background level [e-] = " + cdw->ui->CSCbackgroundLineEdit->text() + "
"; config += "Many hot pixels = " + boolToString(cdw->ui->CSCsamplingCheckBox->isChecked()) + "
"; config += "Min # of objects per detector = " + cdw->ui->CSCrejectExposureLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigGetCatalogFromWeb() { QString config; QString pm; QString ra = cdw->ui->ARCraLineEdit->text(); QString dec = cdw->ui->ARCdecLineEdit->text(); QString mag = cdw->ui->ARCminmagLineEdit->text(); QString rad = cdw->ui->ARCradiusLineEdit->text(); if (cdw->ui->ARCmaxpmLineEdit->text().isEmpty()) pm = "unconstrained"; if (ra.isEmpty()) ra = "automatic"; if (dec.isEmpty()) dec = "automatic"; if (mag.isEmpty()) mag = "unconstrained"; if (rad.isEmpty()) rad = "automatic"; else rad.append("'"); config = ""; config += "Catalog = " + cdw->ui->ARCcatalogComboBox->currentText() + "
"; config += "Max allowed pm = " + pm + "
"; config += "Field center RA = " + ra + "
"; config += "Field center DEC = " + dec + "
"; config += "Target name = " + cdw->ui->ARCtargetresolverLineEdit->text() + "
"; config += "Magnitude limit = " + mag + "
"; config += "Radius = " + rad + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigGetCatalogFromImage() { QString config; config = ""; config += "FITS file = " + cdw->ui->ARCselectimageLineEdit->text() + "
"; config += "DT = " + cdw->ui->ARCDTLineEdit->text() + "
"; config += "DMIN = " + cdw->ui->ARCDMINLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigAstromphotom() { QString config; config = ""; config += "POSANGLE_MAXERR = " + cdw->ui->ASTposangleLineEdit->text() + "
"; config += "POSITION_MAXERR = " + cdw->ui->ASTpositionLineEdit->text() + "
"; config += "PIXSCALE_MAXERR = " + cdw->ui->ASTpixscaleLineEdit->text() + "
"; config += "CROSSID_RADIUS = " + cdw->ui->ASTcrossidLineEdit->text() + "
"; config += "ASTREF_WEIGHT = " + cdw->ui->ASTastrefweightLineEdit->text() + "
"; config += "SN_THRESHOLDS = " + cdw->ui->ASTsnthreshLineEdit->text() + "
"; config += "ASTR_INSTRUKEY = " + cdw->ui->ASTastrinstrukeyLineEdit->text() + "
"; config += "PHOT_INSTRUKEY = " + cdw->ui->ASTphotinstrukeyLineEdit->text() + "
"; config += "DISTORT_DEGREES = " + cdw->ui->ASTdistortLineEdit->text() + "
"; config += "DISTORT_GROUPS = " + cdw->ui->ASTdistortgroupsLineEdit->text() + "
"; config += "DISTORT_KEYS = " + cdw->ui->ASTdistortkeysLineEdit->text() + "
"; config += "Astrometric solver = " + cdw->ui->ASTmethodComboBox->currentText() + "
"; config += "Matching method = " + cdw->ui->ASTmatchMethodComboBox->currentText() + "
"; config += "STABILITY_TYPE = " + cdw->ui->ASTstabilityComboBox->currentText() + "
"; config += "MOSAIC_TYPE = " + cdw->ui->ASTmosaictypeComboBox->currentText() + "
"; config += "FPA mode = " + cdw->ui->ASTfocalplaneComboBox->currentText() + "
"; config += "Match flipped images = " + boolToString(cdw->ui->ASTmatchflippedCheckBox->isChecked()) + "
"; config += "Checkplot resolution = " + cdw->ui->ASTresolutionLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigSkysubModel() { QString config; config = ""; config += "Detection threshold (DT) = " + cdw->ui->skyDTLineEdit->text() + "
"; config += "Detection min area (DMIN) = " + cdw->ui->skyDMINLineEdit->text() + "
"; config += "Kernel width [pixel] = " + cdw->ui->skyKernelLineEdit->text() + "
"; config += "Mask expansion factor = " + cdw->ui->skyMefLineEdit->text() + "
"; emit messageAvailable(config, "config"); } void Controller::pushConfigSkysubConst() { QString config; config = ""; config += "Constant sky measurement area = " + cdw->ui->skyAreaComboBox->currentText() + "
"; if (cdw->ui->skyAreaComboBox->currentIndex() != 0) { config += "Detection threshold (DT) = " + cdw->ui->skyDTLineEdit->text() + "
"; config += "Detection min area (DMIN) = " + cdw->ui->skyDMINLineEdit->text() + "
"; config += "Kernel width [pixel] = " + cdw->ui->skyKernelLineEdit->text() + "
"; config += "Mask expansion factor = " + cdw->ui->skyMefLineEdit->text() + "
"; } emit messageAvailable(config, "config"); } void Controller::pushConfigSkysubPoly() { QString config; config = ""; emit messageAvailable(config, "config"); } void Controller::pushConfigCoadd() { QString config; config = ""; config += "Reference RA = " + cdw->ui->COAraLineEdit->text() + "
"; config += "Reference DEC = " + cdw->ui->COAdecLineEdit->text() + "
"; config += "Plate scale = " + cdw->ui->COApixscaleLineEdit->text() + "
"; config += "Sky PA = " + cdw->ui->COAskypaLineEdit->text() + "
"; config += "COMBINETYPE = " + cdw->ui->COAcombinetypeComboBox->currentText() + "
"; config += "Resamp Kernel = " + cdw->ui->COAkernelComboBox->currentText() + "
"; config += "Sky projection = " + cdw->ui->COAprojectionComboBox->currentText() + "
"; config += "Celestial type = " + cdw->ui->COAcelestialtypeComboBox->currentText() + "
"; config += "Rescale weights = " + boolToString(cdw->ui->COArescaleweightsCheckBox->isChecked()) + "
"; config += "Outlier thresh = " + cdw->ui->COAoutthreshLineEdit->text() + "
"; config += "Outlier numpix = " + cdw->ui->COAoutsizeLineEdit->text() + "
"; config += "Outlier border = " + cdw->ui->COAoutborderLineEdit->text() + "
"; config += "Identifier = " + cdw->ui->COAuniqueidLineEdit->text() + "
"; config += "Coadd chips = " + cdw->ui->COAchipsLineEdit->text() + "
"; config += "Edge smoothing = " + cdw->ui->COAedgesmoothingLineEdit->text() + "
";; config += "NAXIS1 = " + cdw->ui->COAsizexLineEdit->text() + "
";; config += "NAXIS2 = " + cdw->ui->COAsizeyLineEdit->text() + "
";; config += "Nonsidereal RA = " + cdw->ui->COApmraLineEdit->text() + " " + cdw->ui->COApmComboBox->currentText() + "
"; config += "Nonsidereal DEC = " + cdw->ui->COApmdecLineEdit->text() + " " + cdw->ui->COApmComboBox->currentText() + "
"; config += "Perform fluxcal = " + boolToString(cdw->ui->COAfluxcalibCheckBox->isChecked()) + "
"; config += "
"; emit messageAvailable(config, "config"); } THELI-3.1.3/src/processingInternal/mask.cc000066400000000000000000000124641417631501300202750ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mask.h" #include "../functions.h" #include "../tools/polygon.h" #include #include #include Mask::Mask(const instrumentDataType *instrumentData, QObject *parent) : QObject(parent), instData(instrumentData) { // Initialize the masks initMasks(); } void Mask::initMasks() { // We need as many masks as we have chips // Masks are fully populated, even for chips the user does not want to use, because the latter may change, // but the mask is initialized when the instrument is selected, so we need it for all chips. globalMask.resize(instData->numChips); isChipMasked.resize(instData->numChips); // Resize each mask, and set it to false for (int chip=0; chipnumChips; ++chip) { long n = instData->sizex[chip]; // naxis1 after overscan trimming long m = instData->sizey[chip]; // naxis2 after overscan trimming globalMask[chip].fill(false, n*m); // Initiate all pixels to be unmasked ("masked = false") isChipMasked[chip] = false; globalMask[chip].squeeze(); // shed excess memory } // The basename of the region mask. // There can be a global mask (without chip number), ending in .reg which is valid for all chips. // And there can be additional, individual masks, ending in_chip.reg QString baseName = instData->nameFullPath; baseName = baseName.remove(".ini"); // Global mask: create the mask for chip 1, then copy it to all other chips. // This assumes that all chips have identical geometries! QString globalMaskName = baseName+".reg"; long n_ref = instData->sizex[0]; long m_ref = instData->sizey[0]; QFile file(globalMaskName); if (file.exists()) { addRegionFilesToMask(n_ref, m_ref, globalMaskName, globalMask[0], isChipMasked[0]); for (int chip=1; chipnumChips; ++chip) { long n = instData->sizex[chip]; long m = instData->sizey[chip]; if (n != n_ref || m != m_ref) { qDebug() << "QDEBUG: Mask::Mask(): Error: chip geometries must be identical for all chips for a global mask."; break; } isChipMasked[chip] = true; globalMask[chip] = globalMask[0]; } } // Individual mask (addRegionFiles exists immediately if file does not exist) #pragma omp parallel for // NOT parallelized internally (polygon::addPolygon_bool() for (int chip=0; chipnumChips; ++chip) { QString individualMaskName = baseName+"_"+QString::number(chip+1)+".reg"; long n = instData->sizex[chip]; long m = instData->sizey[chip]; addRegionFilesToMask(n, m, individualMaskName, globalMask[chip], isChipMasked[chip]); } } void Mask::invert() { for (int chip=0; chipnumChips; ++chip) { for (auto &it : globalMask[chip]) { it = !it; } } } /* void Mask::addRectangle(int chip, QVector rect, bool invert) { long n = instData->sizex[chip]; // naxis1 after overscan trimming long m = instData->sizey[chip]; // naxis2 after overscan trimming // Add rectangular area to mask, possibly inverted long xmin = rect[0]; long xmax = rect[1]; long ymin = rect[2]; long ymax = rect[3]; long i, j; if (xmin >= 0 && xmax >= 0 && ymin >= 0 && ymax >= 0) { if (!invert) { for (j=0; j= xmin && i <= xmax && j >= ymin && j <= ymax) globalMask[chip][i+n*j] = true; } } } else { for (j=0; j= xmin && i <= xmax && j >= ymin && j <= ymax)) globalMask[chip][i+n*j] = true; } } } } } */ void Mask::addImage(int chip, QVector segmentationMap, bool invert) { long n = instData->sizex[chip]; // naxis1 after overscan trimming long m = instData->sizey[chip]; // naxis2 after overscan trimming // segmentation map (zero for good p Directory not found in Data classixels, i.e. "no object") for (long i=0; inumchips is already the new number of chips, while // the globalMask vector still has the old number! for (auto &it : globalMask) { it.clear(); it.squeeze(); } globalMask.resize(0); } THELI-3.1.3/src/processingInternal/mask.h000066400000000000000000000035411417631501300201330ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MASK_H #define MASK_H #include "../instrumentdata.h" #include // This class is used to create boolean masks for images (one mask per detector). // Value == false: good pixel (unmasked) // Value == true: bad pixel (masked) class Mask : public QObject { Q_OBJECT public: explicit Mask(const instrumentDataType *instrumentData, QObject *parent = nullptr); QVector< QVector > globalMask; QVector isChipMasked; void addImage(int chip, QVector segmentationMap, bool invert); void invert(); void reset(); void initMasks(); const instrumentDataType *instData; private: // See polygon.h for further functionality // void addRegionFiles(int chip, QString regionFile); // void addRectangle(int chip, QVector rect, bool invert); // void addCircle(int chip, float x, float y, float r, QString senseMode); // void addPolygon(int chip, QVector &vertx, QVector &verty, QString senseMode); // void polygon2vertices(QString polystring, QVector &vertx, QVector &verty); // void region2circle(QString circlestring, float &x, float &y, float &r); signals: public slots: }; #endif // MASK_H THELI-3.1.3/src/processingInternal/photinst.cc000066400000000000000000000024371417631501300212110ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "photinst.h" #include "../functions.h" #include PhotInst::PhotInst(QObject *parent) : QObject(parent) { fluxScale.clear(); expTime.clear(); RZP.clear(); indexMap.clear(); baseName.clear(); } void PhotInst::getRZP() { numExp = fluxScale.length(); for (int j=0; j #include #include class PhotInst : public QObject { Q_OBJECT public: explicit PhotInst(QObject *parent = nullptr); // Scamp photometric instruments QVector fluxScale; QVector expTime; QVector RZP; QStringList baseName; QMap indexMap; void getRZP(); signals: private: long numExp = 0; public slots: }; #endif // PHOTINST_H THELI-3.1.3/src/processingInternal/processingAncillary.cc000066400000000000000000000272061417631501300233550ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../query/query.h" #include "dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include #include #include #include void Controller::taskInternalGetCatalogFromWEB() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (instData->validChip == -1) { emit messageAvailable("No images found for "+scienceData->subDirName+". Could not determine sky coordinates for catalog download.", "warning"); emit warningReceived(); return; } pushBeginMessage(taskBasename, scienceDir); pushConfigGetCatalogFromWeb(); Query *query = new Query(&verbosity); connect(query, &Query::bulkMotionObtained, cdw, &ConfDockWidget::updateGaiaBulkMotion); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); connect(query, &Query::critical, this, &Controller::criticalReceived); connect(query, &Query::critical, scienceData, &Data::criticalFromQueryReceived); query->mainDirName = mainDirName; query->refcatName = cdw->ui->ARCcatalogComboBox->currentText(); query->alpha_manual = cdw->ui->ARCraLineEdit->text(); query->delta_manual = cdw->ui->ARCdecLineEdit->text(); query->radius_manual = cdw->ui->ARCradiusLineEdit->text(); query->magLimit_string = cdw->ui->ARCminmagLineEdit->text(); query->maxProperMotion_string = cdw->ui->ARCmaxpmLineEdit->text(); query->scienceData = scienceData; query->naxis1 = instData->sizex[0]; query->naxis2 = instData->sizey[0]; query->pixscale = instData->pixscale; query->doAstromQueryFromWeb(); delete query; query = nullptr; // pushEndMessage(taskBasename, scienceDir); } // UNUSED /* void Controller::provideHeaderInfo(Data *scienceData) { if (verbosity>1) emit messageAvailable("Collecting metadata from FITS files ...", "controller"); for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { it->loadHeader(); } } } */ void Controller::downloadGaiaCatalog(Data *scienceData) { // int verbosity = 0; gaiaQuery = new Query(&verbosity); connect(gaiaQuery, &Query::messageAvailable, this, &Controller::messageAvailableReceived); connect(gaiaQuery, &Query::critical, this, &Controller::criticalReceived); gaiaQuery->mainDirName = mainDirName; gaiaQuery->scienceData = scienceData; gaiaQuery->naxis1 = instData->sizex[0]; gaiaQuery->naxis2 = instData->sizey[0]; gaiaQuery->pixscale = instData->pixscale; gaiaQuery->suppressCatalogWarning = true; emit messageAvailable("Querying point source catalog from GAIA ...", "ignore"); gaiaQuery->doGaiaQuery(); emit messageAvailable(QString::number(gaiaQuery->numSources) + " point sources retrieved for analysis of image quality ...", "ignore"); // DO NOT 'delete' gaia query here. It is still used elsewhere } // Overload, to set the image size from the coadded image, and not from the images in the Data class void Controller::downloadGaiaCatalog(Data *scienceData, QString radius) { // int verbosity = 0; gaiaQuery = new Query(&verbosity); connect(gaiaQuery, &Query::messageAvailable, this, &Controller::messageAvailableReceived); connect(gaiaQuery, &Query::critical, this, &Controller::criticalReceived); gaiaQuery->mainDirName = mainDirName; gaiaQuery->scienceData = scienceData; gaiaQuery->radius_string = radius; gaiaQuery->suppressCatalogWarning = true; emit messageAvailable("Querying point source catalog from GAIA ...", "ignore"); gaiaQuery->doGaiaQuery(); emit messageAvailable(QString::number(gaiaQuery->numSources) + " point sources retrieved for analysis of image quality ...", "ignore"); // DO NOT 'delete' gaia query here. It is still used elsewhere } void Controller::collectGaiaRaDec(MyImage *image, QVector &dec, QVector &ra, QVector> &output) { long dim = dec.length(); output.reserve(dim); QVector alpha; QVector delta; alpha.reserve(4); delta.reserve(4); alpha << image->alpha_ll << image->alpha_lr << image->alpha_ul<< image->alpha_ur; delta << image->delta_ll << image->delta_lr << image->delta_ul<< image->delta_ur; double alpha_min = minVec_T(alpha); double alpha_max = maxVec_T(alpha); double delta_min = minVec_T(delta); double delta_max = maxVec_T(delta); for (long i=0; i= alpha_min && ra[i] <= alpha_max && dec[i] >= delta_min && dec[i] <= delta_max) { QVector result(3); result[0] = dec[i]; result[1] = ra[i]; result[2] = 0.0; // dummy magnitude output << result; } } } void Controller::taskInternalGetCatalogFromIMAGE() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); pushBeginMessage(taskBasename, scienceDir); pushConfigGetCatalogFromImage(); QString DT = cdw->ui->ARCDTLineEdit->text(); QString DMIN = cdw->ui->ARCDMINLineEdit->text(); if (DT == "") DT = cdw->defaultMap["ARCDTLineEdit"]; if (DMIN == "") DMIN = cdw->defaultMap["ARCMINLineEdit"]; QString image = cdw->ui->ARCselectimageLineEdit->text(); QFileInfo fi; fi.setFile(image); QString imagePath = fi.absolutePath(); QString imageName = fi.fileName(); QVector dummyMask; dummyMask.clear(); MyImage *detectionImage = new MyImage(imagePath, imageName, "", 1, dummyMask, &verbosity); connect(detectionImage, &MyImage::critical, this, &Controller::criticalReceived); connect(detectionImage, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); detectionImage->setupCoaddMode(); // Read image, add a dummy global mask, and add a weight map if any detectionImage->backgroundModel(256, "interpolate"); detectionImage->segmentImage(DT, DMIN, true); Query *query = new Query(&verbosity); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); connect(query, &Query::critical, this, &Controller::criticalReceived); query->mainDirName = mainDirName; query->scienceData = scienceData; query->fromImage = true; for (auto &object : detectionImage->objectList) { query->ra_out.append(object->ALPHA_J2000); query->de_out.append(object->DELTA_J2000); query->mag1_out.append(object->MAG_AUTO); } query->writeAstromScamp(); query->writeAstromANET(); query->writeAstromIview(); query->pushNumberOfSources(); delete query; query = nullptr; detectionImage->releaseAllDetectionMemory(); detectionImage->releaseBackgroundMemory("entirely"); delete detectionImage; detectionImage = nullptr; // dump reference catalog ID QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile file(outpath+"/.refcatID"); QTextStream stream(&file); if( !file.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::dumpRefcatID(): ERROR writing "+outpath+file.fileName()+" : "+file.errorString(), "error"); emit criticalReceived(); return; } stream << image+"_"+cdw->ui->ARCDTLineEdit->text()+"_"+cdw->ui->ARCDMINLineEdit->text() << "\n"; file.close(); } void Controller::taskInternalResolveTargetSidereal() { cdw->ui->ARCpmRALineEdit->clear(); cdw->ui->ARCpmDECLineEdit->clear(); QString targetName = cdw->ui->ARCtargetresolverLineEdit->text(); if (targetName.isEmpty()) return; targetName = targetName.simplified().replace(" ", "_"); Query *query = new Query(&verbosity); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); connect(query, &Query::critical, this, &Controller::criticalReceived); QString check = query->resolveTargetSidereal(targetName); if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta); else if (check == "Unresolved") emit showMessageBox("Controller::TARGET_UNRESOLVED", cdw->ui->ARCtargetresolverLineEdit->text(), ""); else { // nothing yet. } delete query; query = nullptr; } void Controller::taskInternalRestoreHeader() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); pushBeginMessage(taskBasename, scienceDir); QDir headerDir; headerDir.setPath(mainDirName+"/"+scienceDir+"/headers/"); if (!headerDir.exists()) { emit messageAvailable("Could not restore the original WCS solution. The headers/ subdirectory does not exist in
"+scienceDir, "error"); successProcessing = false; monitor->raise(); return; } QDir origDir; origDir.setPath(mainDirName+"/"+scienceDir+"/.origheader_backup/"); if (!origDir.exists()) { emit messageAvailable("Cannot restore headers. The backup copy was not found.", "error"); successProcessing = false; monitor->raise(); return; } #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { it->loadHeader(); // Restore the header if a backup exists if (it->scanAstromHeader(chip, "inBackupDir")) { it->updateZeroOrderOnDrive("restore"); // it->updateZeroOrderInMemory(); } } } successProcessing = true; // pushEndMessage(taskBasename, scienceDir); } // Cloned from Query::getCatalogSearchLocationAstrom() void Controller::getFieldCenter(Data *data, QString &alphaCenter, QString &deltaCenter) { if (!successProcessing) return; QVector crval1 = data->getKeyFromAllImages("CRVAL1"); QVector crval2 = data->getKeyFromAllImages("CRVAL2"); if (crval1.isEmpty() || crval2.isEmpty()) { emit messageAvailable("Query::getCatalogSearchLocationAstrom(): CRVAL vectors are empty", "error"); emit criticalReceived(); successProcessing = false; return; } // Use median to calculate field center (avoiding issues with RA=0|360 deg boundary) // Do not average central two elements if number of data points is even alphaCenter = QString::number(straightMedian_T(crval1, 0, false), 'f', 3); deltaCenter = QString::number(straightMedian_T(crval2, 0, false), 'f', 3); } THELI-3.1.3/src/processingInternal/processingAstrometry.cc000066400000000000000000001164241417631501300236110ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "../tools/imagequality.h" #include "../tools/correlator.h" #include "photinst.h" #include "ui_confdockwidget.h" #include #include #include #include #include #include #include void Controller::taskInternalAstromphotom() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; if (!scienceData->successProcessing) return; mainGUI->ui->processProgressBar->setDisabled(true); scampScienceDir = mainDirName+"/"+scienceDir; scampDir = scampScienceDir+"/astrom_photom_scamp/"; scampPlotsDir = mainDirName+"/"+scienceDir + "/plots/"; scampHeadersDir = mainDirName+"/"+scienceDir + "/headers/"; scampScienceData = scienceData; anetDir = scampScienceDir+"/astrom_photom_anet/"; pushBeginMessage(taskBasename, scienceDir); pushConfigAstromphotom(); // DAISY-CHAINING. The end of the scamp run triggers the iView display of the checkplots, // which in turn triggers the header update if (cdw->ui->ASTmethodComboBox->currentText() == "Scamp") { QString catDirName = mainDirName + "/" + scienceDir + "/cat/"; if (!scienceData->hasMatchingPartnerFiles(catDirName, ".scamp", false)) { emit messageAvailable("Not all exposures have complete .scamp catalogs. They will be skipped.", "warning"); // return; } if (cdw->ui->ASTmatchMethodComboBox->currentText() == "Astrometry.net") { if (!scienceData->hasMatchingPartnerFiles(catDirName, ".anet", false)) { emit messageAvailable("Not all exposures have complete .anet catalogs. They will be skipped.", "warning"); // return; } prepareAnetRun(scienceData); progress = 0.; runAnet(scienceData); } // run scamp and retrieval of point source catalog in parallel #pragma omp parallel sections { #pragma omp section { // Prepare scamp directories and perform consistency checks prepareScampRun(scienceData); // Collect scamp input catalogs long totNumObjects = 0; long numCats = prepareScampCats(scienceData, totNumObjects); // if (numCats == 0) return; // no exiting in openMP construct if (numCats > 0) { // Release memory: // 140 bytes per detection // "a few 10 kB" per FITS table // long totBytes = 0; int degrees = cdw->ui->ASTdistortLineEdit->text().toInt(); totBytes += totNumObjects * 140 + (2*50000*instData->numChips)*numCats; long Nt = numCats * 1 * (degrees*degrees+2) + numCats*6; totBytes += 8*Nt*Nt; totBytes = 2*totBytes/ 1024. / 1024.; if (verbosity >= 1) emit messageAvailable("Scamp memory estimate: " + QString::number(long(totBytes)) + " MB", "controller"); releaseMemory(totBytes, 1); progress = 0.; progressStepSize = 80. / (float) numCats; // 80%, leaving some space for distortion solution. // Build the scamp command buildScampCommand(scienceData); // Run the Scamp command workerThread = new QThread(); scampWorker = new ScampWorker(scampCommand, scampDir, instData->shortName); workerInit = true; workerThreadInit = true; scampWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, scampWorker, &ScampWorker::runScamp); // Qt::DirectConnection is bad here, because this task runs in a different thread than the main controller, // meaning that if e.g. sky sub is activated as well it will start immediately even before the scamp checkplots are shown // connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); // connect(scampWorker, &ScampWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); // connect(scampWorker, &ScampWorker::finished, scampWorker, &QObject::deleteLater, Qt::DirectConnection); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); connect(scampWorker, &ScampWorker::errorFound, this, &Controller::scampErrorFoundReceived); connect(scampWorker, &ScampWorker::finishedScamp, this, &Controller::finishedScampReceived); // Need the direct connection if we want the thread to actually return control to the main thread (activating the start button again). // But then sky sub would start before checkplots are evaluated. // CORRECT WAY: call workerThread->quit() at the end of the image quality analysis // connect(scampWorker, &ScampWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); // connect(scampWorker, &ScampWorker::finished, workerThread, &QThread::quit); connect(scampWorker, &ScampWorker::finished, scampWorker, &QObject::deleteLater); connect(scampWorker, &ScampWorker::messageAvailable, monitor, &Monitor::displayMessage); connect(scampWorker, &ScampWorker::fieldMatched, this, &Controller::fieldMatchedReceived); workerThread->start(); workerThread->wait(); } } #pragma omp section { downloadGaiaCatalog(scampScienceData); // Point sources } } } // Not implemented (greyed out) if (cdw->ui->ASTmethodComboBox->currentText() == "Astrometry.net") { QString catDirName = mainDirName + "/" + scienceDir + "/cat/"; if (!scienceData->hasMatchingPartnerFiles(catDirName, ".anet")) return; // Prepare anet directories and perform consistency checks prepareAnetRun(scienceData); /* // Release memory (assuming it is the same for a.net) // 140 bytes per detection // "a few 10 kB" per FITS table // long totBytes = 0; int degrees = cdw->ui->ASTdistortLineEdit->text().toInt(); totBytes += totNumObjects * 140 + (2*50000*instData->numChips)*numCats; long Nt = numCats * 1 * (degrees*degrees+2) + numCats*6; totBytes += 8*Nt*Nt; totBytes = 2*totBytes/ 1024. / 1024.; if (verbosity >= 1) emit messageAvailable("Astrometry.net memory estimate: " + QString::number(long(totBytes)) + " MB", "controller"); releaseMemory(totBytes, 1); */ progress = 0.; runAnet(scienceData); } else if (cdw->ui->ASTmethodComboBox->currentText() == "Cross-correlation") { } else if (cdw->ui->ASTmethodComboBox->currentText() == "Header") { // TODO } else { // No other method yet } } void Controller::scampErrorFoundReceived() { successProcessing = false; criticalReceived(); workerThread->quit(); } int Controller::getMaxPhotInst() { if (!successProcessing) return 0; // Parse the output headers and extract fluxscales and exposure times QDir dir(scampDir); QStringList filterList("*.head"); QStringList MEFheaders = dir.entryList(filterList); int maxPhotInst = 0; for (auto &it : MEFheaders) { QFile MEF(scampDir+"/"+it); QTextStream inStream(&MEF); if (!MEF.open(QIODevice::ReadOnly)) { continue; } QString line; int photinst = 0; while (inStream.readLineInto(&line)) { if (line.contains("PHOTINST=")) photinst = line.split("=")[1].split("/")[0].simplified().toInt(); } MEF.close(); if (photinst > maxPhotInst) maxPhotInst = photinst; } return maxPhotInst; } void Controller::scampCalcFluxscale() { if (!successProcessing) return; // Parse the output headers and extract fluxscales and exposure times QDir dir(scampDir); QStringList filterList("*.head"); QStringList MEFheaders = dir.entryList(filterList); if (MEFheaders.isEmpty()) { successProcessing = false; emit messageAvailable("Could not find scamp output headers.", "error"); criticalReceived(); workerThread->quit(); return; } bool success = true; int maxPhotInst = getMaxPhotInst(); for (int i=0; ivalidChip == -1) { successProcessing = false; return; } for (auto &it : scampScienceData->myImageList[instData->validChip]) { it->loadHeader(); if (it->baseName.contains(MEFbasename)) { exptime = it->exptime; basename = it->baseName; break; } } photInstruments[photinst_idx]->fluxScale.append(fluxscale); photInstruments[photinst_idx]->expTime.append(exptime); photInstruments[photinst_idx]->baseName.append(basename); // Mapping the running overall MEF file index to the running index of MEF file index for the current phot instrument photInstruments[photinst_idx]->indexMap.insert(MEFindex, photInstruments[photinst_idx]->fluxScale.length()-1); ++MEFindex; } // Calculate RZP and FLXSCALE for each photometric instrument for (auto &pi : photInstruments) { pi->getRZP(); } if (!success) { successProcessing = false; } } void Controller::finishedScampReceived() { if (!successProcessing) return; // Move the checkplots to their final place moveFiles("*.png", scampDir, scampPlotsDir); // Calculate the mean RZP and FLXSCALE per photometric instrument scampCalcFluxscale(); // Split the scamp headers into individual chips, adding RZP and FLXSCALE splitScampHeaders(); mainGUI->ui->processProgressBar->setEnabled(true); emit progressUpdate(100); // pushEndMessage(taskBasename, scampScienceDir); photInstruments.clear(); emit showScampCheckPlots(); } void Controller::fieldMatchedReceived() { #pragma omp atomic progress += progressStepSize; } void Controller::splitScampHeaders() { if (!successProcessing) return; // Split the MEF scamp header files into individual chips and move them to their final place QDir dir(scampDir); QStringList filterList("*.head"); QStringList MEFheaders = dir.entryList(filterList); bool success = true; long MEFindex = 0; for (auto &it : MEFheaders) { QFile MEF(scampDir+"/"+it); QFileInfo MEFinfo(MEF); QTextStream inStream(&MEF); if (!MEF.open(QIODevice::ReadOnly)) { success = false; break; } QFile HEAD; QTextStream outStream; QString line; int i=0; int headCount = 0; while (inStream.readLineInto(&line)) { if (i==0) { int chip = instData->chipMap.key(headCount) + 1; // dealing with user defined bad chips HEAD.setFileName(scampHeadersDir+"/"+MEFinfo.completeBaseName()+"_"+QString::number(chip)+".head"); outStream.setDevice(&HEAD); if (!HEAD.open(QIODevice::WriteOnly)) { success = false; break; } } // THELI style flux scaling if (line.contains("FLXSCALE=")) line.replace("FLXSCALE=","FLSCALE ="); // copying the original FLXSCALE keyword to FLSCALE (original will be replaced below) if (line.contains("PHOTINST")) { int photinst_idx = line.split("=")[1].split("/")[0].simplified().toInt() - 1; long idx = photInstruments[photinst_idx]->indexMap.value(MEFindex); QString line1 = "FLXSCALE= "+QString::number(photInstruments[photinst_idx]->fluxScale[idx],'g',12) + " / THELI relative flux scale"; QString line2 = "RZP = "+QString::number(photInstruments[photinst_idx]->RZP[idx],'g',12) + " / THELI relative zeropoint"; outStream << line1 << "\n"; outStream << line2 << "\n"; } outStream << line << "\n"; ++i; if (line.simplified() == "END") { HEAD.close(); HEAD.setPermissions(QFile::ReadUser | QFile::WriteUser); i=0; ++headCount; } } MEF.close(); ++MEFindex; } if (!success) { successProcessing = false; emit messageAvailable("Could not parse one or more of the scamp output header files.", "error"); criticalReceived(); } } // unused, done in copy_zero_order() /* void Controller::updateMyImagesWithScampSolution(Data *scienceData) { for (int chip=0; chipnumChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { // header file QFile headerFile(scienceData->dirName + "/headers/" + it->chipName + ".head"); QString RZP = get_fileHeaderParameter(&headerFile, "RZP"); it->RZP = RZP.toFloat(); it->updateHeaderValue("RZP", RZP); // like that it will be included in the FITS file when written it->updateHeaderValueInFITS("RZP", RZP); // Optionally, updates the FITS file as well (if on drive) } } } */ void Controller::showScampCheckPlotsReceived() { if (!successProcessing) return; emit messageAvailable("
*** Inspect the astrometric solution and accept or reject it. ***
", "warning"); IView *checkplotViewer = new IView("SCAMP", scampPlotsDir, this); // blocks until seeing determination is done, which is silly and i don't understand why // checkplotViewer->setWindowModality(Qt::ApplicationModal); checkplotViewer->show(); connect(checkplotViewer, &IView::solutionAcceptanceState, this, &Controller::registerScampSolutionAcceptance); // Avoid THELI hogging memory during the session with every call to iview connect(checkplotViewer, &IView::closed, checkplotViewer, &IView::deleteLater); connect(checkplotViewer, &IView::closed, this, &Controller::continueWithCopyZeroOrder); } void Controller::registerScampSolutionAcceptance(bool scampSolutionAccepted) { scampSolutionAcceptanceState = scampSolutionAccepted; if (scampSolutionAccepted) { emit messageAvailable("*** Scamp solution accepted ***
", "note"); } else { emit messageAvailable("*** Scamp solution rejected ***
", "warning"); } } void Controller::continueWithCopyZeroOrder() { if (!successProcessing) return; if (scampSolutionAcceptanceState) copyZeroOrder(); else { monitor->raise(); successProcessing = false; workerThread->quit(); successProcessing = true; } } void Controller::copyZeroOrder() { if (!successProcessing) return; pushBeginMessage("CopyZeroOrder", scampScienceDir); if (!QDir(scampHeadersDir).exists()) { emit messageAvailable("Could not update images with 0th order WCS solution.
The headers/ subdirectory does not exist in
"+scampScienceDir, "error"); successProcessing = false; monitor->raise(); workerThread->quit(); successProcessing = true; return; } #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; for (auto &it : scampScienceData->myImageList[chip]) { if (abortProcess) break; it->setupDataInMemorySimple(false); if (it->activeState != MyImage::ACTIVE) continue; if (!it->successProcessing) { abortProcess = true; continue; } // it->backupOrigHeader(chip); // Create a backup copy of the original FITS headers if it doesn't exist yet if (it->scanAstromHeader(chip, "inHeadersDir")) { // reads the header, and updates the wcs struct in MyImage class (i.e. the memory) it->updateZeroOrderOnDrive("update"); // Overwrite 0-th order solution in FITS header (if on drive) // it->updateZeroOrderInMemory(); // Overwrite 0-th order solution in memory } // The following is done by scanAstromheader and updateZeroOrderOnDrive /* // Copy RZP from header file QFile headerFile(scampScienceData->dirName + "/headers/" + it->chipName + ".head"); QString RZP = get_fileHeaderParameter(&headerFile, "RZP"); it->RZP = RZP.toFloat(); it->updateHeaderValue("RZP", RZP); // like that it will be included in the FITS file when written it->updateHeaderValueInFITS("RZP", RZP); // Optionally, updates the FITS file as well (if on drive) */ it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } if (!it->successProcessing) successProcessing = false; } } // pushEndMessage("CopyZeroOrder", scampScienceDir); doImageQualityAnalysis(); } void Controller::prepareAnetRun(Data *scienceData) { if (!successProcessing) return; if (verbosity > 0) emit messageAvailable("Setting up astrometry.net run ...", "controller"); QString scienceDir = mainDirName+"/"+scienceData->subDirName; QString headersPath = scienceDir+"/headers/"; // Clean-up and recreate the anet directory trees QDir dir(anetDir); dir.removeRecursively(); dir.mkpath(anetDir); QDir headersDir(headersPath); headersDir.removeRecursively(); headersDir.mkpath(headersPath); // Check if the reference catalog exists QFile refcat(scienceDir+"/cat/refcat/theli_mystd.index"); if (!refcat.exists()) { emit messageAvailable("The astrometric reference catalog does not exist, or was not created!", "error"); successProcessing = false; monitor->raise(); return; } // Write the config file for the solver QFile backendConfig(scienceDir+"/astrom_photom_anet/backend.cfg"); if (backendConfig.exists()) backendConfig.remove(); QTextStream stream(&backendConfig); if( !backendConfig.open(QIODevice::WriteOnly)) { emit messageAvailable("Controller::prepareAnetRun(): ERROR writing "+scienceDir+"/astrom_photom_anet/backend.cfg : "+backendConfig.errorString(), "error"); emit criticalReceived(); return; } stream << "#inparallel" << "\n"; stream << "#depths 10 20 30 40 50 60 70 80 90 100" << "\n"; stream << "#cpulimit 300" << "\n"; stream << "add_path " << scienceDir+"/cat/refcat/" << "\n"; stream << "index theli_mystd.index" << "\n"; backendConfig.close(); backendConfig.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Controller::runAnet(Data *scienceData) { QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 1; // wild guess, don't know the memory needs of a.net releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); QString pixscaleMaxerr = cdw->ui->ASTpixscaleLineEdit->text(); scienceData->populateExposureList(); progressStepSize = 100. / float(numMyImages); #pragma omp parallel for num_threads(maxCPU) for (int k=0; kchipNumber - 1; if (!it->successProcessing) continue; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity >= 1) emit messageAvailable(it->chipName + " : Running astrometry.net ...", "data"); it->loadHeader(); // don't need pixels, but metadata it->checkWCSsanity(); it->buildAnetCommand(pixscaleMaxerr); it->runAnetCommand(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } #pragma omp atomic progress += progressStepSize; } emit messageAvailable("
Astrometry.net summary : ", "data"); // merge the anet output of multi-chip cameras, and extract relevant keywords, only for (long i=0; iexposureList.length(); ++i) { if (abortProcess || !successProcessing) continue; // open stream for merged output file QString aheaderName = anetDir+"/"+scienceData->exposureList[i][0]->rootName+".ahead"; QFile aheaderFile(aheaderName); QTextStream stream(&aheaderFile); if( !aheaderFile.open(QIODevice::WriteOnly)) { emit messageAvailable("Could not write astrometry.net reformatted output to "+aheaderFile.fileName(), "error"); emit messageAvailable(aheaderFile.errorString(), "error"); emit criticalReceived(); successProcessing = false; break; } // Loop over chips and extract anet header data bool consistent = false; int count = 0; for (auto &it : scienceData->exposureList[i]) { stream << it->extractAnetOutput(); ++count; } if (count == instData->numUsedChips) consistent = true; aheaderFile.close(); aheaderFile.setPermissions(QFile::ReadUser | QFile::WriteUser); if (!consistent) { aheaderFile.remove(); emit messageAvailable(scienceData->exposureList[i][0]->rootName + " : Controller::runAnet(): Inconsistent number of detectors", "warning"); } } // Collect a list of the header files for scamp makeAnetHeaderList(scienceData); } void Controller::doImageQualityAnalysis() { if (!successProcessing) return; // Only do this for cameras which have a meaningful plate scale for this purpose, i.e. where there is // a risk that background galaxies contaminate a global statistical seeing and ellipticity measurement done during 'create source cat'. // Same for huge cameras such as DECam, but here simply because the catalog download would take forever. if (instData->pixscale > 2.0 || instData->radius > 1.0) { workerThread->quit(); successProcessing = true; return; } pushBeginMessage("ImageQuality", scampScienceDir); // Todo: replace with GAIA catalog if that was the reference catalog already! // downloadGaiaCatalog(scampScienceData); // Point sources QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scampScienceData); #pragma omp parallel for num_threads(maxCPU) firstprivate(mainDirName, gaiaQuery, instData) for (int k=0; kchipNumber - 1; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; if (instData->badChips.contains(chip)) continue; it->setupDataInMemorySimple(false); if (!it->successProcessing) { abortProcess = true; continue; } // Setup seeing measurement it->estimateMatchingTolerance(); ImageQuality *imageQuality = new ImageQuality(instData, mainDirName); imageQuality->matchingTolerance = it->matchingTolerance; imageQuality->baseName = it->chipName; // pass the reference data collectGaiaRaDec(it, gaiaQuery->de_out, gaiaQuery->ra_out, imageQuality->refCat); // pass the source data (dec, ra, fwhm, ell on one hand, and mag separately) it->collectSeeingParameters(imageQuality->sourceCat, imageQuality->sourceMag, instData->chipMap.value(chip)); // match static_cast (imageQuality->getSeeingFromGaia()); it->fwhm = imageQuality->fwhm * instData->pixscale; // Updating MyImage fwhm parameter, in arcsec it->updateHeaderValue("FWHM", it->fwhm); // Updating MyImage header string it->updateHeaderValue("ELLIP", imageQuality->ellipticity); it->updateHeaderValueInFITS("FWHM", QString::number(it->fwhm, 'f', 3)); // Updating the current FITS image on drive it->updateHeaderValueInFITS("ELLIP", QString::number(imageQuality->ellipticity, 'f', 3)); // if (!gaia) imageQuality->getSeeingFromRhMag(); TODO: Not yet implemented if (verbosity > 1) emit messageAvailable(it->chipName + " : FWHM / Ellipticity / # stars = " + QString::number(it->fwhm, 'f', 3) + " / " + QString::number(imageQuality->ellipticity, 'f', 3) + " / " + QString::number(imageQuality->numSources), "ignore"); delete imageQuality; imageQuality = nullptr; it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } } workerThread->quit(); delete gaiaQuery; gaiaQuery = nullptr; // emit messageAvailable("You can display the results of the image quality analysis in the statistics module", "note"); successProcessing = true; // pushEndMessage("ImageQuality", scampScienceDir); } // X-correlation works only for instruments with a single chip! void Controller::doCrossCorrelation(Data *scienceData) { if (!successProcessing) return; QString DT = cdw->ui->ASTxcorrDTLineEdit->text(); QString DMIN = cdw->ui->ASTxcorrDMINLineEdit->text(); if (DT.isEmpty()) DT = "3.0"; if (DMIN.isEmpty()) DMIN = "5"; //#pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; emit messageAvailable(it->baseName + " : Building xcorrelation pixel map ...", "controller"); it->setupDataInMemorySimple(false); if (!it->successProcessing) { abortProcess = true; continue; } if (it->activeState != MyImage::ACTIVE) continue; it->readWeight(); it->resetObjectMasking(); it->backgroundModel(64, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->makeXcorrData(); if (!it->successProcessing) successProcessing = false; // TODO // write image // run python script instead of fftw /* // Correlate image with reference image (first in series) Correlator correlator(it, scienceData->myImageList[chip][0]); correlator.xcorrelate(); QVector peakPos = correlator.find_peak(); if (peakPos.isEmpty()) it->successProcessing = false; */ it->releaseAllDetectionMemory(); } } satisfyMaxMemorySetting(); } void Controller::prepareScampRun(Data *scienceData) { if (!successProcessing) return; if (verbosity > 0) emit messageAvailable("Setting up Scamp run ...", "controller"); QString scienceDir = mainDirName+"/"+scienceData->subDirName; QString headersPath = scienceDir+"/headers/"; QString plotsPath = scienceDir+"/plots/"; // Clean-up and recreate the scamp directory trees QDir dir(scampDir); dir.removeRecursively(); dir.mkpath(scampDir); QDir plotsDir(plotsPath); plotsDir.removeRecursively(); plotsDir.mkpath(plotsPath); QDir headersDir(headersPath); headersDir.removeRecursively(); headersDir.mkpath(headersPath); QFile file(scampDir+"/scamp_global.ahead"); file.remove(); // Check if the reference catalog exists QFile refcat(scienceDir+"/cat/refcat/theli_mystd.scamp"); if (!refcat.exists()) { emit messageAvailable("The astrometric reference catalog does not exist, or was not created!", "error"); successProcessing = false; monitor->raise(); return; } // emit appendOK(); } long Controller::prepareScampCats(Data *scienceData, long &totNumObjects) { if (!successProcessing) return 0; QString scienceDir = mainDirName+"/"+scienceData->subDirName; if (verbosity > 0) emit messageAvailable("Linking scamp catalogs to "+scampDir+" ...", "controller"); // Prepare a file that contains all scamp catalogs (only those for which an image is currently present in scienceDir); QFile catFile(scampDir+"/scamp_cats"); catFile.remove(); QTextStream stream(&catFile); if( !catFile.open(QIODevice::WriteOnly)) { emit messageAvailable("Writing list of scamp catalogs to "+scampDir+catFile.fileName(), "error"); emit messageAvailable(catFile.errorString(), "error"); successProcessing = false; monitor->raise(); return 0; } // Link scamp catalogs (only those for currently active images) long numCat = 0; QStringList imageList; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (it->activeState == MyImage::ACTIVE) imageList << it->chipName; } } QDir catDir(scienceDir+"/cat/"); QStringList catList = catDir.entryList(QStringList("*.scamp")); for (auto &cat : catList) { QString catbase = cat; totNumObjects += getNumObjectsScampCat(scienceDir+"/cat/"+catbase); catbase.remove(".scamp"); for (auto &image : imageList) { if (image.contains(catbase)) { QFile catFile(scienceDir+"/cat/"+cat); catFile.link(scampDir+"/"+cat); stream << scampDir+"/"+cat+"\n"; ++numCat; break; } } } catFile.close(); catFile.setPermissions(QFile::ReadUser | QFile::WriteUser); if (numCat == 0) { emit messageAvailable("No cat/*.scamp catalogs were found matching the exposures in "+scienceDir+"
Did you create the source catalogs?", "error"); monitor->raise(); successProcessing = false; return 0; } // emit appendOK(); return numCat; } long Controller::makeAnetHeaderList(Data *scienceData) { if (!successProcessing) return 0; // Prepare a list of all anet .ahead files (only those for which an image is currently present); QFile aheadFile(anetDir+"/anet_headers"); aheadFile.remove(); QTextStream stream(&aheadFile); if( !aheadFile.open(QIODevice::WriteOnly)) { emit messageAvailable("Writing list of anet ehaders to "+anetDir+aheadFile.fileName(), "error"); emit messageAvailable(aheadFile.errorString(), "error"); successProcessing = false; monitor->raise(); return 0; } // Link anet headers (only those for currently active images) long numCat = 0; QStringList imageList; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (it->activeState == MyImage::ACTIVE) imageList << it->chipName; } } QDir aheadDir(anetDir); QStringList aheadList = aheadDir.entryList(QStringList("*.ahead")); for (auto &ahead : aheadList) { QString aheadbase = ahead; int numChips = getNumAnetChips(anetDir+"/"+aheadbase); if (numChips != instData->numUsedChips) continue; // skip bad entry. Error triggered by getNumEnetChips() aheadbase.remove(".ahead"); for (auto &image : imageList) { if (image.contains(aheadbase)) { stream << anetDir+"/"+ahead+"\n"; ++numCat; break; } } } aheadFile.close(); aheadFile.setPermissions(QFile::ReadUser | QFile::WriteUser); if (numCat == 0) { QString scienceDir = mainDirName+"/"+scienceData->subDirName; emit messageAvailable("No *.ahead catalogs were found matching the exposures in "+scienceDir, "error"); monitor->raise(); successProcessing = false; return 0; } return numCat; } long Controller::getNumObjectsScampCat(QString cat) { int status = 0; fitsfile *fptr; fits_open_file(&fptr, cat.toUtf8().data(), READONLY, &status); // LDAC_OBJECTS tables are found in extensions 3, 5, 7, ..., internally referred to as 2, 4, 6, ... int hduType = 0; long nobj = 0; for (int chip=1; chip<=instData->numUsedChips; ++chip) { fits_movabs_hdu(fptr, 2*chip+1, &hduType, &status); long nrows = 0; fits_get_num_rows(fptr, &nrows, &status); nobj += nrows; } fits_close_file(fptr, &status); QString out = __func__; out.append( " :
" +cat); printCfitsioError(out, status); return nobj; } long Controller::getNumAnetChips(QString ahead) { // Count the number of "END" strings QFile file(ahead); QTextStream inStream(&file); if (!file.open(QIODevice::ReadOnly)) { emit messageAvailable("Controller::getNumAnetChips(): Could not open "+ahead+" " + file.errorString(), "error"); emit criticalReceived(); monitor->raise(); successProcessing = false; return 0; } QString line; int numChips = 0; while (inStream.readLineInto(&line)) { if (line == "END") ++numChips; } file.close(); if (numChips == instData->numUsedChips) return numChips; else { emit messageAvailable(ahead + ":
Expected "+QString::number(instData->numUsedChips)+" chips, but found "+QString::number(numChips), "error"); emit criticalReceived(); monitor->raise(); successProcessing = false; return 0; } } long Controller::getNumObjectsSourceExtractorCat(QString cat) { int status = 0; fitsfile *fptr; fits_open_file(&fptr, cat.toUtf8().data(), READONLY, &status); // LDAC_OBJECTS table is found in extensions 3, internally referred to as 2 int hduType = 0; fits_movabs_hdu(fptr, 3, &hduType, &status); long nrows = 0; fits_get_num_rows(fptr, &nrows, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); return nrows; } void Controller::buildScampCommand(Data *scienceData) { if (!successProcessing) return; QString refcat = mainDirName+"/"+scienceData->subDirName; refcat.append("/cat/refcat/theli_mystd.scamp"); QString distGroups = "1,1"; QString distGroupsUser = cdw->ui->ASTdistortgroupsLineEdit->text(); if (!distGroupsUser.isEmpty()) distGroups.append(","+distGroupsUser); QString distKeys = "XWIN_IMAGE,YWIN_IMAGE"; QString distKeysUser = cdw->ui->ASTdistortkeysLineEdit->text(); if (!distKeysUser.isEmpty()) distKeys.append(","+distKeysUser); scampCommand = findExecutableName("scamp"); scampCommand += " @"+scampDir+"/scamp_cats"; scampCommand += " -NTHREADS " + QString::number(maxCPU); scampCommand += " -ASTREF_CATALOG FILE"; scampCommand += " -ASTREFCAT_NAME " + refcat; scampCommand += " -ASTREF_WEIGHT " + getUserParamLineEdit(cdw->ui->ASTastrefweightLineEdit); scampCommand += " -ASTRINSTRU_KEY " + getUserParamLineEdit(cdw->ui->ASTastrinstrukeyLineEdit); scampCommand += " -CROSSID_RADIUS " + getUserParamLineEdit(cdw->ui->ASTcrossidLineEdit); scampCommand += " -DISTORT_DEGREES " + getUserParamLineEdit(cdw->ui->ASTdistortLineEdit); scampCommand += " -DISTORT_GROUPS " + distGroups; scampCommand += " -DISTORT_KEYS " + distKeys; scampCommand += " -PIXSCALE_MAXERR " + getUserParamLineEdit(cdw->ui->ASTpixscaleLineEdit); scampCommand += " -POSANGLE_MAXERR " + getUserParamLineEdit(cdw->ui->ASTposangleLineEdit); scampCommand += " -POSITION_MAXERR " + getUserParamLineEdit(cdw->ui->ASTpositionLineEdit); scampCommand += " -SN_THRESHOLDS " + getUserParamLineEdit(cdw->ui->ASTsnthreshLineEdit); scampCommand += " -STABILITY_TYPE " + getUserParamComboBox(cdw->ui->ASTstabilityComboBox); scampCommand += " -MOSAIC_TYPE " + getUserParamComboBox(cdw->ui->ASTmosaictypeComboBox); scampCommand += " -MATCH_FLIPPED " + getUserParamCheckBox(cdw->ui->ASTmatchflippedCheckBox); scampCommand += " -CHECKPLOT_RES " + getUserParamLineEdit(cdw->ui->ASTresolutionLineEdit); if (cdw->ui->ASTmatchMethodComboBox->currentText() == "Astrometry.net") { scampCommand += " -AHEADER_NAME @"+anetDir+"/anet_headers"; } QString value = cdw->ui->ASTastrinstrukeyLineEdit->text(); if (value == "") value = "NONE"; scampCommand += " -ASTRINSTRU_KEY " + value; value = cdw->ui->ASTphotinstrukeyLineEdit->text(); if (value == "") value = "NONE"; scampCommand += " -PHOTINSTRU_KEY " + value; QString matching = "Y"; if (cdw->ui->ASTmatchMethodComboBox->currentIndex() > 0) matching = "N"; scampCommand += " -MATCH " + matching; if (verbosity >= 1) emit messageAvailable("Executing the following scamp command :

"+scampCommand+"

in directory:

"+scampDir+"
", "info"); if (verbosity >= 1) emit messageAvailable("
Scamp output
", "ignore"); } THELI-3.1.3/src/processingInternal/processingBackground.cc000066400000000000000000001546121417631501300235200ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include "ui_monitor.h" #include "../query/query.h" #include #include #include #include void Controller::taskInternalBackground() { QString scienceDir = instructions.split(" ").at(1); QString skyDir = instructions.split(" ").at(2); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigBackground(); // Need to fill myImageList to get Filter keyword (if the user starts fresh with this task after launching THELI) if (scienceData->myImageList[instData->validChip].isEmpty()) scienceData->populate(scienceData->processingStatus->statusString); if (!scienceData->hasImages()) return; if (!scienceData->collectMJD()) return; // Leave if identical MJD entries are found (or no MJD entries at all) scienceData->resetProcessbackground(); scienceData->resetObjectMasking(); Data *skyData = nullptr; if (skyDir == "noskydir") skyData = scienceData; // The background is calculated either from science or from sky images else { skyData = getData(DT_SKY, skyDir); if (skyData == nullptr) return; // Error triggered by getData(); if (!skyData->hasImages()) return; if (!skyData->collectMJD()) return; skyData->resetProcessbackground(); skyData->resetObjectMasking(); } skyData->rescaleFlag = true; // Background images must be rescaled before combination into the final model memoryDecideDeletableStatus(scienceData, false); backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; // Static or dynamic mode ? scienceData->resetStaticModel(); skyData->resetStaticModel(); QString window = cdw->ui->BACwindowLineEdit->text(); QString mode = "dynamic"; if (window.isEmpty() || window.toInt() == 0) { mode = "static"; } scienceData->checkModeIsPresent(); skyData->checkModeIsPresent(); // Flag images with bright stars, leave if definitely too few images left QList> brightStarList; retrieveBrightStars(skyData, brightStarList); if (!idChipsWithBrightStars(skyData, brightStarList)) return; bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; getNumberOfActiveImages(scienceData); QVector numBackExpList(instData->numChips); float windowsize; if (window.isEmpty() || window == "0") windowsize = scienceData->myImageList[instData->validChip].length(); else windowsize = window.toInt(); float nimg = 7 + windowsize; // image, combined image, new image, background, measure, segment, mask + window data; modify for SKY images? releaseMemory(nimg*instData->storage*maxExternalThreads, 1); // Protect the rest, will be unprotected as needed scienceData->protectMemory(); skyData->protectMemory(); doDataFitInRAM(scienceData->myImageList[instData->validChip].length()*instData->numUsedChips, instData->storage); QString dt = cdw->ui->BACDTLineEdit->text(); QString dmin = cdw->ui->BACDMINLineEdit->text(); QString expFactor = cdw->ui->BACmefLineEdit->text(); QString nlow1 = cdw->ui->BAC1nlowLineEdit->text(); QString nhigh1 = cdw->ui->BAC1nhighLineEdit->text(); QString nlow2 = cdw->ui->BAC2nlowLineEdit->text(); QString nhigh2 = cdw->ui->BAC2nhighLineEdit->text(); bool twoPass = cdw->ui->BAC2passCheckBox->isChecked(); bool convolution = cdw->ui->BACconvolutionCheckBox->isChecked(); bool rescaleModel = cdw->ui->BACrescaleCheckBox->isChecked(); int nGroups = cdw->ui->SPSnumbergroupsLineEdit->text().toInt(); int nLength = cdw->ui->SPSlengthLineEdit->text().toInt(); QVector staticImagesWritten(instData->numChips); for (auto &it : staticImagesWritten) it = false; // **************************************** // OLD PARALLELIZATION SCHEME (good if numCPU <= numChips) // **************************************** processBackground(scienceData, skyData, nimg, numBackExpList, dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, twoPass, convolution, rescaleModel, nGroups, nLength, mode, staticImagesWritten); // **************************************** // NEW PARALLELIZATION SCHEME (good if numCPU > numChips); still not thread-safe // **************************************** /* if (mode == "static") { processBackgroundStatic(scienceData, skyData, nimg, numBackExpList, dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, twoPass, convolution, rescaleModel, nGroups, nLength, staticImagesWritten); } else { processBackgroundDynamic(scienceData, skyData, nimg, numBackExpList, dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, twoPass, convolution, rescaleModel, nGroups, nLength, staticImagesWritten); } */ if (!successProcessing) return; emit messageAvailable("
", "output"); emit messageAvailable("Number of images used in the background models:
", "controller"); for (auto &str : numBackExpList) { emit messageAvailable(str, "ignore"); } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); // Clean-up, otherwise interference with any source detection / masking task scienceData->cleanBackgroundModelStatus(); skyData->cleanBackgroundModelStatus(); if (successProcessing) { scienceData->processingStatus->Background = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header } } //void Controller::processBackground(Data *scienceData, Data *skyData, const float nimg, QVector &numBackExpList, // const QString dt, const QString dmin, const QString expFactor, const QString nlow1, // const QString nhigh1, const QString nlow2, const QString nhigh2, // const bool twoPass, const bool convolution, const bool rescaleModel, // const int nGroups, const int nLength, const QString mode, QVector &staticImagesWritten) void Controller::processBackground(Data *scienceData, Data *skyData, const float nimg, QVector &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QString mode, QVector &staticImagesWritten) { QString dataDirName = scienceData->dirName; QString dataSubDirName = scienceData->subDirName; QVector dataStaticModelDone = skyData->staticModelDone; #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, mode, dataDirName, dataSubDirName, dataStaticModelDone) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; int currentExposure = 0; // only relevant for LIRIS@WHT-type detectors where we need to select specific images QString backExpList = ""; bool pass2staticDone = false; for (auto &it : scienceData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Modeling background ...", "image"); it->processingStatus->Background = false; it->setupBackgroundData(scienceData->isTaskRepeated, backupDirName); // Put original flat-fielded data in dataBackupL1; // The list of background images. // Each image has a flag whether it contributes to the model. Initially, all are set to 'false' if (!setupBackgroundList(chip, skyData, it->chipName)) continue; // cannot use break in OMP loop if (!filterBackgroundList(chip, skyData, it, backExpList, nGroups, nLength, currentExposure, mode)) { continue; // cannot use break in OMP loop } // PASS 1: sendBackgroundMessage(mode, dataStaticModelDone[chip], it->chipName, 1); maskObjectsInSkyImagesPass1(chip, skyData, scienceData, twoPass, dt, dmin, convolution, expFactor); skyData->combineImages(chip, nlow1, nhigh1, it->chipName, mode, dataDirName, dataSubDirName, dataStaticModelDone); skyData->combinedImage[chip]->modeDetermined = false; // must redetermine! skyData->getModeCombineImages(chip); // PASS 2: if (twoPass) { sendBackgroundMessage(mode, dataStaticModelDone[chip], it->chipName, 2); maskObjectsInSkyImagesPass2(chip, skyData, scienceData, twoPass, dt, dmin, convolution, expFactor, rescaleModel); if (mode == "static" && !pass2staticDone) dataStaticModelDone[chip] = false; // must recalculate static model (dynamic model will always be recalculated) skyData->combineImages(chip, nlow2, nhigh2, it->chipName, mode, dataDirName, dataSubDirName, dataStaticModelDone); pass2staticDone = true; skyData->combinedImage[chip]->modeDetermined = false; // must redetermine! skyData->getModeCombineImages(chip); } skyData->writeBackgroundModel(chip, mode, it->baseName, staticImagesWritten[chip]); if (mode == "static") dataStaticModelDone[chip] = true; it->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); // DO NOT UNPROTECT MEMORY HERE (could be needed elsewhere) } // if (mode == "dynamic") it->releaseMemoryForBackground(); if (mode == "dynamic") scienceData->unprotectMemoryForBackground(chip); #pragma omp atomic progress += progressStepSize; ++currentExposure; } // In critical section because length of QString backexpList is variable, and Qvector is probably not thread safe because of this #pragma omp critical { numBackExpList[chip] = backExpList; } // L1 always contains the data before any modification, hence we do not need to create a backup copy. if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { it->makeBackgroundBackup(); // just a FITS file operation if necessary } scienceData->unprotectMemory(chip); skyData->unprotectMemory(chip); } } } /* //void Controller::processBackgroundStatic(Data *scienceData, Data *skyData, const float &nimg, QVector &numBackExpList, // const QString &dt, const QString &dmin, const QString &expFactor, const QString &nlow1, // const QString &nhigh1, const QString &nlow2, const QString &nhigh2, // const bool &twoPass, const bool &convolution, const bool &rescaleModel, // const int &nGroups, const int &nLength, QVector &staticImagesWritten) void Controller::processBackgroundStatic(Data *scienceData, Data *skyData, const float nimg, QVector &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QVector &staticImagesWritten) { // The following is needed for the new scheme QVector backExpList(maxCPU); QVector currentExposure(instData->numChips); // relevant only for LIRIS@WHT-type detectors QVector staticImagesCombined(instData->numChips); QVector combinedBackgroundImages(maxCPU); for (auto &it : backExpList) it = ""; for (auto &it : backExpListRescaleFactors) it = ""; for (auto &it : currentExposure) it = 0; for (auto &it : staticImagesCombined) it = false; for (auto &it : combinedBackgroundImages) it = nullptr; QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); QString dataSubDirName = scienceData->subDirName; #pragma omp parallel for num_threads(maxCPU) firstprivate(dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, dataSubDirName) for (int k=0; ksuccessProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Modeling background ...", "image"); it->processingStatus->Background = false; it->setupBackgroundData_newParallel(scienceData->isTaskRepeated, backupDirName); // Put original flat-fielded data in dataBackupL1; internal lock // The list of background images. Each image has a flag whether it contributes to the model. No locking required QList backgroundList; if (!filterBackgroundList(chip, skyData, it, backExpList[threadID], backgroundList, nGroups, nLength, currentExposure[chip], "static")) { continue; // cannot use break in OMP loop } // PASS 1: sendBackgroundMessage("static", skyData->staticModelDone[chip], it->chipName, 1); maskObjectsInSkyImagesPass1_newParallel(skyData, scienceData, backgroundList, twoPass, dt, dmin, convolution, expFactor, threadID); MyImage *masterCombined = new MyImage(dirName, "dummy.fits", "", chip+1, skyData->mask->globalMask[chip], skyData->mask->isChipMasked[chip], &verbosity); // do this only once per chip omp_set_lock(&backgroundLock); if (!staticImagesCombined[chip]) { skyData->combineImages_newParallel(chip, masterCombined, backgroundList, nlow1, nhigh1, it->chipName, "static", dataSubDirName); skyData->combinedImage[chip] = masterCombined; skyData->combinedImage[chip]->naxis1 = it->naxis1; skyData->combinedImage[chip]->naxis2 = it->naxis2; skyData->combinedImage[chip]->dataCurrent.swap(masterCombined->dataCurrent); skyData->getModeCombineImages(chip); staticImagesCombined[chip] = true; } omp_unset_lock(&backgroundLock); // PASS 2: if (twoPass) { sendBackgroundMessage("static", skyData->staticModelDone[chip], it->chipName, 2); maskObjectsInSkyImagesPass2_newParallel(skyData, scienceData, masterCombined, backgroundList, twoPass, dt, dmin, convolution, expFactor, chip, rescaleModel, threadID, "static"); // do this only once per chip omp_set_lock(&backgroundLock); // CHECK: must recalculate 2nd-pass static model (?) // also, in pass2_newparalell, must check for maskObjectsDonePass2 if (!staticImagesCombined[chip]) { skyData->combineImages_newParallel(chip, skyData->combinedImage[chip], backgroundList, nlow2, nhigh2, it->chipName, "static", dataSubDirName); skyData->getModeCombineImages(chip); } omp_unset_lock(&backgroundLock); } skyData->writeBackgroundModel_newParallel(chip, skyData->combinedImage[chip], "static", it->baseName, threadID, backgroundLock, staticImagesWritten[chip]); skyData->staticModelDone[chip] = true; it->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel, backExpListRescaleFactors); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); // DO NOT UNPROTECT MEMORY HERE (could be needed elsewhere) } #pragma omp atomic progress += progressStepSize; ++currentExposure[chip]; // In critical section because length of QString backexpList is variable, and Qvector is probably not thread safe because of this #pragma omp critical { // Join the number of exposures with the rescale factors QVector joinedList(maxCPU); numBackExpList[chip] = backExpList[chip]; } // L1 always contains the data before any modification, hence we do not need to create a backup copy. if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { it->makeBackgroundBackup(); // just a FITS file operation if necessary } scienceData->unprotectMemory(chip); skyData->unprotectMemory(chip); } } } //void Controller::processBackgroundDynamic(Data *scienceData, Data *skyData, const float &nimg, QVector &numBackExpList, // const QString &dt, const QString &dmin, const QString &expFactor, const QString &nlow1, // const QString &nhigh1, const QString &nlow2, const QString &nhigh2, // const bool &twoPass, const bool &convolution, const bool &rescaleModel, // const int &nGroups, const int &nLength, QVector &staticImagesWritten) void Controller::processBackgroundDynamic(Data *scienceData, Data *skyData, const float nimg, QVector &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QVector &staticImagesWritten) { // The following is needed for the new scheme QVector backExpList(maxCPU); QVector currentExposure(instData->numChips); // relevant only for LIRIS@WHT-type detectors QVector staticImagesCombined(instData->numChips); QVector combinedBackgroundImages(maxCPU); for (auto &it : backExpList) it = ""; for (auto &it : currentExposure) it = 0; for (auto &it : staticImagesCombined) it = false; for (auto &it : combinedBackgroundImages) it = nullptr; QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); QString dataSubDirName = scienceData->subDirName; #pragma omp parallel for num_threads(maxCPU backExpRescaleFactors.append("1.000; no rescaling when dividing model");) firstprivate(dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, backExpList, allMyImages, dataSubDirName) for (int k=0; ksuccessProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Modeling background ...", "image"); it->processingStatus->Background = false; it->setupBackgroundData_newParallel(scienceData->isTaskRepeated, backupDirName); // Put original flat-fielded data in dataBackupL1; internal lock // The list of background images. Each image has a flag whether it contributes to the model. No locking required QList backgroundList; if (!filterBackgroundList(chip, skyData, it, backExpList[threadID], backgroundList, nGroups, nLength, currentExposure[chip], "dynamic")) { continue; // cannot use break in OMP loop } // PASS 1: sendBackgroundMessage("dynamic", skyData, it->chipName, 1); maskObjectsInSkyImagesPass1_newParallel(skyData, scienceData, backgroundList, twoPass, dt, dmin, convolution, expFactor, threadID); MyImage *masterCombined = new MyImage(dirName, "dummy.fits", "", chip+1, skyData->mask->globalMask[chip], skyData->mask->isChipMasked[chip], &verbosity); skyData->combineImages_newParallel(chip, masterCombined, backgroundList, nlow1, nhigh1, it->chipName, "dynamic", dataSubDirName); skyData->getModeCombineImagesBackground(chip, masterCombined); masterCombined->naxis1 = it->naxis1; masterCombined->naxis2 = it->naxis2; combinedBackgroundImages[threadID] = masterCombined; // PASS 2: if (twoPass) { sendBackgroundMessage("dynamic", skyData, it->chipName, 2); maskObjectsInSkyImagesPass2_newParallel(skyData, scienceData, masterCombined, backgroundList, twoPass, dt, dmin, convolution, expFactor, chip, rescaleModel, threadID, "dynamic"); skyData->combineImages_newParallel(chip, combinedBackgroundImages[threadID], backgroundList, nlow2, nhigh2, it->chipName, "dynamic", dataSubDirName); skyData->getModeCombineImagesBackground(chip, combinedBackgroundImages[threadID]); } skyData->writeBackgroundModel_newParallel(chip, combinedBackgroundImages[threadID], "dynamic", it->baseName, threadID, backgroundLock, staticImagesWritten[chip]); it->applyBackgroundModel(combinedBackgroundImages[threadID], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); // DO NOT UNPROTECT MEMORY HERE (could be needed elsewhere) } #pragma omp atomic progress += progressStepSize; ++currentExposure[chip]; // In critical section because length of QString backexpList is variable, and Qvector is probably not thread safe because of this #pragma omp critical { numBackExpList[chip] = backExpList[chip]; } // L1 always contains the data before any modification, hence we do not need to create a backup copy. if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { it->makeBackgroundBackup(); backExpRescaleFactors.append("1.000; no rescaling when dividing model"); // just a FITS file operation if necessary } scienceData->unprotectMemory(chip); skyData->unprotectMemory(chip); } } } */ void Controller::maskObjectsInSkyImagesPass1(const int chip, Data *skyData, Data *scienceData, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor) { // Loop over the list of valid background images and mask the objects bool doSourceDetection = false; QVector thresholds = getBackgroundThresholds(0, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : skyData->myImageList[chip]) { if (!back->successProcessing) break; if (!back->useForBackground) continue; // that should never be the case because the backgroundlist contains 'valid' images, only, at this point // if (!back->useForBackground) { // back->unprotectMemory(); // TODO: check if possibly dangerous. Can we do this here? Or elsewhere? // continue; // } // reads from dataBackupL1; if not then from disk and creates backup in L1, measures the mode if not yet available back->setupBackgroundData(isTaskRepeated, backupDirName); // Already in memory if skyData == scienceData if (doSourceDetection && !twoPass && !back->objectMaskDonePass1) { // only detect if requested and not yet done; objectMaskDone set to false in skydata outside loops if (verbosity >= 2) emit messageAvailable(back->chipName + " : Detecting and masking sources ...", "image"); back->backgroundModel(256, "interpolate"); back->segmentImage(DT, DMIN, convolution, false); back->transferObjectsToMask(); back->maskExpand(expFactor, false); back->objectMaskDonePass1 = true; } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } void Controller::maskObjectsInSkyImagesPass2(const int chip, Data *skyData, Data *scienceData, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor, const bool rescaleModel) { bool doSourceDetection = false; QVector thresholds = getBackgroundThresholds(1, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : skyData->myImageList[chip]) { if (!back->successProcessing) break; if (!back->useForBackground) continue; if (doSourceDetection && !back->objectMaskDonePass2) { if (verbosity >= 2) emit messageAvailable(back->chipName + " : Detecting and masking sources ...", "image"); // Mask objects if not yet done for this sky (science) image // No masking has taken place in PASS 1 if we are in twopass mode! // Subtract 1st pass model: dataCurrent = dataBackupL1 - 1stPassModel back->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); // back->backgroundModelDone = false; // IMPORTANT, otherwise background model step will be skipped back->backgroundModel(256, "interpolate"); // create background model back->segmentImage(DT, DMIN, convolution, false); // detect sources (if requested), do not write seg image back->transferObjectsToMask(); // sets objectMaskDone to true back->maskExpand(expFactor, false); // expand the object mask (if requested) back->objectMaskDonePass2 = true; } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } bool Controller::setupBackgroundList(int chip, Data *skyData, const QString &chipName) { if (!successProcessing) return false; // First, collect all images of this chip, and reset their usability for background modeling to 'false' (or 'true' depending which ones is easier to code) for (auto &it : skyData->myImageList[chip]) { it->useForBackground = false; it->useForBackgroundSequence = true; it->useForBackgroundWindowed = false; it->useForBackgroundStars = true; } if (skyData->myImageList[chip].length() < 2) { emit messageAvailable(chipName + " : At least two images are required for background modeling.", "error"); emit criticalReceived(); successProcessing = false; return false; } return true; } bool Controller::filterBackgroundList(const int chip, Data *skyData, MyImage *it, QString &backExpList, const int nGroups, const int nLength, const int currentExposure, const QString mode) { if (!successProcessing) return false; if (!it->successProcessing) return false; selectImagesFromSequence(skyData->myImageList[chip], nGroups, nLength, currentExposure); // Update flag: Select every n-th image, only, if requested // for (auto &back : skyData->myImageList[chip]) qDebug() << back->baseName << back->useForBackgroundSequence; // qDebug() << ""; if (mode == "dynamic") selectImagesDynamically(skyData->myImageList[chip], it->mjdobs); // Update flag: dynamic or static mode else selectImagesStatically(skyData->myImageList[chip], it); // Already sets BADBACK flag if necessary // for (auto &back : skyData->myImageList[chip]) qDebug() << back->baseName << back->useForBackgroundSequence << back->useForBackgroundWindowed; // qDebug() << ""; flagImagesWithBrightStars(skyData->myImageList[chip]); // Update flag: Exclude images affected by bright stars if (!it->successProcessing) return false; // Leave if not sufficiently many images found for background modeling // Combine the flags from all three tests combineAllBackgroundUsabilityFlags(skyData->myImageList[chip]); // for (auto &back : skyData->myImageList[chip]) qDebug() << back->baseName << back->useForBackground; // qDebug() << ""; int nback = countBackgroundImages(skyData->myImageList[chip], it->chipName); QString outstring = it->chipName + " : " + QString::number(nback) + "
"; if (nback < 4) backExpList.append("" + outstring + ""); // color coding to highlight potentially poor images else backExpList.append(outstring); if (!successProcessing || nback < 2 || !it->successProcessing) { emit messageAvailable(it->chipName + " : No (or not sufficiently many) suitable background images found", "warning"); it->activeState = MyImage::BADBACK; it->successProcessing = false; return false; } return true; } /* void Controller::maskObjectsInSkyImagesPass1_newParallel(Data *skyData, Data *scienceData, const QList &backgroundList, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor, const int threadID) { // Loop over the list of valid background images and calculate the model bool doSourceDetection = false; QVector thresholds = getBackgroundThresholds(0, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : backgroundList) { if (!back->successProcessing) break; // if (!back->useForBackground) { // back->unprotectMemory(); // TODO: check if possibly dangerous. Can we do this here? Or elsewhere? // continue; // } // reads from dataBackupL1; if not then from disk and creates backup in L1, measures the mode if not yet available back->setupBackgroundData_newParallel(isTaskRepeated, backupDirName); // Already in memory if skyData == scienceData if (doSourceDetection && !twoPass) { // only detect if requested and not yet done previously; objectMaskDone set to false in skydata outside loops back->setObjectLock(true); if (!back->objectMaskDone) { back->backgroundModel(256, "interpolate"); back->segmentImage(DT, DMIN, convolution, false); back->transferObjectsToMask(); back->maskExpand(expFactor, false); } back->setObjectLock(false); } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } void Controller::maskObjectsInSkyImagesPass2_newParallel(Data *skyData, Data *scienceData, MyImage *combinedImage, const QList &backgroundList, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor, const int chip, const bool rescaleModel, const int threadID, const QString mode) { bool doSourceDetection = false; QVector thresholds = getBackgroundThresholds(1, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : backgroundList) { if (!back->successProcessing) break; if (!back->useForBackground) continue; if (doSourceDetection) { back->setObjectLock(true); // Mask objects if not yet done for this sky (science) image // No masking has taken place in PASS 1 if we are in twopass mode! // Subtract 1st pass model: dataCurrent = dataBackupL1 - 1stPassModel if (!back->objectMaskDone) { if (mode == "dynamic") back->applyBackgroundModel(combinedImage, cdw->ui->BACapplyComboBox->currentText(), rescaleModel); else back->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); // back->backgroundModelDone = false; // IMPORTANT, otherwise background model step will be skipped back->backgroundModel(256, "interpolate"); // create background model back->segmentImage(DT, DMIN, convolution, false); // detect sources (if requested), do not write seg image back->transferObjectsToMask(); // sets objectMaskDone to true back->maskExpand(expFactor, false); // expand the object mask (if requested) } back->setObjectLock(false); } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } */ void Controller::sendBackgroundMessage(const QString mode, const bool staticmodeldone, const QString basename, const int pass) { if (verbosity >= 0) { if ( (mode == "static" && !staticmodeldone) || mode == "dynamic") { if (pass == 1) emit messageAvailable(basename + " : Image combination 1st pass ...", "image"); if (pass == 2) emit messageAvailable(basename + " : Image combination 2nd pass ...", "image"); } } } // Select the 'windowSize' images that are closest in time to the targetMJD void Controller::selectImagesDynamically(const QList &backgroundList, const double &mjd_ref) { if (!successProcessing) return; if (verbosity == 3) emit messageAvailable("Entering dynamic image selection ...", "image"); QList> imageListAbs; // sorted with respect to fabs(mjd_diff) QList> imageListDiff; // sorted with respect to mjd_diff // Reset, and map data onto a list for (auto &it : backgroundList) { // qDebug() << qSetRealNumberPrecision(12) << it->baseName << it->mjdobs; imageListAbs.append(qMakePair(it,fabs(it->mjdobs-mjd_ref))); imageListDiff.append(qMakePair(it,it->mjdobs-mjd_ref)); } // Sort with respect to mjd difference std::sort(imageListAbs.begin(), imageListAbs.end(), QPairSecondComparer()); std::sort(imageListDiff.begin(), imageListDiff.end(), QPairSecondComparer()); // Mark the first 'windowSize' images, using fabs(mjd_diff), provided they passed the 'spread sequence' test int selected = 0; int windowSize = cdw->ui->BACwindowLineEdit->text().toInt(); if (windowSize > backgroundList.length()) { QString part1 = QString::number(windowSize); QString part2 = QString::number(backgroundList.length()); emit showMessageBox("Controller::WINDOWSIZE_TOO_LARGE", part1, part2); successProcessing = false; return; } // Here's the selection function for (auto &it : imageListAbs) { // Do not use the current image to contribute to its own background model (it->useForBackgroundWindowed remains 'false') if (it.second > 0.) { if (selected < windowSize && it.first->activeState == MyImage::ACTIVE && it.first->useForBackgroundSequence) { it.first->useForBackgroundWindowed = true; it.first->enteredBackgroundWindow = true; ++selected; } else { it.first->useForBackgroundWindowed = false; // redundant. Set to false by default when entering this function // free RAM if (it.first->enteredBackgroundWindow && !it.first->leftBackgroundWindow) { it.first->leftBackgroundWindow = true; it.first->releaseBackgroundMemoryBackgroundModel(); it.first->releaseAllDetectionMemory(); // if (minimizeMemoryUsage) { // it.first->freeAll(); // } } } } } // Check if there is a gap larger than the max gap size in the window QString maxGapString = cdw->ui->BACgapsizeLineEdit->text(); if (!maxGapString.isEmpty()) { int count = 0; double mjd_previous = 0.; bool gapViolated = false; double currentGap = 0.; double maxGap = maxGapString.toDouble() / 24.; // convert from hours to days (MJD) for (auto &it : imageListDiff) { if (it.first->useForBackgroundWindowed) { if (count == 0) { mjd_previous = it.first->mjdobs; ++count; } else { currentGap = it.first->mjdobs - mjd_previous; mjd_previous = it.first->mjdobs; ++count; if (currentGap > maxGap) { gapViolated = true; break; } } } } if (gapViolated) { QString part1 = QString::number(currentGap*24,'f',3); emit showMessageBox("Controller::GAP_DYNAMIC_FOUND", part1, maxGapString); successProcessing = false; } } QString minWindowSizeString = cdw->ui->BACminWindowLineEdit->text(); int minWindowSize; if (minWindowSizeString.isEmpty()) minWindowSize = windowSize; else minWindowSize = minWindowSizeString.toInt(); if (selected < minWindowSize) { QString part1 = QString::number(selected); QString part2 = QString::number(minWindowSize); emit showMessageBox("Controller::INSUFFICIENT_BACKGROUND_NUMBER", part1, part2); successProcessing = false; } } // Select the images that are closest in time to the targetMJD and within a valid block defined by gap sizes void Controller::selectImagesStatically(const QList &backgroundList, MyImage *scienceImage) { if (!successProcessing) return; if (!scienceImage->successProcessing) return; double mjd_ref = scienceImage->mjdobs; if (verbosity == 3) emit messageAvailable("Entering static image selection ...", "image"); QList> imageListDiff; // sorted with respect to mjd_diff // Reset, and map data onto a list for (auto &it : backgroundList) { // it->useForBackground = false; imageListDiff.append(qMakePair(it, it->mjdobs - mjd_ref)); } // Sort with respect to mjd difference std::sort(imageListDiff.begin(), imageListDiff.end(), QPairSecondComparer()); // Identify blocks (if a gap was defined) // Use a giant maxGap (longer than an observer's lifetime) if no gap was defined QString maxGapString = cdw->ui->BACgapsizeLineEdit->text(); double maxGap = 1e9; if (!maxGapString.isEmpty()) maxGap = maxGapString.toDouble() / 24.; int blockCount = 0; double mjd_previous = imageListDiff[0].first->mjdobs; for (auto &it : imageListDiff) { double currentGap = it.first->mjdobs - mjd_previous; if (currentGap > maxGap) ++blockCount; it.first->backgroundBlock = blockCount; mjd_previous = it.first->mjdobs; } // Decide which block is the best (if any) to correct the image with mjd_ref int scienceBlockId = -1; int nSky = imageListDiff.length(); for (int i=0; imjdobs; mjd_obs2 = imageListDiff[i+1].first->mjdobs; } else { mjd_obs1 = imageListDiff[i].first->mjdobs; mjd_obs2 = imageListDiff[i-1].first->mjdobs; } double d1 = fabs(mjd_ref - mjd_obs1); double d2 = fabs(mjd_ref - mjd_obs2); int blockID1; int blockID2; if (ibackgroundBlock; blockID2 = imageListDiff[i+1].first->backgroundBlock; } else { blockID1 = imageListDiff[i].first->backgroundBlock; blockID2 = imageListDiff[i-1].first->backgroundBlock; } // Cases where a science exposure has a valid sky block if (i==0 && mjd_ref < mjd_obs1 && d1 < maxGap) scienceBlockId = blockID1; // image before first sky exposure if (i==nSky-1 && mjd_ref > mjd_obs1 && d1 < maxGap) scienceBlockId = blockID1; // image after last sky exposure if (mjd_ref == mjd_obs1) scienceBlockId = blockID1; // image identical to sky image if (scienceBlockId != -1) break; // Leave if matching block was found if (i==nSky-1) break; // stay within bounds for mjd_obs2, d2, and blockID2 // Image must have been taken within the sky sequence // science image between two sky exposures // if (mjd_ref > mjd_obs1 && mjd_ref < mjd_obs2) { // excluding the science image from the model if (mjd_ref >= mjd_obs1 && mjd_ref <= mjd_obs2) { // including the science image from the model // within a block or between blocks if (blockID1 == blockID2) scienceBlockId = blockID1; else { // Assign the closer block, if within maxGap if (d1 <= d2 && d1 < maxGap) scienceBlockId = blockID1; if (d2 < d1 && d2 < maxGap) scienceBlockId = blockID2; } } if (scienceBlockId != -1) break; } // Set the flag for all sky exposures that have the same block ID as the science exposure, and passed the 'spread sequence' test // Remember, imageListDiff just contains pointers into backgroundList, so we // are indeed updating the flags in the backgroundList int countSky = 0; // the number of sky images used for correction for (auto &it : imageListDiff) { if (it.first->backgroundBlock == scienceBlockId && it.first->activeState == MyImage::ACTIVE && it.first->useForBackgroundSequence) { it.first->useForBackgroundWindowed = true; ++countSky; } } // Always use all images for the static model: comment out the following /* // Do not use the current image to contribute to its own background model for (auto &it : imageListDiff) { if (it.second == 0.) { it.first->useForBackgroundWindowed = false; --countSky; } } */ if (scienceBlockId == -1) { emit messageAvailable(scienceImage->chipName + " : Could not identify suitable sky images. Image deactivated.", "warning"); emit warningReceived(); scienceImage->activeState = MyImage::BADBACK; scienceImage->successProcessing = false; if (scienceImage->imageOnDrive) { moveFile(scienceImage->baseName+".fits", scienceImage->path, scienceImage->path+"/inactive/badBackground/"); scienceImage->path = scienceImage->path+"/inactive/badBackground/"; scienceImage->emitModelUpdateNeeded(); } return; } if (countSky < 3) { emit messageAvailable(scienceImage->chipName + " : Less than three images found for background modeling. Image deactivated.", "warning"); emit warningReceived(); scienceImage->activeState = MyImage::BADBACK; scienceImage->successProcessing = false; if (scienceImage->imageOnDrive) { moveFile(scienceImage->baseName+".fits", scienceImage->path, scienceImage->path+"/inactive/badBackground/"); scienceImage->path = scienceImage->path+"/inactive/badBackground/"; scienceImage->emitModelUpdateNeeded(); } return; } successProcessing = true; } // If several exposures were taken at the same dither position before an offset, // then sometimes the first and perhaps 2nd image must be corrected separately // from all other first or second exposures. void Controller::selectImagesFromSequence(QList &backgroundList, const int &nGroups, const int &nLength, const int ¤tExp) { if (!successProcessing) return; // Nothing to be done if (nGroups == 0 || nLength == 0) return; // returning with all flags set to 'true', i.e. no contraints // set all flags to false for a start for (auto &it : backgroundList) { it->useForBackgroundSequence = false; } // To which group does the current image belong int groupReference = currentExp % nLength; if (groupReference >= nGroups) groupReference = nGroups - 1; // Assign group numbers to background images int group = 0; int count = 0; for (auto &it : backgroundList) { if (group == groupReference) { it->useForBackgroundSequence = true; // image usable for background modeling } // qDebug() << it->chipName << group << count << groupReference << it->useForBackground; // qDebug() << "AAA" << it->chipName << group << count << groupReference << it->useForBackgroundSequence << currentExp; if (group < nGroups-1) ++group; ++count; if (count == nLength) { count = 0; group = 0; } } // Keep only background images that belong to the same group as the science exposure /* QList::iterator it = backgroundList.begin(); while (it != backgroundList.end()) { if (! (*it)->useForBackground) it = backgroundList.erase(it); else ++it; } */ /* for (auto &it : backgroundList) { qDebug() << it->chipName; } qDebug() << " " ; */ } // Obtain a list of bright stars from the UCAC catalog. // This is done before we enter the big loops that process the images (because we want to retrieve it only once) void Controller::retrieveBrightStars(Data *skyData, QList> &brightStarList) { // Leave if not requested QString brightMag = cdw->ui->BACmagLineEdit->text(); if (brightMag.isEmpty()) return; QString mag = ""; QString refcat = ""; if (instData->type == "OPT") { refcat = "UCAC5"; mag = "Rmag"; } else { refcat = "2MASS"; mag = "Hmag"; } emit messageAvailable("Retrieving stars brighter than "+mag+" = "+brightMag+" from "+refcat+" ...", "controller"); skyData->getPointingCharacteristics(); Query *query = new Query(&verbosity); // connect(query, &Query::bulkMotionObtained, cdw, &ConfDockWidget::updateGaiaBulkMotion); connect(query, &Query::messageAvailable, mainGUI, &MainWindow::processMessage); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); query->scienceData = skyData; query->mainDirName = mainDirName; query->refcatName = refcat; query->alpha_manual = QString::number(skyData->RAcenter, 'f', 4); // the query uses QStrings because we execute vizquery.py query->delta_manual = QString::number(skyData->DECcenter, 'f', 4); query->radius_manual = QString::number(skyData->searchRadius, 'f', 2); query->magLimit_string = cdw->ui->BACmagLineEdit->text(); query->maxProperMotion_string = cdw->ui->ARCmaxpmLineEdit->text(); query->doBrightStarQueryFromWeb(); brightStarList.reserve(query->numSources); for (long i=0; inumSources; ++i) { QVector star; star << query->ra_out[i]; star << query->de_out[i]; star << query->mag1_out[i]; brightStarList << star; } QString numstars = QString::number(query->numSources) + " bright stars found "; QString pointing = "within r = "+query->radius_manual+"'"+" of RA = "+query->alpha_manual +", DEC = "+query->delta_manual; emit messageAvailable(numstars+pointing, "controller"); delete query; query = nullptr; } bool Controller::idChipsWithBrightStars(Data *skyData, QList> &brightStarList) { QString safetyDistanceString = cdw->ui->BACdistLineEdit->text(); QString magLimit = cdw->ui->BACmagLineEdit->text(); if (magLimit.isEmpty()) return true; float safetyDistance = safetyDistanceString.toFloat(); int numImagesAffected = 0; QString imagesAffected = ""; QVector numChipsRejected(instData->numChips, 0); /* // TODO: when collapsing loops, make sure each chip has the same number of exposures #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { for (auto &it : skyData->myImageList[chip]) { it->loadHeader(); it->checkBrightStars(brightStarList, safetyDistance, instData->pixscale); if (it->hasBrightStars) { ++numImagesAffected; ++numChipsRejected[chip]; imagesAffected.append(it->baseName + "
"); } } } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, skyData); #pragma omp parallel for num_threads(maxCPU) for (int k=0; kchipNumber - 1; if (instData->badChips.contains(chip)) continue; it->loadHeader(); it->checkBrightStars(brightStarList, safetyDistance, instData->pixscale); if (it->hasBrightStars) { #pragma omp critical { ++numImagesAffected; ++numChipsRejected[chip]; imagesAffected.append(it->chipName + "
"); } } } if (numImagesAffected > 0) { emit messageAvailable("Excluding "+QString::number(numImagesAffected) + " images from entering the background model due to bright stars:", "controller"); emit messageAvailable(imagesAffected, "ignore"); } bool critical = false; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; int chipsAvailable = skyData->myImageList[chip].length() - numChipsRejected[chip]; if (chipsAvailable == 0) { emit messageAvailable("Chip "+QString::number(chip+1) + " : No images available for background modeling after bright star filtering.", "error"); critical = true; } else if (chipsAvailable == 1) { emit messageAvailable("Chip "+QString::number(chip+1) + " : Only 1 image available for background modeling after bright star filtering.", "error"); critical = true; } else if (chipsAvailable <= 4) { emit messageAvailable("Chip "+QString::number(chip+1) + " : Only " + QString::number(chipsAvailable) + " images available for background modeling after bright star filtering,
"+ "expecting poor performance. Ideally, at least 5 images should remain.", "warning"); } } if (critical) { criticalReceived(); successProcessing = false; return false; } else return true; } void Controller::flagImagesWithBrightStars(const QList &backgroundList) { for (auto &it : backgroundList) { if (it->hasBrightStars) it->useForBackgroundStars = false; } } // Set an image as usable for background correction only if everything holds void Controller::combineAllBackgroundUsabilityFlags(const QList &backgroundList) { for (auto &it : backgroundList) { if (it->useForBackgroundSequence && it->useForBackgroundWindowed && it->useForBackgroundStars) { it->useForBackground = true; } } } int Controller::countBackgroundImages(QList list, QString baseName) { if (!successProcessing) return 0; int count = 0; for (auto &it : list) { if (it->useForBackground) ++count; } if (count < 2) { emit messageAvailable(baseName + " : Less than two images (" + QString::number(count) + ") were found to create the background model.", "warning"); warningReceived(); successProcessing = false; return count; } if (count < 4) { emit messageAvailable(baseName + " : Only " + QString::number(count) + " images contribute to the background model, expecting poor performance.", "warning"); warningReceived(); return count; } return count; } THELI-3.1.3/src/processingInternal/processingCalibration.cc000066400000000000000000001037751417631501300236740ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include #include #include #include void Controller::taskInternalProcessbias() { if (!successProcessing) return; QString biasDir = instructions.split(" ").at(1); Data *biasData = getData(DT_BIAS, biasDir); if (biasData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(biasData)) return; QString min = cdw->ui->biasMinLineEdit->text(); QString max = cdw->ui->biasMaxLineEdit->text(); QString nlow = cdw->ui->biasNlowLineEdit->text(); QString nhigh = cdw->ui->biasNhighLineEdit->text(); currentData = biasData; currentDirName = biasDir; memoryDecideDeletableStatus(biasData, false); pushBeginMessage(taskBasename, biasDir); pushConfigProcessbias(); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // The biasData imagelist is empty after splitting because the Data constructor only looks for *_chip.fits, not for raw files. // if (biasData->myImageList[instData->validChip].isEmpty()) { // biasData->populate(""); // emit populateMemoryView(); // } getNumberOfActiveImages(biasData); // Release as much memory as maximally necessary float nimg = biasData->myImageList[instData->validChip].length() + 1; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed biasData->protectMemory(); QString dataDirName = biasData->dirName; // copies for thread safety QString dataSubDirName = biasData->subDirName; // copies for thread safety QString dataDataType = biasData->dataType; doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips // NOTE: QString is not threadsafe, must create copies for threads! // NOTE: a 'bad' chip will 'continue', but openMP waits until at least one of the other threads has finished #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = biasData->myImageList[chip].length() + 1; // The number of images we must keep in memory // Release memory cannot touch any dataCurrent read by MyImage::readImage, because we 'protected' it outside the loop. // Initially, this call might not do anything because everything is protected. On systems with less RAM than // a single exposure this might cause swapping. We test for this elsewhere (when loading images). releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); for (auto &it : biasData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; it->setupCalibDataInMemory(false, true, false); // Read image (if not already in memory), do not create backup, do get mode it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); // Flag the image if its mode is outside a user-provided acceptable range #pragma omp atomic progress += progressHalfStepSize; } if (biasData->myImageList[chip].length() == 0) { biasData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+biasData->subDirName, "error"); emit criticalReceived(); continue; } biasData->combineImagesCalib(chip, combineBias_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); // Combine images biasData->getModeCombineImages(chip); biasData->writeCombinedImage(chip); biasData->unprotectMemory(chip); if (minimizeMemoryUsage) { for (auto &it : biasData->myImageList[chip]) { it->freeAll(); } } biasData->combinedImage[chip]->emitModelUpdateNeeded(); if (!biasData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; } if (!successProcessing) { emit progressUpdate(100); return; } biasData->reportModeCombineImages(); checkSuccessProcessing(biasData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, biasDir); } } void Controller::taskInternalProcessdark() { if (!successProcessing) return; QString darkDir = instructions.split(" ").at(1); Data *darkData = getData(DT_DARK, darkDir); if (darkData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(darkData)) return; QString min = cdw->ui->darkMinLineEdit->text(); QString max = cdw->ui->darkMaxLineEdit->text(); QString nlow = cdw->ui->darkNlowLineEdit->text(); QString nhigh = cdw->ui->darkNhighLineEdit->text(); currentData = darkData; currentDirName = darkDir; memoryDecideDeletableStatus(darkData, false); pushBeginMessage(taskBasename, darkDir); pushConfigProcessdark(); getNumberOfActiveImages(darkData); // // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (darkData->myImageList[instData->validChip].isEmpty()) { // darkData->populate(""); // emit populateMemoryView(); // } // Release as much memory as maximally necessary float nimg = darkData->myImageList[instData->validChip].length() + 1; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed darkData->protectMemory(); QString dataDirName = darkData->dirName; // copies for thread safety QString dataSubDirName = darkData->subDirName; // copies for thread safety QString dataDataType = darkData->dataType; doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = darkData->myImageList[chip].length() + 1; // The number of images we must keep in memory releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); for (auto &it : darkData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; it->setupCalibDataInMemory(false, true, false); it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); #pragma omp atomic progress += progressHalfStepSize; } if (darkData->myImageList[chip].length() == 0) { darkData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+darkData->subDirName, "error"); emit criticalReceived(); continue; } darkData->combineImagesCalib(chip, combineDark_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); darkData->getModeCombineImages(chip); darkData->writeCombinedImage(chip); darkData->unprotectMemory(chip); if (minimizeMemoryUsage) { for (auto &it : darkData->myImageList[chip]) it->freeAll(); } if (!darkData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; } if (!successProcessing) { emit progressUpdate(100); return; } darkData->reportModeCombineImages(); checkSuccessProcessing(darkData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, darkDir); } } void Controller::taskInternalProcessflatoff() { QString flatoffDir = instructions.split(" ").at(1); Data *flatoffData = getData(DT_FLATOFF, flatoffDir); if (flatoffData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(flatoffData)) return; QString min = cdw->ui->flatoffMinLineEdit->text(); QString max = cdw->ui->flatoffMaxLineEdit->text(); QString nlow = cdw->ui->flatoffNlowLineEdit->text(); QString nhigh = cdw->ui->flatoffNhighLineEdit->text(); currentData = flatoffData; currentDirName = flatoffDir; memoryDecideDeletableStatus(flatoffData, false); pushBeginMessage(taskBasename, flatoffDir); pushConfigProcessflatoff(); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (flatoffData->myImageList[instData->validChip].isEmpty()) { // flatoffData->populate(""); // emit populateMemoryView(); // } getNumberOfActiveImages(flatoffData); // Release as much memory as maximally necessary float nimg = flatoffData->myImageList[instData->validChip].length() + 1; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed flatoffData->protectMemory(); QString dataDirName = flatoffData->dirName; // copies for thread safety QString dataSubDirName = flatoffData->subDirName; // copies for thread safety QString dataDataType = flatoffData->dataType; doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = flatoffData->myImageList[chip].length() + 1; // The number of images we must keep in memory releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); for (auto &it : flatoffData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; it->setupCalibDataInMemory(false, true, false); it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); #pragma omp atomic progress += progressHalfStepSize; } if (flatoffData->myImageList[chip].length() == 0) { flatoffData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+flatoffData->subDirName, "error"); emit criticalReceived(); continue; } flatoffData->combineImagesCalib(chip, combineFlatoff_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); flatoffData->getModeCombineImages(chip); flatoffData->writeCombinedImage(chip); flatoffData->unprotectMemory(chip); if (minimizeMemoryUsage) { for (auto &it : flatoffData->myImageList[chip]) it->freeAll(); } if (!flatoffData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; } if (!successProcessing) { emit progressUpdate(100); return; } flatoffData->reportModeCombineImages(); checkSuccessProcessing(flatoffData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, flatoffDir); } } void Controller::taskInternalProcessflat() { QString flatDir = instructions.split(" ").at(1); QString biasDir = instructions.split(" ").at(2); Data *flatData = getData(DT_FLAT, flatDir); if (flatData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(flatData)) return; Data *biasData = nullptr; QString min = cdw->ui->flatMinLineEdit->text(); QString max = cdw->ui->flatMaxLineEdit->text(); QString nlow = cdw->ui->flatNlowLineEdit->text(); QString nhigh = cdw->ui->flatNhighLineEdit->text(); currentData = flatData; currentDirName = flatDir; pushBeginMessage(taskBasename, flatDir); pushConfigProcessflat(); // flatoff, or bias, or no bias; we call it "bias" for simplicity if (!mainGUI->ui->setupFlatoffLineEdit->text().isEmpty()) { biasData = getData(DT_FLATOFF, biasDir); } else if (!mainGUI->ui->setupBiasLineEdit->text().isEmpty()) { biasData = getData(DT_BIAS, biasDir); } // Must rescale flats when combining them flatData->rescaleFlag = true; if (biasData != nullptr && !biasData->hasAllMasterCalibs) { QString part1 = biasData->dirName+"/"+biasData->subDirName+"_*.fits\n"; emit showMessageBox("Controller::MASTER_FLATOFF_NOT_FOUND", part1, ""); successProcessing = false; return; } // Check if all flats have the same filter // TODO: imageInfo.filter is not yet populated at this point! // Actually, as far as I can see it never gets populated at all! /* QStringList filters = flatData->imageInfo.filter; filters.removeDuplicates(); if (filters.length() > 1) { QString filtersJoined = filters.join(' '); QMessageBox::warning(this, tr("Non-identical filters found."), tr("The flat-field directory ")+flatData->dirName+tr(" contains several different filters:\n")+ filtersJoined+"\n"+ tr("You must first remove the unwanted images."), QMessageBox::Ok); return; } QString filter = filters[0]; */ // Retrieve nonlinearity information (checks internally if available, otherwise returns empty list) QList> nonlinearityCoefficients; if (cdw->ui->nonlinearityCheckBox->isChecked()) { nonlinearityCoefficients = getNonlinearityCoefficients(); } memoryDecideDeletableStatus(flatData, false); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (flatData->myImageList[instData->validChip].isEmpty()) { // flatData->populate(""); // emit populateMemoryView(); // } getNumberOfActiveImages(flatData); // Release as much memory as maximally necessary float nimg = flatData->myImageList[instData->validChip].length() + 2; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed flatData->protectMemory(); QString dataDirName = flatData->dirName; // copies for thread safety QString dataSubDirName = flatData->subDirName; // copies for thread safety QString dataDataType = flatData->dataType; QString biasDataType; if (biasData != nullptr) biasDataType = biasData->dataType; if (biasData != nullptr) biasData->protectMemory(); doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = flatData->myImageList[chip].length() + 2; // The number of images we must keep in memory releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); QString message = ""; if (biasData != nullptr) { biasData->loadCombinedImage(chip); message = biasData->subDirName; } for (auto &it : flatData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; if (verbosity >= 0 && !message.isEmpty()) emit messageAvailable(it->chipName + " : Correcting with "+message+"_"+QString::number(chip+1)+".fits", "image"); // careful with the booleans, they make sure the data is correctly reread from disk or memory if task is repeated it->setupCalibDataInMemory(true, true, true); // read from backupL1, if not then from disk. Makes backup copy if not yet done it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); // Must set mode flags before subtracting dark component (flatoffs can have really high levels in NIR data) if (biasData != nullptr && biasData->successProcessing) { // cannot pass nullptr to subtractBias() // it->subtractBias(ref, biasDataType); it->subtractBias(biasData->combinedImage[chip], biasDataType); // it->subtractBias(biasData->combinedImage[chip]->dataCurrent, biasDataType); it->skyValue -= biasData->combinedImage[chip]->skyValue; it->saturationValue -= biasData->combinedImage[chip]->skyValue; } // it->getMode(true); // it->setModeFlag(min, max); if (!it->successProcessing) flatData->successProcessing = false; // does not need to be threadsafe # pragma omp atomic progress += progressHalfStepSize; } if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData->myImageList[chip].length() == 0) { flatData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+flatData->subDirName, "error"); emit criticalReceived(); continue; } flatData->combineImagesCalib(chip, combineFlat_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); // Remove Bayer intensity variations within a 2x2 superpixel if (!instData->bayer.isEmpty()) equalizeBayerFlat(flatData->combinedImage[chip]); flatData->getModeCombineImages(chip); // Individual images may be released; must keep master calib for further below flatData->memorySetDeletable(chip, "dataCurrent", true); for (auto &it : flatData->myImageList[chip]) it->freeData("dataCurrent"); // Bias subtracted pixels, not needed anymore flatData->memorySetDeletable(chip, "dataBackupL1", true); if (minimizeMemoryUsage) { for (auto &it : flatData->myImageList[chip]) it->freeAll(); if (biasData != nullptr) biasData->combinedImage[chip]->freeAll(); } if (!flatData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; // Apply illumination correction (if available, e.g. for DECam; does nothing if not available) // TODO: can be uncommented once the filter is known (see commented block above) // flatData->combinedImage[chip]->illuminationCorrection(chip, thelidir, instData->name, filter); } if (!successProcessing) { emit progressUpdate(100); return; } // Obtain gain normalizations. Must be done once all images have been combined. flatData->getGainNormalization(); // Normalize flats to one. Gain corrections are stored in member variable for later use #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; flatData->combinedImage[chip]->normalizeFlat(); flatData->combinedImage[chip]->applyMask(); flatData->writeCombinedImage(chip); flatData->unprotectMemory(chip); } flatData->reportModeCombineImages(); checkSuccessProcessing(flatData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, flatDir); } } void Controller::taskInternalProcessscience() { QString scienceDir = instructions.split(" ").at(1); QString biasDir = instructions.split(" ").at(2); QString flatDir = instructions.split(" ").at(3); QString scienceMode = instructions.split(" ").at(4); Data *scienceData; if (scienceMode == "theli_DT_SCIENCE") scienceData = getData(DT_SCIENCE, scienceDir); else if (scienceMode == "theli_DT_SKY") scienceData = getData(DT_SKY, scienceDir); else if (scienceMode == "theli_DT_STANDARD") scienceData = getData(DT_STANDARD, scienceDir); else { return; } if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; Data *biasData = nullptr; // Can also point to a dark Data *flatData = nullptr; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); // Link with the correct bias data, if any; dark preferred over bias // I have to select dark / bias again even though it is done in tasks.cc already if (!mainGUI->ui->setupDarkLineEdit->text().isEmpty()) { biasData = getData(DT_DARK, biasDir); } else if (!mainGUI->ui->setupBiasLineEdit->text().isEmpty()) { biasData = getData(DT_BIAS, biasDir); } // Same for the flat if (!mainGUI->ui->setupFlatLineEdit->text().isEmpty()) { flatData = getData(DT_FLAT, flatDir); } if (biasData == nullptr && flatData == nullptr) { emit messageAvailable("No Bias / Dark or Flat calibrators defined. Nothing will be done.", "warning"); return; } // Check if calib data exist (at least chip 1) if (biasData != nullptr && !biasData->hasAllMasterCalibs) { QString part1 = biasData->dirName+"/"+biasData->subDirName+"_*.fits\n"; emit showMessageBox("Controller::MASTER_BIAS_NOT_FOUND", part1, ""); successProcessing = false; return; } if (flatData != nullptr && !flatData->hasAllMasterCalibs) { QString part1 = flatData->dirName+"/"+flatData->subDirName+"_*.fits\n"; emit showMessageBox("Controller::MASTER_FLAT_NOT_FOUND", part1, ""); successProcessing = false; return; } memoryDecideDeletableStatus(scienceData, false); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (scienceData->myImageList[instData->validChip].isEmpty()) { // scienceData->populate(""); // emit populateMemoryView(); // } // Loop over all chips backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; getNumberOfActiveImages(scienceData); scienceData->bayerList.clear(); scienceData->bayerList.resize(instData->numChips); QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); QVector numProcessedImages; numProcessedImages.fill(0, instData->numChips); // Release as much memory as maximally necessary float nimg; if (instData->bayer.isEmpty()) nimg = 4; // old, new, bias, flat else nimg = 6; // old, 3 new, bias, flat releaseMemory(nimg*instData->storage*maxCPU, 1); // Protect the rest, will be unprotected as needed scienceData->protectMemory(); if (biasData != nullptr) biasData->protectMemory(); if (flatData != nullptr) flatData->protectMemory(); QString dataDirName = scienceData->dirName; // copies for thread safety QString biasDataType; if (biasData != nullptr) biasDataType = biasData->dataType; // get rid of bad detectors, should they still be here for (int chip=0; chipnumChips; ++chip) { if (!instData->badChips.contains(chip)) continue; // skip good detectors for (auto &it : scienceData->myImageList[chip]) { if (it->imageOnDrive) { // delete FITS file for bad detectors (if still present after splitting) so they cannot interfere deleteFile(it->baseName+".fits", it->path); it->imageOnDrive = false; it->activeState = MyImage::DELETED; } } } if (instData->bayer.isEmpty()) doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); else { scienceData->currentlyDebayering = true; doDataFitInRAM(4*numMyImages*instData->numUsedChips, instData->storage); } if (instData->bayer.isEmpty()) { QStringList filters; for (auto &it : allMyImages) { filters.append(it->filter); } filters.removeDuplicates(); if (filters.length() > 1) { QString filtersJoined = filters.join(", "); emit messageAvailable("Files with different FILTER keywords found in "+scienceData->dirName+" :", "error"); emit messageAvailable(filtersJoined, "error"); emit warningReceived(); return; } } // Must keep track of memory consumption scienceData->bayerList.clear(); scienceData->bayerList.resize(instData->numChips); #pragma omp parallel for num_threads(maxCPU) firstprivate(dataDirName, biasDataType) for (int k=0; kchipNumber - 1; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; if (instData->badChips.contains(chip)) continue; // redundant. Image not even in allMyImages[k]; releaseMemory(nimg*instData->storage, maxCPU); // Don't remember why we need a lock here. I think it had to do with the headers. Will crash otherwise // TODO: probably not needed anymore with latest memory scheme QString message; // #pragma omp critical // { if (biasData != nullptr) { biasData->loadCombinedImage(chip); // skipped if already in memory message.append(biasData->subDirName); } if (flatData != nullptr) { flatData->loadCombinedImage(chip); // skipped if already in memory if (message.isEmpty()) message.append(flatData->subDirName); else message.append(" and " + flatData->subDirName); } // } if (verbosity >= 0) { if (!message.isEmpty() && instData->bayer.isEmpty()) emit messageAvailable(it->chipName + " : Correcting with "+message, "image"); if (!message.isEmpty() && !instData->bayer.isEmpty()) emit messageAvailable(it->chipName + " : Correcting with "+message+", debayering", "image"); if (message.isEmpty() && !instData->bayer.isEmpty()) emit messageAvailable(it->chipName + " : Debayering", "image"); } it->processingStatus->Processscience = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); it->checkCorrectMaskSize(instData); if (!it->successProcessing) { abortProcess = true; continue; } // TODO: check if we can just pass the data structure and chip number, // and test internally for nullptr and 'successProcessing'. // Then the "if" could go away if (biasData != nullptr && biasData->successProcessing) { it->subtractBias(biasData->combinedImage[chip], biasDataType); } if (flatData != nullptr && flatData->successProcessing) { it->divideFlat(flatData->combinedImage[chip]); } it->bitpix = -32; // so that mode calculations later on use the right algorithm // Without Bayer pattern if (instData->bayer.isEmpty()) { it->getMode(true); it->applyMask(); it->backupOrigHeader(chip); // Write out the zero order solution (before everything is kept in memory). This requires a FITS file updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } } } else { // Create 3 new MyImages for R, G, and B MyImage *debayerB = new MyImage(dataDirName, it->baseName, "P", chip+1, mask->globalMask[chip], &verbosity); MyImage *debayerG = new MyImage(dataDirName, it->baseName, "P", chip+1, mask->globalMask[chip], &verbosity); MyImage *debayerR = new MyImage(dataDirName, it->baseName, "P", chip+1, mask->globalMask[chip], &verbosity); debayer(chip, it, debayerB, debayerG, debayerR); it->unprotectMemory(); it->freeAll(); #pragma omp critical { // The order in which we insert the images here is important for data::writeGlobalWeights()! scienceData->bayerList[chip] << debayerB << debayerG << debayerR; } QList list; // Contains the current 3 debayered images list << debayerB << debayerG << debayerR; for (auto &it_deb: list) { if (abortProcess) break; connect(it_deb, &MyImage::modelUpdateNeeded, scienceData, &Data::modelUpdateReceiver); connect(it_deb, &MyImage::critical, this, &Controller::criticalReceived); connect(it_deb, &MyImage::warning, this, &Controller::warningReceived); connect(it_deb, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); connect(it_deb, &MyImage::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); it_deb->getMode(true); it_deb->applyMask(); it_deb->backupOrigHeader(chip); it_deb->imageInMemory = true; it_deb->backupL1InMemory = true; it_deb->processingStatus->HDUreformat = true; updateImageAndData(it_deb, scienceData); // Must provide filter string explicitly (and therefore also the full path and file name. // Always store debayered images // it->writeImageDebayer(it->path + "/" + it->chipName + "PA.fits", it->filter, it->exptime, it->mjdobs); it_deb->writeImageDebayer(); it_deb->unprotectMemory(); if (minimizeMemoryUsage) { it_deb->freeAll(); } } } #pragma omp atomic progress += progressStepSize; ++numProcessedImages[chip]; if ((minimizeMemoryUsage && instData->numChips > 1) || numProcessedImages[chip] == numMyImages/instData->numUsedChips) { // all images of this chip have been processed, and the calib data can be set deletable if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData != nullptr) flatData->unprotectMemory(chip); } } // Clear memory from pre-debayered data if (!instData->bayer.isEmpty()) { for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { it->freeAll(); } } } for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; // Update image list; remove bayer images, insert debayered images if (!instData->bayer.isEmpty()) { scienceData->repopulate(chip, scienceData->bayerList[chip]); emit populateMemoryView(); } /* if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); // qDebug() << "taskInternalProcessscience():" << scienceData->successProcessing << instData->bayer; if (instData->bayer != "Y") it->makeDriveBackup("P_IMAGES", statusOld); // scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } */ // Double tapping ... if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData != nullptr) flatData->unprotectMemory(chip); if (minimizeMemoryUsage) { if (biasData != nullptr) biasData->releaseAllMemory(); if (flatData != nullptr) flatData->releaseAllMemory(); } } if (!instData->bayer.isEmpty()) scienceData->currentlyDebayering = false; scienceData->bayerList.clear(); checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { scienceData->processingStatus->Processscience = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header // pushEndMessage(taskBasename, scienceDir); } } THELI-3.1.3/src/processingInternal/processingCoadd.cc000066400000000000000000001445731417631501300224600ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/swarpfilter.h" #include "../tools/fitting.h" #include "../tools/fileprogresscounter.h" #include "ui_confdockwidget.h" #include "../threading/scampworker.h" #include "../readmes/swarpreadme.h" #include "../tools/imagequality.h" #include "unistd.h" // To query max number of open files #include #include #include #include #include #include #include #include void Controller::taskInternalCoaddition() { coaddScienceDir = instructions.split(" ").at(1); QString filterArg = instructions.split(" ").at(2); coaddScienceData = getData(DT_SCIENCE, coaddScienceDir); if (coaddScienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(coaddScienceData)) return; currentData = coaddScienceData; currentDirName = coaddScienceDir; // Initialise, so we always have the correct values even when the coaddition is repeated several times coaddTexptime = 0.; coaddSkyvalue = 0.; coaddFilter = ""; coaddGain = 0.; mjdStart = 0.; mjdEnd = 0.; mjdMedian = 0.; // If coming here right after launch: // #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { for (auto &it : coaddScienceData->myImageList[chip]) { it->loadHeader(); } } coaddScienceData->checkModeIsPresent(); memoryDecideDeletableStatus(coaddScienceData, false); QString coaddSubDir = "coadd_"+filterArg; QString coaddUniqueID = cdw->ui->COAuniqueidLineEdit->text(); if (!coaddUniqueID.isEmpty()) coaddSubDir.append("_"+coaddUniqueID); coaddDirName = mainDirName + "/" + coaddScienceDir + "/" + coaddSubDir; QString headerDirName = mainDirName + "/" + coaddScienceDir + "/headers/"; if (!coaddScienceData->hasMatchingPartnerFiles(headerDirName, ".head")) return; // if all chips are stacked, make sure the reference point is within the covered area. // If selected chips are present, then the user might want the same ref coords for all chip stacks, which might be outside if (cdw->ui->COAchipsLineEdit->text().isEmpty()) { if (!coaddScienceData->doesCoaddContainRaDec(cdw->ui->COAraLineEdit->text(), cdw->ui->COAdecLineEdit->text())) { emit showMessageBox("Controller::POOR_COORD", cdw->ui->COAraLineEdit->text(), cdw->ui->COAdecLineEdit->text()); return; } } // qDebug() << "taskInternalCoaddition() : " << filterArg; // TODO // The following is very fast and does not need a parallel loop on top. getMinimumSaturationValue(); // The various coadd tasks are daisy-chained through signals and slots coaddSmoothEdge(); QTest::qWait(1000); coaddPrepare(filterArg); // entry point to daisy chain } void Controller::coaddSmoothEdge() { if (!successProcessing) return; QString edgeString = cdw->ui->COAedgesmoothingLineEdit->text(); if (edgeString.isEmpty()) return; float edge = edgeString.toFloat(); bool roundEdge = true; pushBeginMessage("CoaddSmoothWeights", coaddScienceData->subDirName); getNumberOfActiveImages(coaddScienceData); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : coaddScienceData->myImageList[chip]) { emit messageAvailable(it->baseName + " : Smoothing weight edge ...", "controller"); it->readWeight(); it->roundEdgeOfWeight(edge, roundEdge); it->writeWeightSmoothed(mainDirName+ "/WEIGHTS/" + it->chipName + ".weightsmooth.fits"); it->weightName = it->chipName + ".weight"; QVector().swap(it->dataWeightSmooth); // immediately release the memory incrementProgress(); } } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, coaddScienceData); progressStepSize = 100. / float(numMyImages); float nimg = 2; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); coaddScienceData->protectMemory(); #pragma omp parallel for num_threads(maxCPU) firstprivate(mainDirName) for (int k=0; kstorage, maxCPU); auto &it = allMyImages[k]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; emit messageAvailable(it->baseName + " : Smoothing weight edge ...", "controller"); it->readWeight(); it->roundEdgeOfWeight(edge, roundEdge); it->writeWeightSmoothed(mainDirName+ "/WEIGHTS/" + it->chipName + ".weightsmooth.fits"); it->weightName = it->chipName + ".weight"; // immediately release the memory it->dataWeightSmooth.clear(); it->dataWeightSmooth.squeeze(); it->unprotectMemory(); if (it->successProcessing) coaddScienceData->successProcessing = false; #pragma omp atomic progress += progressStepSize; } checkSuccessProcessing(coaddScienceData); satisfyMaxMemorySetting(); if (successProcessing) { coaddScienceData->status = statusNew; emit progressUpdate(100); // pushEndMessage("CoaddSmoothWeights", coaddScienceData->subDirName); } } void Controller::coaddPrepare(QString filterArg) { if (!successProcessing) return; pushBeginMessage("CoaddPrepare", coaddScienceDir); pushConfigCoadd(); emit resetProgressBar(); // Release at least as much RAM as nCPU*nchip*2 releaseMemory(maxCPU*instData->numChips*2*instData->storage, 1); QString ident = cdw->ui->COAuniqueidLineEdit->text(); QString chips = cdw->ui->COAchipsLineEdit->text(); QVector chipList; QStringList chipStringList = chips.replace(","," ").simplified().split(" "); if (!chips.isEmpty()) { for (auto &chip : chipStringList) chipList.append(chip.toInt()-1); } else { // include all chips for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; chipList.append(chip); } } QString edgeSmooth = cdw->ui->COAedgesmoothingLineEdit->text(); // Check if coaddDir exists. Delete everything in it if yes. Then recreate it. QDir coaddDir(coaddDirName); if (coaddDir.exists()) coaddDir.removeRecursively(); coaddDir.mkpath(coaddDirName); // Calculate median RA / DEC if not given manually QString refRA = cdw->ui->COAraLineEdit->text(); QString refDE = cdw->ui->COAdecLineEdit->text(); if (!refRA.isEmpty() && refRA.contains(":")) refRA = hmsToDecimal(refRA); if (!refDE.isEmpty() && refDE.contains(":")) refDE = dmsToDecimal(refDE); if (refRA.isEmpty() || refDE.isEmpty()) { QVector alpha; QVector delta; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : coaddScienceData->myImageList[chip]) { if (!it->successProcessing) continue; alpha.append(it->alpha_ctr); delta.append(it->delta_ctr); } } double alphaMedian = straightMedian_T(alpha, 0, false); // do not average center two elements because of the RA 0|360 deg boundary double deltaMedian = straightMedian_T(delta); refRA = QString::number(alphaMedian, 'f', 9); refDE = QString::number(deltaMedian, 'f', 9); } // Progress bar is updated some fraction of a second. We just need to set the variable. progress = 30.; // emit progressUpdate(progress); // For proper motion correction we need the MJD-OBS of the first exposure, taken from the first valid chip // We also want accurate start and end DATE-OBS keywords. QVector mjdobsData; minDateObs = coaddScienceData->myImageList[instData->validChip][0]->dateobs; maxDateObs = coaddScienceData->myImageList[instData->validChip][0]->dateobs; mjdStart = coaddScienceData->myImageList[instData->validChip][0]->mjdobs; mjdEnd = coaddScienceData->myImageList[instData->validChip][0]->mjdobs; float lastExpTime = 0.; // to be added to DATE-OBS of the last exposure for (auto &it : coaddScienceData->myImageList[instData->validChip]) { if (!it->successProcessing) continue; it->loadHeader(); mjdobsData.append(it->mjdobs); if (it->mjdobs <= mjdStart) { mjdStart = it->mjdobs; minDateObs = it->dateobs; } if (it->mjdobs >= mjdEnd) { mjdEnd = it->mjdobs; maxDateObs = it->dateobs; lastExpTime = it->exptime; } } double mjdobsZero = minVec_T(mjdobsData); // mjdStart = mjdobsZero; // mjdEnd = maxVec_T(mjdobsData) + lastExpTime / 86400.; mjdEnd += lastExpTime / 86400.; mjdMedian = straightMedian_T(mjdobsData, 0, false); bool doPMupdate = false; if (!cdw->ui->COApmraLineEdit->text().isEmpty() && !cdw->ui->COApmdecLineEdit->text().isEmpty()) doPMupdate = true; if (mjdobsZero == 0. && doPMupdate) { emit showMessageBox("Controller::NO_MJDOBS_FOR_PM", "", ""); successProcessing = false; return; } // Copy the headers (might be modified), link the images and weights, if they match the filterArg float numexp = 0; QList filterNames; for (int chip=0; chipnumChips; ++chip) { if (!chipList.contains(chip) || instData->badChips.contains(chip)) continue; // Skip chips that should not be coadded for (auto &it : coaddScienceData->myImageList[chip]) { if (!it->successProcessing) continue; it->loadHeader(); QFile image(it->path + "/" + it->baseName + ".fits"); QFile weight(it->weightPath + "/" + it->weightName + ".fits"); if (!edgeSmooth.isEmpty()) weight.setFileName(it->weightPath + "/" + it->weightName + "smooth.fits"); QString headerNewName = coaddDirName+"/" + it->baseName + ".head"; QFile header(it->path + "/headers/" + it->chipName + ".head"); if (filterArg == "all") { image.link(coaddDirName+"/" + it->baseName + ".fits"); weight.link(coaddDirName+"/" + it->baseName + ".weight.fits"); if (!doPMupdate) header.copy(headerNewName); else coaddPrepareProjectPM(header, headerNewName, refDE, mjdobsZero, it->mjdobs); coaddTexptime += it->exptime; coaddSkyvalue += it->skyValue / it->exptime; ++numexp; if (!filterNames.contains(it->filter)) filterNames.append(it->filter); } else { if (it->filter == filterArg) { image.link(coaddDirName+"/" + it->baseName + ".fits"); weight.link(coaddDirName+"/" + it->baseName + ".weight.fits"); if (!doPMupdate) header.copy(coaddDirName+"/" + it->baseName + ".head"); else coaddPrepareProjectPM(header, headerNewName, refDE, mjdobsZero, it->mjdobs); if (!filterNames.contains(it->filter)) filterNames.append(it->filter); coaddTexptime += it->exptime; coaddSkyvalue += it->skyValue / it->exptime; ++numexp; } } } } coaddTexptime /= instData->numUsedChips; coaddSkyvalue /= numexp; for (auto &filter : filterNames) { coaddFilter.append(filter); coaddFilter.append("+"); } coaddFilter.truncate(coaddFilter.length()-1); coaddGain = coaddTexptime; // Check if Swarp will open more file handles than the system currently allows long maxOpenFiles = sysconf(_SC_OPEN_MAX); if (2*numexp > maxOpenFiles) { successProcessing = false; SwarpReadme *swarpReadme = new SwarpReadme(2*numexp, maxOpenFiles, this); swarpReadme->show(); return; } // Run swarp to create coadd.head // tmpCoaddDir = coaddDirName; // tmpCoaddData = scienceData; progress = 50.; // emit progressUpdate(progress); coaddPrepareBuildSwarpCommand(refRA, refDE); // Run the Swarp command currentSwarpProcess = "swarpPreparation"; workerThreadPrepare = new QThread(); swarpWorker = new SwarpWorker(swarpCommand, coaddDirName, currentSwarpProcess); workerInit = true; workerThreadInit = true; swarpWorker->moveToThread(workerThreadPrepare); connect(workerThreadPrepare, &QThread::started, swarpWorker, &SwarpWorker::runSwarp, Qt::DirectConnection); // connect(workerThreadPrepare, &QThread::finished, workerThreadPrepare, &QThread::deleteLater, Qt::DirectConnection); connect(workerThreadPrepare, &QThread::finished, workerThreadPrepare, &QThread::deleteLater); connect(swarpWorker, &SwarpWorker::errorFound, this, &Controller::swarpErrorFoundReceived); connect(swarpWorker, &SwarpWorker::finishedPreparation, this, &Controller::finishedPreparationReceived); // MUST NOT connect to quit, otherwise control returns immediately to the controller, which might start another coaddition // right away in case of multi-color data // connect(swarpWorker, &SwarpWorker::finished, workerThreadPrepare, &QThread::quit, Qt::DirectConnection); // connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater, Qt::DirectConnection); // connect(swarpWorker, &SwarpWorker::finished, workerThreadPrepare, &QThread::quit); connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater); connect(swarpWorker, &SwarpWorker::messageAvailable, monitor, &Monitor::displayMessage); //qDebug() << "coaddPrepare(): before threadstart" << coaddDirName; workerThreadPrepare->start(); workerThreadPrepare->wait(); // finishedXXX signal triggers next step } void Controller::swarpErrorFoundReceived() { successProcessing = false; } // UNUSED void Controller::finishedPreparationReceived() { progress = 70.; // emit progressUpdate(progress); foldCoaddFits(); if (!successProcessing) return; // If requested, rotate coadd.head to user-specified position angle coaddPrepareProjectRotation(); progress = 100.; // emit progressUpdate(progress); // Trigger resampling emit swarpStartResampling(); } void Controller::coaddPrepareProjectPM(QFile &headerFileOld, QString newHeaderName, QString refDE, double mjdobsZero, double mjdobsNow) { if (!successProcessing) return; double pmRA = cdw->ui->COApmraLineEdit->text().toDouble(); double pmDE = cdw->ui->COApmdecLineEdit->text().toDouble(); int unitIndex = cdw->ui->COApmComboBox->currentIndex(); double timeConversion = 1.; if (unitIndex == 0) timeConversion = 1./60.; // arcsec / sec else if (unitIndex == 1) timeConversion = 1.; // arcsec / min else if (unitIndex == 2) timeConversion = 60.; // arcsec / hr else if (unitIndex == 3) timeConversion = 1440.; // arcsec / day // Calculate speed in CRVAL1/2 per minute double crval2 = refDE.toDouble(); double crval1Speed = pmRA / 3600. / timeConversion / cos(crval2*rad); double crval2Speed = pmDE / 3600. / timeConversion; // How many minutes passed since the first image was taken double timeDiff = (mjdobsNow - mjdobsZero) * 1440.; // New CRVAL1/2 for the current exposure // double crval1New = crval1 + timeDiff * crval1Speed; // double crval2New = crval2 + timeDiff * crval2Speed; // Update CRVAL1/2 (and write to a new header file) QTextStream streamIn(&headerFileOld); if( !headerFileOld.open(QIODevice::ReadOnly)) { QString part1 = headerFileOld.fileName(); QString part2 = headerFileOld.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PM_READ", part1, part2); successProcessing = false; return; } QFile headerFileNew(newHeaderName); QTextStream streamOut(&headerFileNew); if( !headerFileNew.open(QIODevice::WriteOnly)) { QString part1 = headerFileNew.fileName(); QString part2 = headerFileNew.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PM_WRITE", part1, part2); successProcessing = false; return; } // CHECK CHECK CHECK: // MPC: what is the difference between coordinate motion and sky motion? // It seems I got it right, but for a target at DEC=3. Higher declinations? don't need to divide crval1speed by cosine dec(?) while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (!line.contains("CRVAL")) streamOut << line << "\n"; else { QString value = line.split("=").at(1); int slashPosition = value.lastIndexOf('/'); // (can be -1 if not found, treated as 0 by truncate(), i.e. entire string is set to empty if (slashPosition > 10) value.truncate(slashPosition); double crval1New = value.simplified().toDouble() - timeDiff * crval1Speed; double crval2New = value.simplified().toDouble() - timeDiff * crval2Speed; QString crval1String = "CRVAL1 = " + QString::number(crval1New, 'f', 12); QString crval2String = "CRVAL2 = " + QString::number(crval2New, 'f', 12); crval1String.resize(79, ' '); // Must be 80 chars long to conform with FITS standard. crval2String.resize(79, ' '); // We use 79 here because the read in stream also contains a carriage return! if (line.contains("CRVAL1")) streamOut << crval1String << "\n"; if (line.contains("CRVAL2")) streamOut << crval2String << "\n"; } } headerFileOld.close(); headerFileNew.close(); headerFileNew.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Controller::coaddPrepareProjectRotation() { if (!successProcessing) return; if (cdw->ui->COAskypaLineEdit->text().isEmpty()) return; // Rename coadd.head QFile coaddHeadOld(coaddDirName+"/coadd.head"); coaddHeadOld.rename(coaddDirName+"/coadd.head_orig"); // Read the CD matrix in coadd.head if(!coaddHeadOld.open(QIODevice::ReadOnly)) { QString part1 = coaddHeadOld.fileName(); QString part2 = coaddHeadOld.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PA", part1, part2); successProcessing = false; return; } double cd11_coadd = 0.; double cd12_coadd = 0.; double cd21_coadd = 0.; double cd22_coadd = 0.; long naxis1_coadd = 0; long naxis2_coadd = 0; QTextStream streamIn(&coaddHeadOld); while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (line.contains("NAXIS1 =")) naxis1_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); if (line.contains("NAXIS2 =")) naxis2_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); if (line.contains("CD1_1 =")) cd11_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); if (line.contains("CD1_2 =")) cd12_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); if (line.contains("CD2_1 =")) cd21_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); if (line.contains("CD2_2 =")) cd22_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); } // PA of the original data (taken from first image and its valid chip) double cd11 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[0]; double cd12 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[1]; double cd21 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[2]; double cd22 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[3]; double PAold = getPosAnglefromCD(cd11, cd12, cd21, cd22); // in [deg]; not sure about the minus here double PAnew = cdw->ui->COAskypaLineEdit->text().toDouble(); // in [deg]; if image is flipped, the angle to get "parallel" axes should be 180 - the automatically determined angle. rotateCDmatrix(cd11_coadd, cd12_coadd, cd21_coadd, cd22_coadd, PAnew); long naxis1New = 0; long naxis2New = 0; get_rotimsize(naxis1_coadd, naxis2_coadd, PAold, PAnew, naxis1New, naxis2New); // Updated header lines: QString str_naxis1 = "NAXIS1 = "+QString::number(naxis1New); QString str_naxis2 = "NAXIS2 = "+QString::number(naxis1New); QString str_crpix1 = "CRPIX1 = "+QString::number(naxis1New/2); QString str_crpix2 = "CRPIX2 = "+QString::number(naxis1New/2); QString str_cd11 = "CD1_1 = "+QString::number(cd11_coadd, 'f', 12); QString str_cd12 = "CD1_2 = "+QString::number(cd12_coadd, 'f', 12); QString str_cd21 = "CD2_1 = "+QString::number(cd21_coadd, 'f', 12); QString str_cd22 = "CD2_2 = "+QString::number(cd22_coadd, 'f', 12); str_naxis1.resize(80, ' '); str_naxis2.resize(80, ' '); str_crpix1.resize(80, ' '); str_crpix2.resize(80, ' '); str_cd11.resize(80, ' '); str_cd12.resize(80, ' '); str_cd21.resize(80, ' '); str_cd22.resize(80, ' '); // Open new coadd.head QFile coaddHeadNew(coaddDirName+"/coadd.head"); if(!coaddHeadNew.open(QIODevice::WriteOnly)) { QString part1 = coaddHeadNew.fileName(); QString part2 = coaddHeadNew.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PA", part1, part2); successProcessing = false; return; } // Reset the old stream, and scan the file once more streamIn.seek(0); QTextStream streamOut(&coaddHeadNew); while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (line.contains("NAXIS1")) streamOut << str_naxis1 << "\n"; else if (line.contains("NAXIS2")) streamOut << str_naxis2 << "\n"; else if (line.contains("CRPIX1")) streamOut << str_crpix1 << "\n"; else if (line.contains("CRPIX2")) streamOut << str_crpix2 << "\n"; else if (line.contains("CD1_1")) streamOut << str_cd11 << "\n"; else if (line.contains("CD1_2")) streamOut << str_cd12 << "\n"; else if (line.contains("CD2_1")) streamOut << str_cd21 << "\n"; else if (line.contains("CD2_2")) streamOut << str_cd22 << "\n"; else streamOut << line << "\n"; } coaddHeadOld.close(); coaddHeadNew.close(); coaddHeadOld.remove(); coaddHeadNew.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Controller::coaddPrepareBuildSwarpCommand(QString refRA, QString refDE) { if (!successProcessing) return; QString coaddSize = ""; QString naxis1 = cdw->ui->COAsizexLineEdit->text(); QString naxis2 = cdw->ui->COAsizeyLineEdit->text(); if (!naxis1.isEmpty() && !naxis2.isEmpty()) coaddSize = " -IMAGE_SIZE "+naxis1+","+naxis2; QString pixelScale = cdw->ui->COApixscaleLineEdit->text(); if (pixelScale.isEmpty()) pixelScale = QString::number(instData->pixscale, 'f', 9); statusOld = coaddScienceData->processingStatus->statusString; QString swarp = findExecutableName("swarp"); swarpCommand = swarp + " *"+statusOld+".fits"; swarpCommand += " -NTHREADS " + QString::number(maxCPU); swarpCommand += " -CENTER "+refRA+","+refDE; swarpCommand += " -CENTER_TYPE MANUAL"; swarpCommand += " -VERBOSE_TYPE FULL"; swarpCommand += " -HEADER_ONLY Y"; // only in v2.40.1, not in earlier versions. Current latest official release: 2.38 // swarpCommand += " -HEADEROUT_NAME coadd.head"; swarpCommand += " -PIXELSCALE_TYPE MANUAL"; swarpCommand += " -GAIN_KEYWORD GAIN"; swarpCommand += " -PIXEL_SCALE "+pixelScale; swarpCommand += " -PROJECTION_TYPE " + cdw->ui->COAprojectionComboBox->currentText(); swarpCommand += " -CELESTIAL_TYPE " + cdw->ui->COAcelestialtypeComboBox->currentText(); swarpCommand += " -RESAMPLING_TYPE " + cdw->ui->COAkernelComboBox->currentText(); swarpCommand += coaddSize; if (verbosity > 1) emit messageAvailable("Executing the following swarp command :

"+swarpCommand+"

in directory:

"+coaddDirName+"
", "info"); if (verbosity > 1) emit messageAvailable("
Swarp output
", "ignore"); } void Controller::coaddResampleBuildSwarpCommand(QString imageList, int i) { if (!successProcessing) return; QString swarpCommand; // shadowing the class member 'swarpCommand' for a moment QString pixelScale = cdw->ui->COApixscaleLineEdit->text(); if (pixelScale.isEmpty()) pixelScale = QString::number(instData->pixscale, 'f', 9); QString rescaleWeights = "N"; if (cdw->ui->COArescaleweightsCheckBox->isChecked()) rescaleWeights = "Y"; statusOld = coaddScienceData->processingStatus->statusString; QString swarp = findExecutableName("swarp"); swarpCommand = swarp +" @"+imageList; swarpCommand += " -NTHREADS 1"; // Launching maxCPU externally // swarpCommand += " -NTHREADS " + QString::number(maxExternalThreads); swarpCommand += " -RESAMPLE Y"; swarpCommand += " -RESAMPLE_SUFFIX ."+coaddUniqueID+"resamp.fits"; swarpCommand += " -COMBINE N"; swarpCommand += " -VERBOSE_TYPE FULL"; swarpCommand += " -WEIGHT_TYPE MAP_WEIGHT"; swarpCommand += " -GAIN_KEYWORD GAIN"; swarpCommand += " -SUBTRACT_BACK N"; swarpCommand += " -PROJECTION_TYPE " + cdw->ui->COAprojectionComboBox->currentText(); swarpCommand += " -CELESTIAL_TYPE " + cdw->ui->COAcelestialtypeComboBox->currentText(); swarpCommand += " -RESAMPLING_TYPE " + cdw->ui->COAkernelComboBox->currentText(); swarpCommand += " -COMBINE_TYPE " + cdw->ui->COAcombinetypeComboBox->currentText(); swarpCommand += " -RESCALE_WEIGHTS " + rescaleWeights; swarpCommand += " -COPY_KEYWORDS OBJECT,SKYVALUE,EXPTIME,DATE-OBS"; swarpCommands[i] = swarpCommand; if (verbosity > 1) emit messageAvailable("Executing the following swarp command :

"+swarpCommands[i]+"

in directory:

"+coaddDirName+"
", "info"); if (verbosity > 1) emit messageAvailable("
Swarp output
", "ignore"); } void Controller::coaddCoadditionBuildSwarpCommand(QString imageList) { if (!successProcessing) return; QString pixelScale = cdw->ui->COApixscaleLineEdit->text(); if (pixelScale.isEmpty()) pixelScale = QString::number(instData->pixscale, 'f', 9); QString rescaleWeights = "N"; if (cdw->ui->COArescaleweightsCheckBox->isChecked()) rescaleWeights = "Y"; statusOld = coaddScienceData->processingStatus->statusString; QString swarp = findExecutableName("swarp"); swarpCommand = swarp +" @"+imageList; swarpCommand += " -NTHREADS " + QString::number(maxCPU); swarpCommand += " -RESAMPLE N"; swarpCommand += " -COMBINE Y"; swarpCommand += " -VERBOSE_TYPE FULL"; swarpCommand += " -WEIGHT_TYPE MAP_WEIGHT"; swarpCommand += " -BLANK_BADPIXELS Y"; swarpCommand += " -SUBTRACT_BACK N"; swarpCommand += " -GAIN_KEYWORD GAIN"; swarpCommand += " -PROJECTION_TYPE " + cdw->ui->COAprojectionComboBox->currentText(); swarpCommand += " -CELESTIAL_TYPE " + cdw->ui->COAcelestialtypeComboBox->currentText(); swarpCommand += " -RESAMPLING_TYPE " + cdw->ui->COAkernelComboBox->currentText(); swarpCommand += " -COMBINE_TYPE " + cdw->ui->COAcombinetypeComboBox->currentText(); swarpCommand += " -RESCALE_WEIGHTS " + rescaleWeights; swarpCommand += " -COPY_KEYWORDS OBJECT"; if (verbosity > 1) emit messageAvailable("Executing the following swarp command :

"+swarpCommand+"

in directory:

"+coaddDirName+"
", "info"); if (verbosity > 1) emit messageAvailable("
Swarp output
", "ignore"); } void Controller::coaddResample() { if (!successProcessing) { coaddUpdate(); return; } progress = 0.; emit resetProgressBar(); pushBeginMessage("CoaddResample", coaddScienceDir); statusOld = coaddScienceData->processingStatus->statusString; // List of all images QDir coaddDir(coaddDirName); QStringList filter("*"+statusOld+".fits"); QStringList imageList = coaddDir.entryList(filter); // Lists containing output files and streams QString listName; QFile file; QTextStream stream; QStringList listNames; int i = 0; int fileCount = 0; int highGroup = imageList.length() % maxCPU - 1; for (auto &imageName : imageList) { if (i==0) { listName = coaddDirName+"/listCoadd_"+QString::number(fileCount); listNames << listName; file.setFileName(listName); stream.setDevice(&file); if (!file.open(QIODevice::WriteOnly)) { QString part1 = listName; QString part2 = file.errorString(); emit showMessageBox("Controller::CANNOT_WRITE_RESAMPLE_LIST", part1, part2); successProcessing = false; return; } } stream << imageName << "\n"; ++i; /* if (i == imageList.length() / maxCPU) { i = 0; ++fileCount; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } */ // Spread images as evenly as possible across the threads if (fileCount <= highGroup && i == imageList.length() / maxCPU + 1) { i = 0; ++fileCount; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } if (fileCount > highGroup && i == imageList.length() / maxCPU) { i = 0; ++fileCount; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } } if (file.isOpen()) { file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } numberFileCounter = new FileProgressCounter(coaddDirName, "*resamp.fits", imageList.length(), &progress, this); connect(numberFileCounter->timer, &QTimer::timeout, numberFileCounter, &FileProgressCounter::numberFileProgress); // connect(numberFileCounter, &FileProgressCounter::progressUpdate, mainGUI, &MainWindow::progressUpdateReceived, Qt::DirectConnection); numberFileCounter->timer->start(2000); // We can use at most as many threads as we have files in listname: localMaxCPU = maxCPU > listNames.length() ? listNames.length() : maxCPU; currentSwarpProcess = "swarpResampling"; #pragma omp parallel for num_threads(localMaxCPU) firstprivate(coaddDirName) for (int i=0; ithreadID = i; swarpWorkers[i]->moveToThread(workerThreads[i]); } connect(workerThreads[i], &QThread::started, swarpWorkers[i], &SwarpWorker::runSwarp); connect(workerThreads[i], &QThread::finished, workerThreads[i], &QThread::deleteLater); connect(swarpWorkers[i], &SwarpWorker::errorFound, this, &Controller::swarpErrorFoundReceived); // connect(workerThreads[i], &QThread::finished, workerThreads[i], &QThread::deleteLater); connect(swarpWorkers[i], &SwarpWorker::finishedResampling, this, &Controller::waitForResamplingThreads); // connect(swarpWorkers[i], &SwarpWorker::finished, workerThreads[i], &QThread::quit); connect(swarpWorkers[i], &SwarpWorker::finished, swarpWorkers[i], &QObject::deleteLater); connect(swarpWorkers[i], &SwarpWorker::finished, workerThreads[i], &QThread::quit); // connect(swarpWorkers[i], &SwarpWorker::finished, swarpWorkers[i], &QObject::deleteLater); connect(swarpWorkers[i], &SwarpWorker::messageAvailable, monitor, &Monitor::displayMessage); workerThreads[i]->start(); // workerThreads[i]->wait(); } // emit progressUpdate(100); } void Controller::waitForResamplingThreads(int threadID) { omp_set_lock(&genericLock); threadsFinished[threadID] = true; // Trigger Swarpfilter if all resampling threads have finished bool allTrue = true; for (int i=0; itimer->stop(); // We don't have to delete the swarpWorkers because they are "movedTo" the threads // for (auto &it : workerThreads) { // delete it; // } } omp_unset_lock(&genericLock); } void Controller::coaddSwarpfilter() { if (!successProcessing) { emit swarpStartCoaddition(); // Must continue through the chain 'naturally' until its end return; } QString kappa = cdw->ui->COAoutthreshLineEdit->text(); QString clustersize = cdw->ui->COAoutsizeLineEdit->text(); QString borderwidth = cdw->ui->COAoutborderLineEdit->text(); if (kappa.isEmpty()) { // Trigger coaddition emit swarpStartCoaddition(); return; } progress = 0.; emit resetProgressBar(); pushBeginMessage("CoaddSwarpFilter", coaddScienceDir); SwarpFilter swarpFilter(coaddDirName, kappa, clustersize, borderwidth, maxCPU, &verbosity); swarpFilter.progress = &progress; connect(&swarpFilter, &SwarpFilter::messageAvailable, monitor, &Monitor::displayMessage); connect(&swarpFilter, &SwarpFilter::progressUpdate, mainGUI, &MainWindow::progressUpdateReceived); connect(&swarpFilter, &SwarpFilter::critical, this, &Controller::criticalReceived); swarpFilter.runCosmicFilter(); // TODO: introduce successProcessing to swarpfilter(); // TODO: swarpfilter blocks the update of the CPU and memory progress bar (normal progress bar increases as intended). Check timers? checkSuccessProcessing(coaddScienceData); if (successProcessing) { emit progressUpdate(100); } // Trigger coaddition emit swarpStartCoaddition(); } void Controller::coaddCoaddition() { if (!successProcessing) { coaddUpdate(); return; } if (!successProcessing) return; emit resetProgressBar(); statusOld = coaddScienceData->processingStatus->statusString; pushBeginMessage("CoaddCoadd", coaddScienceDir); // List of all images QDir coaddDir(coaddDirName); QStringList filter("*"+statusOld+"*resamp.fits"); QStringList imageList = coaddDir.entryList(filter); QString listName = coaddDirName+"/listCoadd"; QFile file(listName); QTextStream stream(&file); if (!file.open(QIODevice::WriteOnly)) { QString part1 = listName; QString part2 = file.errorString(); emit showMessageBox("Controller::CANNOT_WRITE_RESAMPLE_LIST", part1, part2); successProcessing = false; return; } for (auto &imageName : imageList) { stream << imageName << "\n"; } file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); sizeFileCounter = new FileProgressCounter(coaddDirName, coaddCoadditionGetSize(), &progress, this); connect(sizeFileCounter->timer, &QTimer::timeout, sizeFileCounter, &FileProgressCounter::sizeFileProgress); connect(sizeFileCounter, &FileProgressCounter::progressUpdate, mainGUI, &MainWindow::progressUpdateReceived); connect(this, &Controller::stopFileProgressTimer, sizeFileCounter, &FileProgressCounter::stopFileProgressTimerReceived); sizeFileCounter->timer->start(1000); coaddCoadditionBuildSwarpCommand(listName); // delete a previous Thread from the preparation. // workerThreadPrepare->quit(); // delete workerThreadPrepare; // Run the Swarp command currentSwarpProcess = "swarpCoaddition"; workerThreadCoadd = new QThread(); swarpWorker = new SwarpWorker(swarpCommand, coaddDirName, currentSwarpProcess); workerInit = true; workerThreadInit = true; swarpWorker->moveToThread(workerThreadCoadd); connect(workerThreadCoadd, &QThread::started, swarpWorker, &SwarpWorker::runSwarp); connect(workerThreadCoadd, &QThread::finished, workerThreadCoadd, &QThread::deleteLater); // connect(workerThreadCoadd, &QThread::finished, workerThreadCoadd, &QThread::deleteLater); connect(swarpWorker, &SwarpWorker::finishedCoaddition, this, &Controller::coaddUpdate, Qt::DirectConnection); connect(swarpWorker, &SwarpWorker::finished, workerThreadCoadd, &QThread::quit); connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater); connect(swarpWorker, &SwarpWorker::errorFound, this, &Controller::swarpErrorFoundReceived); //connect(swarpWorker, &SwarpWorker::finished, workerThreadCoadd, &QThread::quit); //connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater); connect(swarpWorker, &SwarpWorker::messageAvailable, monitor, &Monitor::displayMessage); workerThreadCoadd->start(); // workerThreadCoadd->wait(); // TODO: does not continue with next filter if scheduled as "separately"! QTconnection issue? } long Controller::coaddCoadditionGetSize() { // Read NAXIS1/2 in coadd.head QFile coaddHead(coaddDirName+"/coadd.head"); if(!coaddHead.open(QIODevice::ReadOnly)) { QString part1 = coaddHead.fileName(); QString part2 = coaddHead.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PA", part1, part2); successProcessing = false; return 0; } long naxis1_coadd = 0; long naxis2_coadd = 0; QTextStream streamIn(&coaddHead); while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (line.contains("NAXIS1 =")) naxis1_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); if (line.contains("NAXIS2 =")) naxis2_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); } return 4 * naxis1_coadd * naxis2_coadd; } void Controller::coaddUpdate() { if (!successProcessing) { // emit forceFinish(); if (workerThreadPrepare) workerThreadPrepare->quit(); // crashing sometimes, not sure why return; } // Stop "measuring" the file size of coadd.fits emit stopFileProgressTimer(); progress = 0.; emit resetProgressBar(); // cleanup temporary files QDir coaddDir(coaddDirName); QStringList filter = {"listCoadd*", "coadd.head"}; coaddDir.setNameFilters(filter); coaddDir.setSorting(QDir::Name); QStringList tempFiles = coaddDir.entryList(filter); for (auto &it : tempFiles) { QFile tmpFile(coaddDirName+"/"+it); if (tmpFile.exists()) tmpFile.remove(); } pushBeginMessage("CoaddUpdate", coaddScienceDir); bool skippedIQ = true; float seeing_world = 0.; float seeing_image = 0.; // float maxVal = 100.; emit loadViewer(coaddDirName, "coadd.fits", "DragMode"); // Do IQ analysis only for small images with "normal" plate scales if (instData->pixscale <= 2.0 && instData->radius <= 0.5) { skippedIQ = false; emit messageAvailable("coadd.fits : Loading image data ...", "image"); QVector dummyMask; dummyMask.clear(); MyImage *coadd = new MyImage(coaddDirName, "coadd.fits", "", 1, dummyMask, &verbosity); connect(coadd, &MyImage::critical, this, &Controller::criticalReceived); connect(coadd, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); connect(coadd, &MyImage::warning, this, &Controller::warningReceived); connect(coadd, &MyImage::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(coadd, &MyImage::setWCSLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); coadd->chipName = "coadd"; coadd->setupData(false, false, true); coadd->globalMaskAvailable = false; coadd->objectMaskDone = false; coadd->weightInMemory = false; coadd->weightPath = coaddDirName; coadd->weightName = "coadd"; coadd->readWeight(); coadd->gain = 1.0; coadd->saturationValue = minCoaddSaturationValue; // maxVal = maxVec_T(coadd->dataCurrent); float radius = sqrt(coadd->naxis1*coadd->naxis1 + coadd->naxis2*coadd->naxis2) / 2. * coadd->plateScale / 60.; // in arcmin // Enforce an upper limit to the download catalog (the query also has a built-in limit of # sources < 1e6) if (radius > 60) radius = 60.; emit messageAvailable("coadd.fits : Downloading GAIA point sources ...", "image"); downloadGaiaCatalog(coaddScienceData, QString::number(radius, 'f', 1)); // Point sources // Measure the seeing if we have reference sources if (gaiaQuery->numSources > 0) { emit messageAvailable("coadd.fits : Modeling background ...", "image"); coadd->backgroundModel(256, "interpolate"); emit messageAvailable("coadd.fits : Detecting sources ...", "image"); coadd->segmentImage("10", "3", true, false); coadd->estimateMatchingTolerance(); ImageQuality *imageQuality = new ImageQuality(instData, mainDirName); imageQuality->matchingTolerance = coadd->matchingTolerance; imageQuality->baseName = "coadd.fits"; connect(imageQuality, &ImageQuality::messageAvailable, this, &Controller::messageAvailableReceived); // pass the reference data collectGaiaRaDec(coadd, gaiaQuery->de_out, gaiaQuery->ra_out, imageQuality->refCat); // pass the source data (dec, ra, fwhm, ell on one hand, and mag separately) coadd->collectSeeingParameters(imageQuality->sourceCat, imageQuality->sourceMag, 0); // match static_cast (imageQuality->getSeeingFromGaia()); // if (!gaia) imageQuality->getSeeingFromRhMag(); TODO: not yet implemented seeing_image = imageQuality->fwhm; // in pixel seeing_world = imageQuality->fwhm * coadd->plateScale; // in pixel if (imageQuality->numSources > 0) { emit messageAvailable("coadd.fits : FWHM = " + QString::number(seeing_world, 'f', 2) + "\" (" + QString::number(seeing_image, 'f', 2) + " pixel)", "image"); emit messageAvailable("coadd.fits : Ellipticity = " + QString::number(imageQuality->ellipticity, 'f', 3), "image"); // emit messageAvailable("coadd.fits : # stars used for IQ analysis = " + QString::number(imageQuality->numSources), "image"); } else { emit messageAvailable("coadd.fits : FWHM = undetermined", "image"); emit messageAvailable("coadd.fits : Ellipticity = undetermined", "image"); // emit messageAvailable("coadd.fits : # stars used for IQ analysis = 0", "image"); } if (seeing_image < 2.0 && seeing_image > 0. && (cdw->ui->COAkernelComboBox->currentText() == "LANCZOS3" || cdw->ui->COAkernelComboBox->currentText() == "LANCZOS4")) { emit messageAvailable("Undersampling detected. The chosen "+cdw->ui->COAkernelComboBox->currentText() +" resampling kernel could lead to artifacts in compact sources (stars). In this case, consider the LANCZOS2 kernel.", "warning"); } coadd->releaseAllDetectionMemory(); coadd->releaseBackgroundMemory("entirely"); } else { emit messageAvailable("Seeing will not be determined because no reference point sources were retrieved.", "warning"); } coadd->freeAll(); delete coadd; coadd = nullptr; delete gaiaQuery; gaiaQuery = nullptr; /* // TODO: that should be redone using the new gaia matching method QVector fluxRadius(coadd->objectList.length()); for (auto &obj : coadd->objectList) { if (obj->FLAGS == 0) fluxRadius.append(obj->FLUX_RADIUS); } float seeing_image = modeMask(fluxRadius, "classic", QVector(), false)[0]; float seeing_world = seeing_image * instData->pixscale; emit messageAvailable("coadd.fits : FWHM = " + QString::number(seeing_world, 'f', 2) + "\" (" + QString::number(seeing_image, 'f', 2) + " pixel)" */ } else { skippedIQ = true; emit messageAvailable("
The coadded image covers a very large area on sky. The image quality analysis is skipped, as it would require the download of a very large point source catalog.
", "data"); } // IQ analysis ended. Update FITS header fitsfile *fptr = nullptr; QString name = coaddDirName+"/coadd.fits"; int status = 0; // declared above if (name.isNull() || name.isEmpty()) { status = 1; emit messageAvailable("Controller::coaddUpdate(): file name empty or not initialized!", "error"); emit criticalReceived(); return; } fits_open_file(&fptr, name.toUtf8().data(), READWRITE, &status); fits_update_key_str(fptr, "FILTER", coaddFilter.toUtf8().data(), NULL, &status); fits_update_key_flt(fptr, "EXPTIME", 1.0, 1, "Exposure time is normalized to 1s", &status); fits_update_key_flt(fptr, "TEXPTIME", coaddTexptime, 3, "Total exposure time [s]", &status); fits_update_key_flt(fptr, "SKYVALUE", coaddSkyvalue, 3, "Effective background value [e-/s]", &status); fits_update_key_flt(fptr, "GAIN", coaddGain, 3, "Effective gain. This image is already in e-/s!", &status); fits_update_key_str(fptr, "UNITS", "e-/s", "Pixels are photo-electrons / second", &status); fits_update_key_flt(fptr, "SATURATE", minCoaddSaturationValue, 3, "Lowest value at which saturation occurs [e-/s]", &status); if (!skippedIQ) { fits_update_key_flt(fptr, "FWHM_I", seeing_image, 3, "FWHM (pixel)", &status); fits_update_key_flt(fptr, "FWHM_W", seeing_world, 3, "FWHM (arcsec)", &status); } fits_update_key_str(fptr, "DATEOBS1", minDateObs.toUtf8().data(), "Begin of the first observation (DATE-OBS)", &status); fits_update_key_str(fptr, "DATEOBS2", maxDateObs.toUtf8().data(), "Begin of the last observation (DATE-OBS)", &status); fits_update_key_dbl(fptr, "MJDSTART", mjdStart, 12, "Begin of the first observation (MJD-OBS)", &status); fits_update_key_dbl(fptr, "MJDMED", mjdMedian, 12, "Median MJD-OBS of all observations", &status); fits_update_key_dbl(fptr, "MJDEND", mjdEnd, 12, "End of the last observation (MJD-OBS + EXPTIME)", &status); fits_update_key_str(fptr, "THELIRUN", mainGUI->ui->setupProjectLineEdit->text().toUtf8().data(), "THELI project name", &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); emit progressUpdate(100); // pushEndMessage(taskBasename, coaddScienceDir); // Now we can quit the first coaddition thread (which spawned all the other threads). // This will return control to mainGUI() (i.e. enable the start button again) // workerThreadPrepare->quit(); // Finally, do flux calibration if requested if (cdw->ui->COAfluxcalibCheckBox->isChecked()) { emit messageAvailable("coadd.fits : Loading flux calibration module ...", "image"); // emit loadAbsZP(coaddDirName+"/coadd.fits", maxVal); emit loadAbsZP(coaddDirName+"/coadd.fits", minCoaddSaturationValue); } else { // Now we can quit the first coaddition thread (which spawned all the other threads). // This will return control to mainGUI() (i.e. enable the start button again) workerThreadPrepare->quit(); } } void Controller::getMinimumSaturationValue() { minCoaddSaturationValue = 1e12; QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, coaddScienceData); // Update minimum saturation value (normalized to exposure time) // TODO: update wrt fluxscaling for (int k=0; ksuccessProcessing) continue; if (it->saturationValue / it->exptime < minCoaddSaturationValue) { minCoaddSaturationValue = it->saturationValue / it->exptime; } } } void Controller::absZeroPointCloseReceived() { workerThreadPrepare->quit(); } // write the initial empty coadd.fits into a coadd.head void Controller::foldCoaddFits() { QFile fileIn(coaddDirName+"/coadd.fits"); QFile fileOut(coaddDirName+"/coadd.head"); QTextStream streamIn(&fileIn); QTextStream streamOut(&fileOut); if (!fileIn.open(QIODevice::ReadOnly)) { QString part1 = coaddDirName+"/coadd.fits"; QString part2 = fileIn.errorString(); emit showMessageBox("Controller::CANNOT_OPEN_FILE", part1, part2); successProcessing = false; return; } if (!fileOut.open(QIODevice::WriteOnly)) { QString part1 = coaddDirName+"/coadd.head"; QString part2 = fileIn.errorString(); emit showMessageBox("Controller::CANNOT_OPEN_FILE", part1, part2); successProcessing = false; return; } QString line; int cardLength = 80; while (streamIn.readLineInto(&line)) { if (line.isEmpty()) continue; long length = line.length(); if (length<80) return; for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&line, i, cardLength); QString string = subString.toString(); streamOut << string << "\n"; } } fileIn.close(); fileOut.close(); fileOut.setPermissions(QFile::ReadUser | QFile::WriteUser); fileIn.remove(); } THELI-3.1.3/src/processingInternal/processingCollapse.cc000066400000000000000000000305351417631501300232000ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include "ui_monitor.h" #include #include #include #include void Controller::taskInternalCollapse() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigCollapse(); memoryDecideDeletableStatus(scienceData, false); backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; // Parameters for collapse correction QString DT = cdw->ui->COCDTLineEdit->text(); QString DMIN = cdw->ui->COCDMINLineEdit->text(); QString expFactor = cdw->ui->COCmefLineEdit->text(); QString direction = cdw->ui->COCdirectionComboBox->currentText(); QString threshold = cdw->ui->COCrejectLineEdit->text(); bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; getNumberOfActiveImages(scienceData); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { if (verbosity >= 0) emit messageAvailable(it->baseName + " : Collapse correction ...", "controller"); it->setupDataInMemory(isTaskRepeated, true, true); it->backgroundModel(256, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor, false); it->collapseCorrection(threshold, direction); it->makeMemoryBackup(); it->statusCurrent = statusNew; it->baseName = it->chipName + statusNew; it->imageOnDrive = false; if (alwaysStoreData) it->writeImage(); incrementProgress();64 } if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } decrementCurrentThreads(lock); } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); // Release as much memory as maximally necessary float nimg = 7; // old, new, background, segmentation, measure, mask, margin releaseMemory(nimg*instData->storage*maxCPU, 1); // Protect the rest, will be unprotected as needed scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); long imin = 0; long imax = 0; long jmin = 0; long jmax = 0; if (!cdw->ui->COCxminLineEdit->text().isEmpty()) imin = cdw->ui->COCxminLineEdit->text().toLong() - 1; if (!cdw->ui->COCxmaxLineEdit->text().isEmpty()) imax = cdw->ui->COCxmaxLineEdit->text().toLong() - 1; if (!cdw->ui->COCyminLineEdit->text().isEmpty()) jmin = cdw->ui->COCyminLineEdit->text().toLong() - 1; if (!cdw->ui->COCymaxLineEdit->text().isEmpty()) jmax = cdw->ui->COCymaxLineEdit->text().toLong() - 1; #pragma omp parallel for num_threads(maxCPU) for (int k=0; ksuccessProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Collapse correction ...", "image"); it->processingStatus->Collapse = false; it->setupData(scienceData->isTaskRepeated, true, true, backupDirName); // CHECK: why do we determine the mode here? if (!it->successProcessing) { abortProcess = true; continue; } it->backgroundModel(256, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor, false); it->addExludedRegionToMask(imin, imax, jmin, jmax); it->collapseCorrection(threshold, direction); it->releaseAllDetectionMemory(); it->releaseBackgroundMemory("entirely"); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } } #pragma omp atomic progress += progressStepSize; } /* // Just file movements (if on drive), does not require parallelization for (int chip=0; chipnumChips; ++chip) { if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); } } } */ checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { scienceData->processingStatus->Collapse = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header // pushEndMessage(taskBasename, scienceDir); } } void Controller::taskInternalBinnedpreview() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigBinnedpreview(); // Collect CD matrices (from first exposure in the list) // The transformation matrix is the CD matrix with rotation angle and plate scale stripped QVector< QVector> CDmatrices; QVector< QVector> Tmatrices; for (int chip=0; chipnumChips; ++chip) { if (!instData->badChips.contains(chip)) { scienceData->myImageList[chip][0]->readImage(false); QVector CDmatrix = scienceData->myImageList[chip][0]->extractCDmatrix(); CDmatrices << CDmatrix; Tmatrices << CDmatrixToTransformationMatrix(CDmatrix, instData->name); } else { // a dummy QVector CDmatrix = {-0.001, 0.0, 0.0, 0.0001}; CDmatrices << CDmatrix; Tmatrices << CDmatrixToTransformationMatrix(CDmatrix, instData->name); } } // Determine overall image size int nGlobal; int mGlobal; int xminOffset; int yminOffset; int binFactor = cdw->ui->BIPSpinBox->value(); getBinnedSize(instData, Tmatrices, nGlobal, mGlobal, binFactor, xminOffset, yminOffset); memoryDecideDeletableStatus(scienceData, false); int numExp = scienceData->myImageList[instData->validChip].length(); getNumberOfActiveImages(scienceData); float nimg = (1 + 1./(binFactor*binFactor)) * instData->numChips; releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numExp, instData->storageExposure); QString statusString = scienceData->processingStatus->statusString; // Loop over all exposures #pragma omp parallel for num_threads(maxCPU) firstprivate(statusString) for (int img=0; imgstorage, maxCPU); // Loop over all chips if (verbosity >= 0) emit messageAvailable("Binning and mapping chips in exposure " + QString::number(img) + " / " + QString::number(numExp), "controller"); QVector dataBinnedGlobal(nGlobal*mGlobal,0); int binnedChipCounter = 0; for (int chip=0; chipnumChips; ++chip) { if (abortProcess) break; if (instData->badChips.contains(chip)) continue; scienceData->myImageList[chip][img]->setupDataInMemorySimple(false); if (!scienceData->myImageList[chip][img]->successProcessing) continue; int n = scienceData->myImageList[chip][img]->naxis1; int m = scienceData->myImageList[chip][img]->naxis2; int crpix1 = scienceData->myImageList[chip][img]->getKeyword("CRPIX1").toFloat() / binFactor; int crpix2 = scienceData->myImageList[chip][img]->getKeyword("CRPIX2").toFloat() / binFactor; int nb = floor(n/binFactor); int mb = floor(m/binFactor); QVector dataBinned(nb*mb,0); // Bin the image; map it onto the output binned image; if (verbosity >= 1) emit messageAvailable(scienceData->myImageList[chip][img]->chipName + " : Binning ...", "image"); binData(scienceData->myImageList[chip][img]->dataCurrent, dataBinned, n, nb, mb, binFactor, binFactor); mapBinnedData(dataBinnedGlobal, dataBinned, Tmatrices[chip], nGlobal, mGlobal, nb, mb, crpix1, crpix2, xminOffset, yminOffset, instData->name); scienceData->myImageList[chip][img]->unprotectMemory(); if (minimizeMemoryUsage) { scienceData->myImageList[chip][img]->freeAll(); } ++binnedChipCounter; #pragma omp atomic progress += progressStepSize; } if (binnedChipCounter == 0) continue; // skip inactive images QString outName = scienceData->myImageList[instData->validChip][img]->rootName; outName.append("_"+statusString+".mosaic.fits"); QString outDirName = scienceData->dirName+"/BINNED/"; QDir outDir(outDirName); if (!outDir.exists()) outDir.mkdir(outDirName); QFile out(outDirName+outName); if (out.exists()) out.remove(); MyImage *myBinnedImage = new MyImage(outDirName, outName, "", 1, QVector(), &verbosity); connect(myBinnedImage, &MyImage::critical, this, &Controller::criticalReceived); connect(myBinnedImage, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); connect(myBinnedImage, &MyImage::warning, this, &Controller::warningReceived); connect(myBinnedImage, &MyImage::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(myBinnedImage, &MyImage::setMemoryLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); myBinnedImage->naxis1 = nGlobal; myBinnedImage->naxis2 = mGlobal; myBinnedImage->dataCurrent.swap(dataBinnedGlobal); myBinnedImage->writeImage(outDirName+outName); // TODO: preserve for iView; set memory flags accordingly; could create myImageList and construct iView accordingly delete myBinnedImage; myBinnedImage = nullptr; } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } // Load the plot viewer emit loadViewer(scienceData->dirName+"/BINNED/", "*_"+scienceData->processingStatus->statusString+".mosaic.fits", "DragMode"); } THELI-3.1.3/src/processingInternal/processingCreateSourceCat.cc000066400000000000000000000517241417631501300244550ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "../tools/imagequality.h" #include "../tools/correlator.h" #include "photinst.h" #include "ui_confdockwidget.h" #include #include #include #include #include #include #include void Controller::taskInternalCreatesourcecat() { QString scienceDir = instructions.split(" ").at(1); QString updateMode = instructions.split(" ").at(2); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; // Ensure that the output path exists QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/"; mkAbsDir(outpath); pushBeginMessage(taskBasename, scienceDir); pushConfigCreatesourcecat(); memoryDecideDeletableStatus(scienceData, false); if (!scienceData->hasMatchingPartnerFiles(mainDirName+"/WEIGHTS/", ".weight.fits")) return; // Update coordinates if necessary. Leave if cancelled by the user bool check = manualCoordsUpdate(scienceData, updateMode); if (!check) return; QString minFWHM = cdw->ui->CSCFWHMLineEdit->text(); QString maxFlag = cdw->ui->CSCmaxflagLineEdit->text(); getNumberOfActiveImages(scienceData); // Cleanup the catalog directory from the results of a previous run scienceData->removeCatalogs(); // Check if exposures have unambiguous MJD-OBS keywords, otherwise the construction of scamp catalogs will fail if (!scienceData->collectMJD()) { emit messageAvailable("Duplicate MJD-OBS entries found!", "error"); emit criticalReceived(); return; } emit messageAvailable("Running source extraction ...", "data"); // INTERNAL if (cdw->ui->CSCMethodComboBox->currentText() == "THELI") { detectionInternal(scienceData, minFWHM, maxFlag); emit resetProgressBar(); progressStepSize = 100. / float(scienceData->exposureList.length()); mergeInternal(scienceData, minFWHM, maxFlag); } // EXTERNAL (SourceExtractor) else { detectionSourceExtractor(scienceData, minFWHM, maxFlag); emit resetProgressBar(); progressStepSize = 100. / float(scienceData->exposureList.length()); mergeSourceExtractor(scienceData); } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } } void Controller::detectionInternal(Data *scienceData, QString minFWHM, QString maxFlag) { // Parameters for source detection QString DT = cdw->ui->CSCDTLineEdit->text(); QString DMIN = cdw->ui->CSCDMINLineEdit->text(); QString background = cdw->ui->CSCbackgroundLineEdit->text(); bool convolution = cdw->ui->CSCconvolutionCheckBox->isChecked(); QString saturation = cdw->ui->CSCsaturationLineEdit->text(); // Create source catalogs for each exposure (keep them in memory!) /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { if (verbosity >=0 ) emit messageAvailable(it->baseName + " : Creating source catalog ...", "image"); it->setupDataInMemory(isTaskRepeated, true, true); it->backgroundModel(256, "interpolate"); it->segmentImage(DT, DMIN, convolution, false); it->writeCatalog(minFWHM, maxFlag); // filters out objects that don't match flag or fwhm incrementProgress(); } } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 4; // detection releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); #pragma omp parallel for num_threads(maxCPU) for (int k=0; kchipNumber - 1; if (!it->successProcessing) continue; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity > 1 ) emit messageAvailable(it->chipName + " : Creating source catalog ...", "image"); it->setupDataInMemorySimple(true); if (!it->successProcessing) { abortProcess = true; continue; } it->checkWCSsanity(); it->readWeight(); it->backgroundModel(256, "interpolate"); // it->updateSaturation(saturation); // Handled during splitting if (it->dataBackground.capacity() == 0) { if (successProcessing) emit messageAvailable(it->chipName + " : Background vector has zero capacity!", "error"); criticalReceived(); successProcessing = false; } it->segmentImage(DT, DMIN, convolution, false); it->releaseBackgroundMemory(); it->releaseDetectionPixelMemory(); it->calcMedianSeeingEllipticity(); // Also propagate to FITS header if file is on drive it->writeCatalog(minFWHM, maxFlag); // filters out objects that don't match flag or fwhm it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } if (it->successProcessing) { long nobj = it->objectList.length(); emitSourceCountMessage(nobj, it->chipName); if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long nReject = cdw->ui->CSCrejectExposureLineEdit->text().toLong(); if (nobj < nReject) { it->setActiveState(MyImage::LOWDETECTION); it->emitModelUpdateNeeded(); it->removeSourceCatalogs(); } } } else { scienceData->successProcessing = false; } #pragma omp atomic progress += progressStepSize; } // Deactivate exposures with low detections if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long numExpRejected = 0; long numImgRejected = 0; flagLowDetectionImages(scienceData, numExpRejected, numImgRejected); if (numImgRejected > 0) { QString addedString = ""; if (instData->numChips > 1) addedString = "("+QString::number(numImgRejected)+ " detector images)"; emit messageAvailable("
"+QString::number(numExpRejected) + " exposures "+addedString+ " deactivated " + "(low source count). Corresponding FITS files were moved to
" + scienceData->subDirName+"/inactive/lowDetections/
", "warning"); emit warningReceived(); } } } void Controller::detectionSourceExtractor(Data *scienceData, QString minFWHM, QString maxFlag) { buildSourceExtractorCommandOptions(); // Create source catalogs for each exposure /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { if (verbosity >=0 ) emit messageAvailable(it->baseName + " : Creating SourceExtractor catalog ...", "image"); it->setupDataInMemory(isTaskRepeated, true, true); it->buildSourceExtractorCommand(); it->sourceExtractorCommand.append(sourceExtractorCommandOptions); it->createSourceExtractorCatalog(); it->filterSourceExtractorCatalog(minFWHM, maxFlag); it->sourceExtractorCatToIview(); incrementProgress(); } } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 4; // some breathing space for SourceExtractor releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); #pragma omp parallel for num_threads(maxCPU) for (int k=0; kchipNumber - 1; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity > 1) emit messageAvailable(it->chipName + " : Creating source catalog ...", "image"); it->setupDataInMemorySimple(true); if (!it->successProcessing) { abortProcess = true; continue; } it->checkWCSsanity(); it->buildSourceExtractorCommand(); it->sourceExtractorCommand.append(sourceExtractorCommandOptions); if (!it->imageOnDrive) it->writeImage(); // Must be on drive for SourceExtractor it->createSourceExtractorCatalog(); it->filterSourceExtractorCatalog(minFWHM, maxFlag); it->calcMedianSeeingEllipticitySex(); it->sourceExtractorCatToIview(); it->sourceExtractorCatToAnet(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } if (it->successProcessing) { long nobj = getNumObjectsSourceExtractorCat(it->path+"/cat/"+it->chipName+".cat"); emitSourceCountMessage(nobj, it->chipName); if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long nReject = cdw->ui->CSCrejectExposureLineEdit->text().toLong(); if (nobj < nReject) { it->setActiveState(MyImage::LOWDETECTION); it->emitModelUpdateNeeded(); it->removeSourceCatalogs(); } } } else { scienceData->successProcessing = false; successProcessing = false; } #pragma omp atomic progress += progressStepSize; } // Deactivate exposures with low detections if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long numExpRejected = 0; long numImgRejected = 0; flagLowDetectionImages(scienceData, numExpRejected, numImgRejected); if (numImgRejected > 0) { QString addedString = ""; if (instData->numChips > 1) addedString = "("+QString::number(numImgRejected)+ " detector images)"; emit messageAvailable("
"+QString::number(numExpRejected) + " exposures "+addedString+ " deactivated " + "(low source count). Corresponding FITS files were moved to
" + scienceData->subDirName+"/inactive/lowDetections/", "warning"); emit warningReceived(); } } } void Controller::emitSourceCountMessage(long &nobj, QString baseName) { // Color-coding output lines QString detStatus = ""; QString level = "image"; if (nobj<10 && nobj>3) { detStatus = " (low source count)"; level = "warning"; } if (nobj<=3) { detStatus = " (very low source count)"; level = "stop"; } emit messageAvailable(baseName + " : " + QString::number(nobj) + " sources detected..."+detStatus, level); } void Controller::flagLowDetectionImages(Data *scienceData, long &numExpRejected, long &numImgRejected) { numExpRejected = 0; numImgRejected = 0; scienceData->populateExposureList(); int numExposures = scienceData->exposureList.length(); for (long i=0; iexposureList[i]) { if (it->activeState == MyImage::LOWDETECTION) { exposureIsBad = true; break; } } // Reject all chips if a single one is bad if (exposureIsBad) { for (auto &it : scienceData->exposureList[i]) { ++numImgRejected; if (it->activeState != MyImage::LOWDETECTION) { it->setActiveState(MyImage::LOWDETECTION); it->emitModelUpdateNeeded(); it->removeSourceCatalogs(); } it->emitModelUpdateNeeded(); } ++numExpRejected; } } } void Controller::mergeInternal(Data *scienceData, QString minFWHM, QString maxFlag) { scienceData->populateExposureList(); emit messageAvailable("Merging source catalogs ...", "controller"); for (long i=0; iexposureList.length(); ++i) { // if one detector has been rejected due to low source counts, then skip this exposure bool lowCounts = false; int inactiveCounter = 0; for (auto &it : scienceData->exposureList[i]) { if (it->activeState == MyImage::LOWDETECTION) lowCounts = true; if (!it->isActive()) ++inactiveCounter; } // WARNING: skipping images where some detectors have no data / deactivated if (lowCounts || inactiveCounter > 0) { emit messageAvailable(scienceData->exposureList[i][0]->rootName + " : Omitted. One or more images inactive or with low counts.", "warning"); continue; } fitsfile *fptr; int status = 0; QString filename = scienceData->dirName+"/cat/"+scienceData->exposureList[i][0]->rootName+".scamp"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); int counter = 0; for (auto &it : scienceData->exposureList[i]) { // Exclude inactive exposures // if (!it->isActive()) continue; it->appendToScampCatalogInternal(fptr, minFWHM, maxFlag); ++counter; } // if (counter != instData->numChips) { if (counter != instData->numUsedChips) { emit messageAvailable(scienceData->exposureList[i][0]->rootName + " : Merged only " + QString::number(counter) + " out of " + QString::number(instData->numUsedChips) + " catalogs for scamp!", "error"); emit criticalReceived(); } fits_close_file(fptr, &status); printCfitsioError(__func__, status); #pragma omp atomic progress += progressStepSize; } } void Controller::mergeSourceExtractor(Data *scienceData) { // Merge SourceExtractor catalogs to final scamp catalog // Loop over exposures scienceData->populateExposureList(); emit messageAvailable("Merging source catalogs ...", "controller"); progress = 0.; progressStepSize = 100./float(scienceData->exposureList.length()); #pragma omp parallel for num_threads(maxCPU) for (long i=0; iexposureList.length(); ++i) { if (abortProcess || !successProcessing) continue; // if one detector has been rejected due to low source counts, then skip this exposure bool lowCounts = false; for (auto &it : scienceData->exposureList[i]) { if (it->activeState == MyImage::LOWDETECTION) lowCounts = true; } if (lowCounts) continue; fitsfile *fptr; int status = 0; QString filename = scienceData->dirName+"/cat/"+scienceData->exposureList[i][0]->rootName+".scamp"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); for (auto &it : scienceData->exposureList[i]) { it->appendToScampCatalogSourceExtractor(fptr); if (!it->successProcessing) scienceData->successProcessing = false; } fits_close_file(fptr, &status); printCfitsioError(__func__, status); #pragma omp atomic progress += progressStepSize; } } void Controller::buildSourceExtractorCommandOptions() { // This builds the major part of the SourceExtractor command based on the chosen GUI settings. // The MyImage class adds the variable rest (catalog name, weight name, image name) if (!successProcessing) return; sourceExtractorCommandOptions = " -PARAMETERS_NAME " + thelidir + "/config/default.param"; sourceExtractorCommandOptions += " -FILTER_NAME " + thelidir + "/config/default.conv"; sourceExtractorCommandOptions += " -STARNNW_NAME " + thelidir + "/config/default.nnw"; sourceExtractorCommandOptions += " -DETECT_MINAREA " + getUserParamLineEdit(cdw->ui->CSCDMINLineEdit); sourceExtractorCommandOptions += " -DETECT_THRESH " + getUserParamLineEdit(cdw->ui->CSCDTLineEdit); sourceExtractorCommandOptions += " -ANALYSIS_THRESH " + getUserParamLineEdit(cdw->ui->CSCDTLineEdit); sourceExtractorCommandOptions += " -FILTER " + getUserParamCheckBox(cdw->ui->CSCconvolutionCheckBox); sourceExtractorCommandOptions += " -DEBLEND_MINCONT " + getUserParamLineEdit(cdw->ui->CSCmincontLineEdit); sourceExtractorCommandOptions += " -SATUR_LEVEL " + getUserParamLineEdit(cdw->ui->CSCsaturationLineEdit); sourceExtractorCommandOptions += " -CATALOG_TYPE FITS_LDAC"; sourceExtractorCommandOptions += " -WEIGHT_TYPE MAP_WEIGHT "; sourceExtractorCommandOptions += " -PIXEL_SCALE 0.0 "; QString backString = cdw->ui->CSCbackgroundLineEdit->text(); if (backString.isEmpty()) sourceExtractorCommandOptions += " -BACK_TYPE AUTO " ; else sourceExtractorCommandOptions += " -BACK_TYPE MANUAL -BACK_VALUE "+backString; } bool Controller::manualCoordsUpdate(Data *scienceData, QString mode) { if (!successProcessing) return false; if (mode == "Cancel") return false; if (mode.isEmpty() || mode == "empty") return true; QString targetAlpha = cdw->ui->ARCraLineEdit->text(); QString targetDelta = cdw->ui->ARCdecLineEdit->text(); if (targetAlpha.contains(':')) targetAlpha = hmsToDecimal(targetAlpha); if (targetDelta.contains(':')) targetDelta = dmsToDecimal(targetDelta); emit messageAvailable("Updating WCS:", "controller"); if (mode == "crval") { emit messageAvailable("CRVAL1 = "+targetAlpha + "
" + "CRVAL2 = "+targetDelta, "data"); } else if (mode == "crval+cd") { emit messageAvailable("CRVAL1 = "+targetAlpha + "
" + "CRVAL2 = "+targetDelta + "
" + "CD1_1 = "+QString::number(-1.*instData->pixscale/3600.) + "
" + "CD1_2 = 0.0
" + "CD2_1 = 0.0
" + "CD2_2 = "+QString::number(instData->pixscale/3600.), "data"); } getNumberOfActiveImages(scienceData); QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); #pragma omp parallel for num_threads(maxCPU) for (int k=0; kchipNumber - 1; if (instData->badChips.contains(chip)) continue; if (!it->successProcessing) continue; it->loadHeader(); if (!it->successProcessing) { abortProcess = true; continue; } // TODO: should be sufficient, but crashes when executed right after launch // it->loadHeader(); if (mode == "crval") { it->wcs->crval[0] = targetAlpha.toDouble(); it->wcs->crval[1] = targetDelta.toDouble(); it->wcs->flag = 0; it->updateCRVALinHeader(); it->updateCRVALinHeaderOnDrive(); } if (mode == "crval+cd") { it->wcs->crval[0] = targetAlpha.toDouble(); it->wcs->crval[1] = targetDelta.toDouble(); it->wcs->cd[0] = -1.*it->plateScale/3600.; it->wcs->cd[1] = 0.; it->wcs->cd[2] = 0.; it->wcs->cd[3] = it->plateScale/3600.; it->wcs->flag = 0; it->updateCRVALCDinHeader(); it->updateCRVALCDinHeaderOnDrive(); } if (!it->successProcessing) scienceData->successProcessing = false; #pragma omp atomic progress += progressStepSize; } successProcessing = true; // emit appendOK(); return true; } THELI-3.1.3/src/processingInternal/processingSkysub.cc000066400000000000000000000734361417631501300227250ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include #include #include #include #include void Controller::taskInternalSkysub() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; memoryDecideDeletableStatus(scienceData, false); if (!scienceData->hasMatchingPartnerFiles(mainDirName+"/WEIGHTS/", ".weight.fits")) return; // Loop over all chips backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; // Parameters for sky subtraction QString DT = cdw->ui->skyDTLineEdit->text(); QString DMIN = cdw->ui->skyDMINLineEdit->text(); QString expFactor = cdw->ui->skyMefLineEdit->text(); QString kernelWidth = cdw->ui->skyKernelLineEdit->text(); // Polyfit: read the sky values here, do the polynomial fit, store the gsl_vector with the solution // and evaluate inside the function getNumberOfActiveImages(scienceData); scienceData->cleanBackgroundModelStatus(); bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; if (cdw->ui->skyModelRadioButton->isChecked()) { skysubModel(scienceData, DT, DMIN, expFactor, kernelWidth); } else if (cdw->ui->skyPolynomialRadioButton->isChecked()) { skysubPolynomialFit(scienceData); } else if (cdw->ui->skyConstsubRadioButton->isChecked()) { if (cdw->ui->skyAreaComboBox->currentIndex() == 0) { skysubConstantFromArea(scienceData); } else if (cdw->ui->skyAreaComboBox->currentIndex() == 1) { skysubConstantEachChip(scienceData, DT, DMIN, expFactor, kernelWidth); } else { skysubConstantReferenceChip(scienceData, DT, DMIN, expFactor, kernelWidth); } } else { // Other methods to be implemented } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { scienceData->processingStatus->Skysub = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header // pushEndMessage(taskBasename, scienceDir); } } void Controller::skysubPolynomialFit(Data *scienceData) { if (!successProcessing) return; pushBeginMessage("SkysubPoly", scienceData->subDirName); pushConfigSkysubPoly(); scienceData->populateExposureList(); // Measure the sky in all blank regions, update the list of sky nodes in each chip QList ignoreReturnValue = measureSkyInBlankRegions(scienceData); // Loop over all exposures int order = cdw->ui->skyPolynomialSpinBox->value(); int numExposures = scienceData->exposureList.length(); // Overriding getNumberOfActiveImages() progressStepSize = 100. / (float) numExposures; float nimg = 4; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numExposures, instData->storageExposure); #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName) for (long i=0; i> skyPolyfitNodes; // Collect sky nodes from all images belonging to that exposure for (auto &it : scienceData->exposureList[i]) { int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (!it->successProcessing) continue; skyPolyfitNodes.append(it->skyPolyfitNodes); } // Fit a polynomial to the nodes, subtract the model from the images Fitting skyFit; connect(&skyFit, &Fitting::messageAvailable, this, &Controller::messageAvailableReceived); skyFit.makePolynomialFit2D(order, skyPolyfitNodes); if (!skyFit.FITSUCCESS) continue; // TODO: large multi-chip cameras would profit from an internal parallelization // I THINK a simple '#pragma omp for' would take care of this automatically for (auto &it : scienceData->exposureList[i]) { if (abortProcess) break; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); // Already done in measureSkyInBlankRegions; // Does nothing if image is still in memory. // If not in memory, will just read it again from drive it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->subtractSkyFit(order, skyFit.c, cdw->ui->skySavemodelCheckBox->isChecked()); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); emit messageAvailable(it->chipName + " : <sky> = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); #pragma omp atomic progress += progressStepSize; } } } void Controller::skysubConstantFromArea(Data *scienceData) { if (!successProcessing) return; pushBeginMessage("SkysubConst", scienceData->subDirName); pushConfigSkysubConst(); // scienceData->populateExposureList(); // Measure the sky in all blank regions, update the list of sky nodes in each chip QList listOfAllImages = measureSkyInBlankRegions(scienceData); emit messageAvailable("Calculating mean sky level per exposure ...", "controller"); int numExposures = scienceData->exposureList.length(); doDataFitInRAM(numExposures, instData->storageExposure); progressStepSize = 50. / float(scienceData->exposureList.length()); // Loop over all exposures (consisting of n chips) #pragma omp parallel for num_threads(maxCPU) for (long i=0; i skyBackground; for (auto &it : scienceData->exposureList[i]) { int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; if (!it->successProcessing) continue; for (auto &position : it->skyPolyfitNodes) { skyBackground.append(position[2]); } } float meanExposureBackground; if (skyBackground.isEmpty()) { QString part1 = scienceData->exposureList[i][0]->rootName; emit showMessageBox("Controller::NO_OVERLAP_WITH_SKYAREA", part1, ""); meanExposureBackground = 0.; successProcessing = false; continue; } else { meanExposureBackground = meanMask(skyBackground); } for (auto &it : scienceData->exposureList[i]) { int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; if (!it->successProcessing) continue; it->meanExposureBackground = meanExposureBackground; emit messageAvailable(it->chipName + " : <sky> = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); // sky subtraction outsourced below for faster parallelisation } #pragma omp atomic progress += progressStepSize; } if (!successProcessing) return; progressStepSize = 50. / float(listOfAllImages.length()); float nimg = 3; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); emit messageAvailable("Subtracting mean sky level ...", "controller"); // In principle this could be done in nicer form by including it in the last for-loop above #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName) for (long i=0; ichipNumber - 1; if (instData->badChips.contains(chip)) continue; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; releaseMemory(nimg*instData->storage, maxCPU); // Already done in measureSkyInBlankRegions; // Does nothing if image is still in memory. // If not in memory, will just read it again from drive it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->subtract(it->meanExposureBackground); it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeConstSkyImage(it->meanExposureBackground); } it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } emit messageAvailable(it->chipName + " : <sky> = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); #pragma omp atomic progress += progressStepSize; } } void Controller::skysubConstantReferenceChip(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth) { if (!successProcessing) return; pushBeginMessage("SkysubConst", scienceData->subDirName); pushConfigSkysubConst(); scienceData->populateExposureList(); // TODO: add a mode that does not require blank sky fields (i.e., if no coords file found, use entire chip) // Measure the sky in all blank regions, update the list of sky nodes in each chip QList listOfAllImages = measureSkyInBlankRegions(scienceData, "listOnly"); int referenceChip = cdw->ui->skyAreaComboBox->currentIndex(); if (referenceChip < 2) { emit messageAvailable("Controller::skysubConstantReferenceChip(): invalid chip index returned. This is a bug.", "error"); criticalReceived(); successProcessing = false; return; } // Calculate the corrrect chip number (subtract the first two entries of the combo box) referenceChip -= 2; // Loop over all exposures (consisting of n chips) int kernel = kernelWidth.toInt(); if (!kernel) { // a kernel width of zero will cause a floating-point-exception // in the calculation of grid points for background modelling emit messageAvailable("Controller::skysubModel(): Kernel width is zero", "error"); criticalReceived(); return; } // Create object masks (does not change pixels) progressStepSize = 50. / float(scienceData->exposureList.length()); float nimg = 5; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); int numExposures = scienceData->exposureList.length(); doDataFitInRAM(numExposures, instData->storageExposure); #pragma omp parallel for num_threads(maxCPU) firstprivate(DT, DMIN, expFactor) for (long i=0; istorage, maxCPU); // Measure the sky background from the reference chip auto &it = scienceData->exposureList[i][referenceChip]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; // Already done in measureSkyInBlankRegions; // Does nothing if image is still in memory. // If not in memory, will just read it again from drive it->setupData(scienceData->isTaskRepeated, false, false); if (!it->successProcessing) { abortProcess = true; continue; } it->resetObjectMasking(); it->backgroundModelDone = false; it->readWeight(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); it->mergeObjectWithGlobalMask(); if (!it->successProcessing) scienceData->successProcessing = false; float meanExposureBackground = modeMask(it->dataCurrent, "stable", it->objectMask)[0]; emit messageAvailable(scienceData->exposureList[0][0]->rootName + " : Exposure background = " + QString::number(meanExposureBackground,'f',2), "image"); for (auto &it : scienceData->exposureList[i]) { it->meanExposureBackground = meanExposureBackground; } it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } it->releaseBackgroundMemory("entirely"); it->releaseAllDetectionMemory(); #pragma omp atomic progress += progressStepSize; } if (!successProcessing) return; // Subtract sky (does change pixels) progressStepSize = 50. / float(listOfAllImages.length()); #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName) for (long i=0; isuccessProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; emit messageAvailable(it->chipName + " : <sky> = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->subtract(it->meanExposureBackground); it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeConstSkyImage(it->meanExposureBackground); } it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } #pragma omp atomic progress += progressStepSize; } } void Controller::skysubConstantEachChip(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth) { if (!successProcessing) return; // Loop over all exposures (consisting of n chips) int kernel = kernelWidth.toInt(); if (!kernel) { // a kernel width of zero will cause a floating-point-exception // in the calculation of grid points for background modelling emit messageAvailable("Controller::skysubModel(): Kernel width is zero", "error"); criticalReceived(); return; } pushBeginMessage("SkysubConst", scienceData->subDirName); pushConfigSkysubConst(); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { it->setupDataInMemory(isTaskRepeated, true, true); it->resetObjectMasking(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); it->mergeObjectWithGlobalMask(); float meanExposureBackground = modeMask(it->dataCurrent, "stable", it->objectMask)[0]; it->subtract(meanExposureBackground); it->statusCurrent = statusNew; it->baseName = it->chipName + statusNew; it->writeImage(); emit messageAvailable(it->baseName + " : sky = "+QString::number(meanExposureBackground,'f',2), "controller"); incrementProgress(); } if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } decrementCurrentThreads(lock); } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); progressStepSize = 100. / float(numMyImages); float nimg = 5; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); #pragma omp parallel for num_threads(maxCPU) firstprivate(DT, DMIN, expFactor, backupDirName) for (int k=0; kstorage, maxCPU); auto &it = allMyImages[k]; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->resetObjectMasking(); it->backgroundModelDone = false; it->readWeight(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); it->mergeObjectWithGlobalMask(); float meanExposureBackground = modeMask(it->dataCurrent, "stable", it->objectMask)[0]; it->subtract(meanExposureBackground); it->saturationValue -= meanExposureBackground; it->updateHeaderSaturation(); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeConstSkyImage(meanExposureBackground); } it->unprotectMemory(); it->releaseBackgroundMemory("entirely"); it->releaseAllDetectionMemory(); if (minimizeMemoryUsage) { it->freeAll(); } emit messageAvailable(it->chipName + " : <sky> = " + QString::number(meanExposureBackground,'f',2) + " e-", "image"); #pragma omp atomic progress += progressStepSize; } /* // Just file moving, no parallelization required for (int chip=0; chipnumChips; ++chip) { if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); // scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } } */ } void Controller::skysubModel(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth) { if (!successProcessing) return; pushBeginMessage("SkysubModel", scienceData->subDirName); pushConfigSkysubModel(); int kernel = kernelWidth.toInt(); if (!kernel) { // a kernel width of zero will cause a floating-point-exception // in the calculation of grid points for background modelling emit messageAvailable("Controller::skysubModel(): Kernel width is zero", "error"); criticalReceived(); return; } /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { emit messageAvailable(it->baseName + " : Modeling the sky ...", "controller"); it->setupDataInMemory(isTaskRepeated, true, true); it->readWeight(); // Model background so we can detect objects it->resetObjectMasking(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); // Model background once more, including object masks, and detect objects it->backgroundModel(kernel, "interpolate"); it->resetObjectMasking(); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); // Model background once more, including object masks, and subtract it from the image it->backgroundModel(kernel, "interpolate"); it->subtractBackgroundModel(); it->freeAncillaryData(it->dataBackground); // We don't need that anymore it->statusCurrent = statusNew; it->baseName = it->chipName + statusNew; // it->freeAncillaryData(it->dataSegmentation); // We don't need that anymore // boolean it->writeImage(); incrementProgress(); } if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); scienceData->memorySetDeletable(chip, "dataBackupL1", true); scienceData->memorySetDeletable(chip, "databackgroundL1", true); // potential double free? see 10 lines above } } decrementCurrentThreads(lock); } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); progressStepSize = 100. / float(numMyImages); float nimg = 5; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); emit messageAvailable(" Calculating sky models ...", "controller"); #pragma omp parallel for num_threads(maxCPU) firstprivate(DT, DMIN, expFactor, backupDirName) for (int k=0; kstorage, maxCPU); auto &it = allMyImages[k]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; // emit messageAvailable(it->baseName + " : Modeling the sky ...", "controller"); it->processingStatus->Skysub = false; // it->setupData(scienceData->isTaskRepeated, false, true, backupDirName); it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->readWeight(); // Model background so we can detect objects it->resetObjectMasking(); it->backgroundModelDone = false; it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); // Model background once more, including object masks, and detect objects it->backgroundModelDone = false; it->backgroundModel(kernel, "interpolate"); it->resetObjectMasking(); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); // overwrites previous mask it->maskExpand(expFactor, false); // false -> true to write the mask FITS files // Model background once more, including object masks, and subtract it from the image it->backgroundModelDone = false; it->backgroundModel(kernel, "interpolate"); it->subtractBackgroundModel(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeBackgroundModel(); } it->getMeanBackground(); it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); if (!isnan(it->meanExposureBackground)) { emit messageAvailable(it->chipName + " : <sky> = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); } else { emit messageAvailable(it->chipName + " : <sky> = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "warning"); warningReceived(); it->setActiveState(MyImage::BADBACK); continue; } it->releaseAllDetectionMemory(); it->releaseBackgroundMemory("entirely"); updateImageAndData(it, scienceData); // Must write for SWarp it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } #pragma omp atomic progress += progressStepSize; } /* // Just file moving, no parallelization required for (int chip=0; chipnumChips; ++chip) { if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); // scienceData->memorySetDeletable(chip, "dataBackupL1", true); // scienceData->memorySetDeletable(chip, "databackgroundL1", true); // potential double free? see 10 lines above } } } */ } QList Controller::measureSkyInBlankRegions(Data *scienceData, QString method) { QList listOfAllImages; if (!successProcessing) return listOfAllImages; emit messageAvailable("Measuring sky level in user-defined areas ...", "controller"); // Measure background at all sky positions // For full parallelisation, I collapse the loops. Since some images from some detectors might // have been removed, the loops are not prefectly rectangular // (one could use a 'continue' statement, though, but would have to determine the max number of exposures per chip for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; listOfAllImages.append(it); } } if (listOfAllImages.isEmpty()) { successProcessing = false; return listOfAllImages; } if (method.isEmpty()) { QVector alpha; QVector delta; QVector radius; // Retrieve sky positions from maindir/subdir/skysamples.dat if (verbosity > 1) emit messageAvailable("Reading blank sky positions from " + scienceData->dirName+"/skysamples.dat", "controller"); if (!readData3D(scienceData->dirName+"/skysamples.dat", alpha, delta, radius) || alpha.isEmpty()) { if (verbosity > 1) emit messageAvailable("Fallback: Reading blank sky positions from " + mainDirName+"/skysamples.dat", "controller"); if (!readData3D(mainDirName+"/skysamples.dat", alpha, delta, radius) || alpha.isEmpty()) { QString part1 = scienceData->dirName; emit showMessageBox("Controller::SKY_FILE_NOT_FOUND", part1, ""); successProcessing = false; return listOfAllImages; } } #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName, alpha, delta, radius) for (int i=0; isetupData(scienceData->isTaskRepeated, false, true, backupDirName); // 'false': do not move images to backup dir yet listOfAllImages[i]->evaluateSkyNodes(alpha, delta, radius); listOfAllImages[i]->unprotectMemory(); if (minimizeMemoryUsage) { listOfAllImages[i]->freeAll(); } } } // Get all images that belong to one exposure (number could vary from exposure to exposure) scienceData->populateExposureList(); return listOfAllImages; } THELI-3.1.3/src/processingInternal/processingSplitter.cc000066400000000000000000000436331417631501300232470ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/splitter.h" #include "ui_confdockwidget.h" #include "fitsio.h" #include #include #include #include void Controller::taskInternalHDUreformat() { if (!successProcessing) return; QString dataDir = instructions.split(" ").at(1); currentDirName = dataDir; Data *data = getDataAll(dataDir); if (data == nullptr) return; // Error triggered by getDataAll(); data->numImages = 0; pushBeginMessage(taskBasename, dataDir); pushConfigHDUreformat(); // Obtain a list of files in this directory, including non-FITS files QString path = mainDirName + "/" + dataDir; QDir dir(path); QStringList filter; filter << "*.*"; QStringList files = dir.entryList(filter, QDir::Files); numActiveImages = files.length(); progressStepSize = 100./(float(numActiveImages) * instData->numChips); progress = 0.; // Saturation value float userSaturationValue = 0.; if (!cdw->ui->saturationLineEdit->text().isEmpty()) { userSaturationValue = cdw->ui->saturationLineEdit->text().toFloat(); } // Retrieve nonlinearity information (checks internally if available, otherwise returns empty list) QList> nonlinearityCoefficients; if (cdw->ui->nonlinearityCheckBox->isChecked()) { nonlinearityCoefficients = getNonlinearityCoefficients(); } // DUMMY keywords, and others needed later-on QStringList dummyKeys; QString newCard; newCard = "FWHM = -1.0"; newCard.resize(80, ' '); dummyKeys.append(newCard); newCard = "ELLIP = -1.0"; newCard.resize(80, ' '); dummyKeys.append(newCard); newCard = "RZP = -1.0"; newCard.resize(80, ' '); dummyKeys.append(newCard); for (int i=0; i<20; ++i) { QString newCard = "DUMMY"+QString::number(i+1); newCard.resize(8, ' '); newCard.append("= 0.0 / Placeholder card"); newCard.resize(80, ' '); dummyKeys.append(newCard); } QString dataType = data->dataType; // Stop memory bar. Updated internally because data classes are not yet available // Must use signals instead, timer lives in a different thread // memTimer->stop(); float dateObsIncrementor = 0; bool commaDetected = false; // Loop over all chips #pragma omp parallel for num_threads(maxCPU) firstprivate(mainDirName, dataDir, dummyKeys, nonlinearityCoefficients, headerDictionary, filterDictionary, dataType) for (int i=0; iheaderDictionary = headerDictionary; splitter->filterDictionary = filterDictionary; splitter->instrumentDictionary = instrumentDictionary; splitter->dummyKeys = dummyKeys; splitter->combineOverscan_ptr = combineOverscan_ptr; // set by MainWindow::updateControllerFunctors() splitter->nonlinearityCoefficients = nonlinearityCoefficients; splitter->progressStepSize = progressStepSize; splitter->progressLock = &progressLock; splitter->genericLock = &genericLock; splitter->progress = &progress; splitter->dateObsIncrementor = &dateObsIncrementor; splitter->userSaturationValue = userSaturationValue; splitter->compileNumericKeys(); connect(splitter, &Splitter::messageAvailable, this, &Controller::messageAvailableReceived); connect(splitter, &Splitter::critical, this, &Controller::criticalReceived); connect(splitter, &Splitter::warning, this, &Controller::warningReceived); connect(splitter, &Splitter::showMessageBox, this, &Controller::showMessageBoxReceived); // Extract images. This also handles all low-level pixel processing. splitter->determineFileFormat(); splitter->extractImages(); if (splitter->commaDetected) commaDetected = true; if (!splitter->successProcessing) successProcessing = false; delete splitter; // Hogging lots of memory otherwise! splitter = nullptr; // splitter handles the progress counter // No memory management needed, splitter simply runs out of scope } checkSuccessProcessing(data); if (verbosity > 1 && commaDetected) { emit messageAvailable("Decimal commas found in raw data, converted to decimal dots in output.", "warning"); emit warningReceived(); } if (successProcessing) { uniformMJDOBS(dir); // rename file and update MJDOBS for a few specific instruments, only if (!updateDataDirs(data)) { // Some instruments need to split the original data dir into several more, e.g. GROND and LIRIS_POL finalizeSplitter(data); } emit progressUpdate(100); } // Restart memory bar // memTimer->start(1000); } void Controller::finalizeSplitter(Data *data) { data->processingStatus->HDUreformat = true; data->processingStatus->writeToDrive(); if (!data->dataInitialized) { data->dataInitialized = true; data->populate("P"); } for (int chip=0; chipnumChips; ++chip) { for (auto &it : data->myImageList[chip]) { it->processingStatus->HDUreformat = true; } } data->emitStatusChanged(); emit populateMemoryView(); } // Multi-chip cameras must have uniform MJD-OBS, otherwise "exposures" cannot be identified unambiguously // The following instruments do not have this void Controller::uniformMJDOBS(QDir &dir) { if (instData->name == "VIMOS@VLT" // VIMOS has no unique DATE-OBS || instData->name.contains("MOIRCS")) { // MOIRCS has no unique DATE-OBS QString path = dir.absolutePath(); QStringList filter = {instData->shortName+"*.fits"}; dir.setNameFilters(filter); dir.setSorting(QDir::Name); QStringList fileNames = dir.entryList(); char filterChip1[80]; char dateObsChip1[80]; double mjdObsChip1 = 0.; for (auto &fileName : fileNames) { QFileInfo fi(path+"/"+fileName); QString baseName = fi.completeBaseName(); int pos = baseName.lastIndexOf('_'); QString chipNumber = baseName.remove(0,pos).remove('_').remove("P"); fitsfile *fptr; int status = 0; QString completeName = path+"/"+fileName; fits_open_file(&fptr, completeName.toUtf8().data(), READWRITE, &status); // Extract DATE-OBS and MJD-OBS from chip 1 if (chipNumber == "1") { fits_read_key_str(fptr, "DATE-OBS", dateObsChip1, nullptr, &status); fits_read_key_str(fptr, "FILTER", filterChip1, nullptr, &status); fits_read_key_dbl(fptr, "MJD-OBS", &mjdObsChip1, nullptr, &status); } // Project DATE-OBS and MJD-OBS from chip 1 onto other chips else { fits_update_key_str(fptr, "DATE-OBS", dateObsChip1, nullptr, &status); fits_update_key_dbl(fptr, "MJD-OBS", mjdObsChip1, -13, nullptr, &status); // the '-' enforces floating point notation over exponential notation } if (chipNumber == "1") { // make double sure that in chip one we have exactly the same format and number of digits as in the other chips! fits_update_key_dbl(fptr, "MJD-OBS", mjdObsChip1, -13, nullptr, &status); } fits_close_file(fptr, &status); printCfitsioError(__func__, status); // Rename image file to THELI standard QString dateObsString(dateObsChip1); QString filterString(filterChip1); QFile file(path+"/"+fileName); file.rename(path+"/"+instData->shortName+"."+filterString+"."+dateObsString+"_"+chipNumber+"P.fits"); } } } bool Controller::updateDataDirs(Data *data) { bool updateDataDirDone = false; QLineEdit *le = nullptr; QString newDirs = ""; QString d = data->subDirName; // Erase and update the data tree LineEdits if (instData->name == "LIRIS_POL@WHT") { newDirs = d+"_PA000 "; newDirs.append(d+"_PA045 "); newDirs.append(d+"_PA090 "); newDirs.append(d+"_PA135"); le = getDataTreeLineEdit(data); } if (instData->name == "GROND_OPT@MPGESO") { newDirs = d+"_g "; newDirs.append(d+"_r "); newDirs.append(d+"_i "); newDirs.append(d+"_z "); le = getDataTreeLineEdit(data); } if (instData->name == "GROND_NIR@MPGESO") { newDirs = d+"_J "; newDirs.append(d+"_H "); newDirs.append(d+"_K"); le = getDataTreeLineEdit(data); } if (instData->name == "PISCO@LCO") { newDirs = d+"_g "; newDirs.append(d+"_r "); newDirs.append(d+"_i "); newDirs.append(d+"_z "); le = getDataTreeLineEdit(data); } if (le != nullptr) { le->clear(); le->setText(newDirs); if (!mainGUI->checkPathsLineEdit(le)) { le->clear(); return false; // return if some data do not exist (e.g. optical GROND might not have darks, but NIR does) } dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); // emit clearMemoryView(); // Manipulate sobject in different thread despite just emitting a signal. Strange mainDirName = mainGUI->ui->setupMainLineEdit->text(); recurseCounter = 0; QList *DT_x; // = new QList(); if (data->dataType == "BIAS") DT_x = &DT_BIAS; else if (data->dataType == "DARK") DT_x = &DT_DARK; else if (data->dataType == "FLATOFF") DT_x = &DT_FLATOFF; else if (data->dataType == "FLAT") DT_x = &DT_FLAT; else if (data->dataType == "SCIENCE") DT_x = &DT_SCIENCE; else if (data->dataType == "SKY") DT_x = &DT_SKY; else { // data->dataType == "STD") DT_x = &DT_STANDARD; } updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; for (auto &data : *DT_x) { finalizeSplitter(data); } updateDataDirDone = true; // delete DT_x; } return updateDataDirDone; } QLineEdit* Controller::getDataTreeLineEdit(Data *data) { QLineEdit *le = nullptr; if (data->dataType == "BIAS") le = mainGUI->ui->setupBiasLineEdit; else if (data->dataType == "DARK") le = mainGUI->ui->setupDarkLineEdit; else if (data->dataType == "FLATOFF") le = mainGUI->ui->setupFlatoffLineEdit; else if (data->dataType == "FLAT") le = mainGUI->ui->setupFlatLineEdit; else if (data->dataType == "SCIENCE") le = mainGUI->ui->setupScienceLineEdit; else if (data->dataType == "SKY") le = mainGUI->ui->setupSkyLineEdit; else if (data->dataType == "STD") le = mainGUI->ui->setupStandardLineEdit; else { // nothing to be done } return le; } // copied from MainWindow void Controller::resetAltInstrumentData() { altInstData.numChips = 1; altInstData.numUsedChips = 1; altInstData.name = ""; altInstData.shortName = ""; altInstData.nameFullPath = ""; altInstData.obslat = 0.; altInstData.obslon = 0.; altInstData.bayer = ""; altInstData.type = "OPT"; altInstData.pixscale = 1.0; // in arcsec // altInstData.gain = 1.0; altInstData.radius = 0.1; // exposure coverage radius in degrees altInstData.storage = 0; // MB used for a single image altInstData.storageExposure = 0.; // MB used for the entire (multi-chip) exposure altInstData.overscan_xmin.clear(); altInstData.overscan_xmax.clear(); altInstData.overscan_ymin.clear(); altInstData.overscan_ymax.clear(); altInstData.cutx.clear(); altInstData.cuty.clear(); altInstData.sizex.clear(); altInstData.sizey.clear(); altInstData.crpix1.clear(); altInstData.crpix2.clear(); } // copied and modified (shortened) from MainWindow, to handle the two GROND detector types void Controller::initAltInstrumentData(QString instrumentNameFullPath) { resetAltInstrumentData(); QFile altInstDataFile(instrumentNameFullPath); altInstDataFile.setFileName(instrumentNameFullPath); altInstData.nameFullPath = instrumentNameFullPath; // read the instrument specific data if( !altInstDataFile.open(QIODevice::ReadOnly)) { emit messageAvailable("Controller::initAltInstrumentData(): "+instrumentNameFullPath+" "+altInstDataFile.errorString(), "error"); return; } bool bayerFound = false; QTextStream in(&(altInstDataFile)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty() || line.contains("#")) continue; // scalars if (line.contains("INSTRUMENT=")) altInstData.name = line.split("=")[1]; if (line.contains("INSTSHORT=")) altInstData.shortName = line.split("=")[1]; if (line.contains("NCHIPS=")) altInstData.numChips = line.split("=")[1].toInt(); if (line.contains("TYPE=")) altInstData.type = line.split("=")[1]; if (line.contains("BAYER=")) { // BAYER is not mandatory; if not found, we must set it to blank altInstData.bayer = line.split("=")[1]; bayerFound = true; } if (line.contains("OBSLAT=")) altInstData.obslat = line.split("=")[1].toFloat(); if (line.contains("OBSLONG=")) altInstData.obslon = line.split("=")[1].toFloat(); if (line.contains("PIXSCALE=")) altInstData.pixscale = line.split("=")[1].toFloat(); // if (line.contains("GAIN=")) altInstData.gain = line.split("=")[1].toFloat(); // vectors if (line.contains("OVSCANX1=") || line.contains("OVSCANX2=") || line.contains("OVSCANY1=") || line.contains("OVSCANY2=") || line.contains("CUTX=") || line.contains("CUTY=") || line.contains("SIZEX=") || line.contains("SIZEY=") || line.contains("REFPIXX=") || line.contains("REFPIXY=")) { line = line.replace('=',' ').replace(')',' ').replace(')',""); line = line.simplified(); QStringList values = line.split(" "); QVector vecData; // NOTE: already subtracting -1 to make it conform with C++ indexing // (apart from SIZEX/Y, which is the actual number of pixels per axis and not a coordinate) for (int i=2; i &overscan) { if (overscan.isEmpty()) return; // if the overscan is consistently -1, then the vector must be empty bool flag = true; for (auto &it : overscan) { if (it != -1) { flag = false; break; } } if (flag) overscan.clear(); } // Runs outside the processing thread, but kept here for consistency void Controller::provideAlternativeMask() { // If the NIR detector config is chosen for GROND, then we must create separate masks for the optical data. // Not the other way round, as the masking for the NIR data is handled elsewhere. if (instData->name == "GROND_NIR@MPGESO") { initAltInstrumentData(instrument_dir+"/GROND_OPT@MPGESO.ini"); altMask = new Mask(&altInstData, this); } } THELI-3.1.3/src/processingInternal/processingWeight.cc000066400000000000000000000404531417631501300226650ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "ui_confdockwidget.h" #include "ui_monitor.h" #include #include #include #include void Controller::taskInternalGlobalweight() { QString scienceDir = instructions.split(" ").at(1); QString flatDir = instructions.split(" ").at(2); QString biasDir = instructions.split(" ").at(3); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; Data *biasData = nullptr; // Can also point to a dark Data *flatData = nullptr; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigGlobalweight(); // Link with the correct bias data, if any; dark preferred over bias // I have to select dark / bias again even though it is done in tasks.cc already if (!mainGUI->ui->setupDarkLineEdit->text().isEmpty()) { biasData = getData(DT_DARK, biasDir); } else if (!mainGUI->ui->setupBiasLineEdit->text().isEmpty()) { biasData = getData(DT_BIAS, biasDir); } // Same for the flat if (!mainGUI->ui->setupFlatLineEdit->text().isEmpty()) { flatData = getData(DT_FLAT, flatDir); // Should we check the filter string? } // Check if calib data exist) if (biasData != nullptr && !biasData->hasAllMasterCalibs) { QString part1 = biasData->dirName+"/"+biasData->subDirName+"_?.fits\n"; emit showMessageBox("Controller::MASTER_BIAS_NOT_FOUND_GLOBW", part1, ""); successProcessing = false; return; } if (flatData != nullptr && !flatData->hasAllMasterCalibs) { QString part1 = flatData->dirName+"/"+flatData->subDirName+"_?.fits\n"; emit showMessageBox("Controller::MASTER_FLAT_NOT_FOUND_GLOBW", part1, ""); successProcessing = false; return; } memoryDecideDeletableStatus(scienceData, false); // Need to fill myImageList to get Filter keyword (if the user starts fresh with this task after launching THELI) if (scienceData->myImageList[instData->validChip].isEmpty()) scienceData->populate(scienceData->processingStatus->statusString); // Get the filter name, first exposure in SCIENCE (assuming same filter for all exposures) QString filter = ""; for (auto &it : scienceData->myImageList[instData->validChip]) { if (!it->filter.isEmpty()) { filter = it->filter; break; } else { it->readFILTER(); filter = it->filter; if (!filter.isEmpty()) break; } } QDir globalweightDir(mainDirName+"/GLOBALWEIGHTS/"); if (!globalweightDir.exists()) { globalweightDir.mkpath(mainDirName+"/GLOBALWEIGHTS/"); GLOBALWEIGHTS = new Data(instData, mask, mainDirName, "GLOBALWEIGHTS", &verbosity); connect(GLOBALWEIGHTS, &Data::messageAvailable, this, &Controller::messageAvailableReceived); connect(GLOBALWEIGHTS, &Data::appendOK, this, &Controller::appendOKReceived); connect(GLOBALWEIGHTS, &Data::critical, this, &Controller::criticalReceived); connect(GLOBALWEIGHTS, &Data::warning, this, &Controller::warningReceived); connect(GLOBALWEIGHTS, &Data::showMessageBox, this, &Controller::showMessageBoxReceived); connect(GLOBALWEIGHTS, &Data::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); GLOBALWEIGHTS->progress = &progress; GLOBALWEIGHTS->dataType = "GLOBALWEIGHT"; // GLOBALWEIGHTS->myImageList is empty at this point // TODO: should we not make all the connections here for Data class? } else { // remove the globalweight for the present filter only, in this science directory (and then re-create it) GLOBALWEIGHTS->resetGlobalWeight(filter); } bool sameWeight = cdw->ui->CGWsameweightCheckBox->isChecked(); QString flatMin = cdw->ui->CGWflatminLineEdit->text(); QString flatMax = cdw->ui->CGWflatmaxLineEdit->text(); QString threshMin = cdw->ui->CGWdarkminLineEdit->text(); QString threshMax = cdw->ui->CGWdarkmaxLineEdit->text(); QString defectKernel = cdw->ui->CGWflatsmoothLineEdit->text(); QString defectRowTol = cdw->ui->CGWflatrowtolLineEdit->text(); QString defectColTol = cdw->ui->CGWflatcoltolLineEdit->text(); QString defectClusTol = cdw->ui->CGWflatclustolLineEdit->text(); if (defectKernel.isEmpty() && ( !defectRowTol.isEmpty() || !defectColTol.isEmpty() || !defectClusTol.isEmpty())) { emit messageAvailable("For defect detection, a kernel size must be specified as well!", "error"); emit criticalReceived(); return; } if (!defectKernel.isEmpty() && ( defectRowTol.isEmpty() && defectColTol.isEmpty() && defectClusTol.isEmpty())) { emit messageAvailable("For defect detection, at least one of row, column or cluster tolerance must be specified as well", "error"); emit criticalReceived(); return; } progressStepSize = 100./(float(instData->numChips)); float nimg = 6; // bias, flat, 4 for image detection back, seg, measure, mask) releaseMemory(nimg*instData->storage*maxExternalThreads, 1); // Only need as many threads as chips, max #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); // not sure why i had this in a critical section. libwcs not being threadsafe i think. // should be fixed now that the MyImage::initWCS is always called inside a omp critical section //#pragma omp critical // { if (biasData != nullptr) biasData->loadCombinedImage(chip); // skipped if already in memory if (flatData != nullptr) flatData->loadCombinedImage(chip); // skipped if already in memory // } GLOBALWEIGHTS->initGlobalWeight(chip, flatData, filter, sameWeight, flatMin, flatMax); GLOBALWEIGHTS->thresholdGlobalWeight(chip, biasData, filter, threshMin, threshMax); GLOBALWEIGHTS->detectDefects(chip, flatData, filter, sameWeight, defectKernel, defectRowTol, defectColTol, defectClusTol); GLOBALWEIGHTS->applyMask(chip, filter); GLOBALWEIGHTS->writeGlobalWeights(chip, filter); if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData != nullptr) flatData->unprotectMemory(chip); GLOBALWEIGHTS->myImageList[chip][0]->unprotectMemory(); // List with one entry per chip, only #pragma omp atomic progress += progressStepSize; } checkSuccessProcessing(GLOBALWEIGHTS); satisfyMaxMemorySetting(); if (successProcessing) { emit populateMemoryView(); emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } } void Controller::taskInternalIndividualweight() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigIndividualweight(); memoryDecideDeletableStatus(scienceData, false); QDir globalweightDir(mainDirName+"/GLOBALWEIGHTS/"); if (!globalweightDir.exists()) { emit messageAvailable("The global weight maps must be created before the individual weight maps.", "error"); emit criticalReceived(); successProcessing = false; return; } QDir individualweightDir(mainDirName+"/WEIGHTS/"); individualweightDir.mkdir(mainDirName+"/WEIGHTS/"); QString imageMin = cdw->ui->CIWminaduLineEdit->text(); QString imageMax = cdw->ui->CIWmaxaduLineEdit->text(); QString range = cdw->ui->CIWbloomRangeLineEdit->text(); QString minVal = cdw->ui->CIWbloomMinaduLineEdit->text(); QString aggressiveness = cdw->ui->CIWaggressivenessLineEdit->text(); getNumberOfActiveImages(scienceData); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chipnumChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { if (verbosity >= 0) emit messageAvailable(it->baseName + " : Creating weight map ...", "controller"); it->readImage(false); // no dataBackupL1 required; just use dataCurrent, or read from disk if not yet in memory it->initWeightfromGlobalWeight(GLOBALWEIGHTS->myImageList[chip]); it->thresholdWeight(imageMin, imageMax); it->applyPolygons(chip); it->maskBloomingSpike(instData->type, range, minVal, cdw->ui->CIWmaskbloomingCheckBox->isChecked()); incrementProgress(); it->cosmicsFilter(aggressiveness); it->writeWeight(mainDirName+ "/WEIGHTS/" + it->chipName + ".weight.fits"); it->weightName = it->chipName + ".weight"; incrementProgress(); } } */ QList allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 4; // weight, global weight, margins releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); QString instType = instData->type; #pragma omp parallel for num_threads(maxCPU) firstprivate(instType, mainDirName) for (int k=0; ksuccessProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Creating weight map ...", "image"); it->setupDataInMemorySimple(false); if (!it->successProcessing) { abortProcess = true; continue; } it->initWeightfromGlobalWeight(GLOBALWEIGHTS->myImageList[chip]); // calls a threadsafe version of MyImage::loadData() to avoid parallel reads of the same globalweight map it->thresholdWeight(imageMin, imageMax); it->applyPolygons(); it->maskSaturatedPixels(cdw->ui->CIWsaturationLineEdit->text(), cdw->ui->CIWmasksaturationCheckBox->isChecked()); it->maskBloomingSpike(instType, range, minVal, cdw->ui->CIWmaskbloomingCheckBox->isChecked()); #pragma omp atomic progress += progressHalfStepSize; it->cosmicsFilter(aggressiveness); // Must write weights to drive for swarp it->writeWeight(mainDirName+ "/WEIGHTS/" + it->chipName + ".weight.fits"); it->weightOnDrive = true; it->weightName = it->chipName + ".weight"; it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } GLOBALWEIGHTS->myImageList[chip][0]->unprotectMemory(); // List with one entry per chip, only; could also do: // GLOBALWEIGHTS->unprotectMemory(chip); #pragma omp atomic progress += progressHalfStepSize; } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { emit populateMemoryView(); emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } } void Controller::taskInternalSeparate() { // TODO: // Shouldn't there be a successprocessing step at the beginning of every task? QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); memoryDecideDeletableStatus(scienceData, false); getNumberOfActiveImages(scienceData); QString tolerance = cdw->ui->separateTargetLineEdit->text(); int numGroups = scienceData->identifyClusters(tolerance); if (numGroups == 0) return; if (verbosity >= 0) emit messageAvailable("Moving images ...", "controller"); QStringList newSubDirNames; QString dataSubDirName = scienceData->subDirName; QString statusString = scienceData->processingStatus->statusString; // Delete previously created directories, then add files in another loop for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { QString subDirName = dataSubDirName+"_"+QString::number(it->groupNumber); QString pathNew = mainDirName+"/"+subDirName; QDir groupDir(pathNew); if (groupDir.exists()) groupDir.removeRecursively(); } } #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(dataSubDirName, mainDirName, statusString) for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (!it->successProcessing) continue; QString pathOld = it->path; QString subDirName = dataSubDirName+"_"+QString::number(it->groupNumber); #pragma omp critical { if (!newSubDirNames.contains(subDirName)) newSubDirNames.append(subDirName); } QString pathNew = mainDirName+"/"+subDirName; QDir groupDir(pathNew); groupDir.mkpath(pathNew); it->path = pathNew; it->loadHeader(); // Always write the new image, even if until now it was kept in memory. if (it->imageOnDrive) { moveFile(it->chipName+statusString+".fits", pathOld, it->path); } else { it->writeImage(); it->unprotectMemory(); } #pragma omp atomic progress += progressStepSize; } } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); // Now we have to create new 'Data' instances for each image association emit messageAvailable("Setting up "+QString::number(numGroups+1)+" image associations ...", "controller"); // First, update the line edit // In case several dirs are entered, we must replace the current one, only QString newDirs = newSubDirNames.join(" "); // New dirs forming one blank-separated string QStringList dirList = mainGUI->ui->setupScienceLineEdit->text().split(" "); for (auto &dir : dirList) { if (dir == scienceData->subDirName) { // replace old dir with new dirs dir = newDirs; } } QString allDirs = dirList.join(" "); scienceData->myImageList.clear(); // We run in a processing thread inside the controller. To change anything "outside" we need signals and slots // Trigger an update of the science dir LineEdit. The MainWindow will then trigger the controller to parse the new data dirs. // For that we need to have access to the status (of which the controller knows nothing, only the Data class) statusAtDistribute = scienceData->processingStatus->statusString; emit scienceDataDirUpdated(allDirs); /* if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } */ } THELI-3.1.3/src/processingStatus/000077500000000000000000000000001417631501300165335ustar00rootroot00000000000000THELI-3.1.3/src/processingStatus/processingStatus.cc000066400000000000000000000135621417631501300224310ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "processingStatus.h" #include "../functions.h" #include #include #include #include #include #include ProcessingStatus::ProcessingStatus(QString dirname, QObject *parent) : QObject(parent) { dirName = dirname; dir.setPath(dirname); if (!dir.exists()) { emit messageAvailable("ProcessingStatus::ProcessingStatus(): Directory " + dirName + " does not exist", "error"); emit critical(); statusString = ""; return; } } void ProcessingStatus::writeToDrive() { QFile file(dirName + "/.processingStatus"); QTextStream stream(&file); if( !file.open(QIODevice::WriteOnly)) { emit messageAvailable("ProcessingStatus::write(): Could not write "+dirName + "/.processingStatus "+file.errorString(), "error"); emit critical(); return; } // Write status stream << getStatusString() << "\n"; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } void ProcessingStatus::deleteFromDrive() { QFile file(dirName + "/.processingStatus"); file.remove(); } void ProcessingStatus::readFromDrive() { QFile file(dirName + "/.processingStatus"); if (!file.exists()) { inferStatusFromFilenames(); statusToBoolean(statusString); return; } if(!file.open(QIODevice::ReadOnly)) { emit messageAvailable("ProcessingStatus::read(): Could not open "+dirName + "/.processingStatus "+file.errorString(), "error"); emit critical(); return; } QTextStream stream(&file); statusString = stream.readLine(); statusToBoolean(statusString); file.close(); } // same as above, just returning the string QString ProcessingStatus::whatIsStatusOnDrive() { QFile file(dirName + "/.processingStatus"); if (!file.exists()) { inferStatusFromFilenames(); statusToBoolean(statusString); return ""; } if(!file.open(QIODevice::ReadOnly)) { emit messageAvailable("ProcessingStatus::read(): Could not open "+dirName + "/.processingStatus "+file.errorString(), "error"); emit critical(); return ""; } QTextStream stream(&file); QString tmp = stream.readLine(); file.close(); return tmp; } QString ProcessingStatus::getStatusString() { statusString = ""; if (HDUreformat) statusString.append("P"); if (Processscience) statusString.append("A"); if (Chopnod) statusString.append("M"); if (Background) statusString.append("B"); if (Collapse) statusString.append("C"); if (Starflat) statusString.append("D"); if (Skysub) statusString.append("S"); return statusString; } void ProcessingStatus::statusToBoolean(QString status) { reset(); if (status.contains("P")) HDUreformat = true; if (status.contains("A")) Processscience = true; if (status.contains("M")) Chopnod = true; if (status.contains("B")) Background = true; if (status.contains("C")) Collapse = true; if (status.contains("D")) Starflat = true; if (status.contains("S")) Skysub = true; emit processingStatusChanged(); } void ProcessingStatus::reset() { HDUreformat = false; Processscience = false; Chopnod = false; Background = false; Collapse = false; Starflat = false; Skysub = false; } // If the .processingStatus file is absent when initialising the Data class, then infer the status from the FITS file names void ProcessingStatus::inferStatusFromFilenames() { statusString = ""; QStringList statusList; QStringList fileList = dir.entryList(QStringList() << "*.fits"); for (auto &it : fileList) { QString status = extractStatusFromFilename(it); if (!statusList.contains(status)) statusList.append(status); } if (statusList.length() == 1) statusString = statusList.at(0); else { QString joined = ""; for (auto &it : statusList) { joined.append(it+" "); } joined = joined.simplified(); emit messageAvailable("ProcessingStatus::inferStatus(): Could not infer unambiguous processing status from the FITS file names in " + dirName + ".
The following statuses were identified: "+ joined + "
Cleanup the directory manually to establish a consistent status. Restart required.", "error"); emit critical(); statusString = ""; } } // This does not work if raw data have e.g. the form fsr_1075_03_c2.fits (FourStar). // It would return 'c'. Or in case of Gemini, e.g. S20191231S0495.fits, it would return 'SS' // Hence this function must not be called if no processing has taken place yet. // UPDATE: This function IS called when initializing the Data class. But inside that initialization, we check for RAW data, // and if any are found, the status string and internal data are reset. QString ProcessingStatus::extractStatusFromFilename(QString &filename) { QString id = getLastWord(filename, '_'); QString status = id.remove(".fits"); status.remove(QRegExp("[0123456789]")); return status; } bool ProcessingStatus::doesStatusFileExist() { QFile file(dirName + "/.processingStatus"); if( !file.exists()) return false; else return true; } THELI-3.1.3/src/processingStatus/processingStatus.h000066400000000000000000000033671417631501300222750ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef PROCESSINGSTATUS_H #define PROCESSINGSTATUS_H #include #include #include class ProcessingStatus : public QObject { Q_OBJECT public: explicit ProcessingStatus(QString dirName, QObject *parent = nullptr); bool HDUreformat = false; bool Processscience = false; bool Chopnod = false; bool Background = false; bool Collapse = false; bool Starflat = false; bool Skysub = false; QString statusString = ""; void writeToDrive(); // Used by Data class only void readFromDrive(); // Used by Data class only void reset(); void statusToBoolean(QString status); QString getStatusString(); void inferStatusFromFilenames(); bool doesStatusFileExist(); void deleteFromDrive(); QString whatIsStatusOnDrive(); QString extractStatusFromFilename(QString &filename); private: QDir dir; QString dirName = ""; signals: void processingStatusChanged(); void messageAvailable(QString messageString, QString code); void critical(); public slots: }; #endif // PROCESSINGSTATUS_H THELI-3.1.3/src/qcustomplot.cpp000066400000000000000000047671751417631501300163040ustar00rootroot00000000000000/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2021 Emanuel Eichhammer ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License for more details. ** ** ** ** You should have received a copy of the GNU General Public License ** ** along with this program. If not, see http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 29.03.21 ** ** Version: 2.1.0 ** ****************************************************************************/ #include "qcustomplot.h" /* including file 'src/vector2d.cpp' */ /* modified 2021-03-29T02:30:44, size 7973 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPVector2D //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPVector2D \brief Represents two doubles as a mathematical 2D vector This class acts as a replacement for QVector2D with the advantage of double precision instead of single, and some convenience methods tailored for the QCustomPlot library. */ /* start documentation of inline functions */ /*! \fn void QCPVector2D::setX(double x) Sets the x coordinate of this vector to \a x. \see setY */ /*! \fn void QCPVector2D::setY(double y) Sets the y coordinate of this vector to \a y. \see setX */ /*! \fn double QCPVector2D::length() const Returns the length of this vector. \see lengthSquared */ /*! \fn double QCPVector2D::lengthSquared() const Returns the squared length of this vector. In some situations, e.g. when just trying to find the shortest vector of a group, this is faster than calculating \ref length, because it avoids calculation of a square root. \see length */ /*! \fn double QCPVector2D::angle() const Returns the angle of the vector in radians. The angle is measured between the positive x line and the vector, counter-clockwise in a mathematical coordinate system (y axis upwards positive). In screen/widget coordinates where the y axis is inverted, the angle appears clockwise. */ /*! \fn QPoint QCPVector2D::toPoint() const Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point information. \see toPointF */ /*! \fn QPointF QCPVector2D::toPointF() const Returns a QPointF which has the x and y coordinates of this vector. \see toPoint */ /*! \fn bool QCPVector2D::isNull() const Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y coordinates, i.e. if both are binary equal to 0. */ /*! \fn QCPVector2D QCPVector2D::perpendicular() const Returns a vector perpendicular to this vector, with the same length. */ /*! \fn double QCPVector2D::dot() const Returns the dot/scalar product of this vector with the specified vector \a vec. */ /* end documentation of inline functions */ /*! Creates a QCPVector2D object and initializes the x and y coordinates to 0. */ QCPVector2D::QCPVector2D() : mX(0), mY(0) { } /*! Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified values. */ QCPVector2D::QCPVector2D(double x, double y) : mX(x), mY(y) { } /*! Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of the specified \a point. */ QCPVector2D::QCPVector2D(const QPoint &point) : mX(point.x()), mY(point.y()) { } /*! Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of the specified \a point. */ QCPVector2D::QCPVector2D(const QPointF &point) : mX(point.x()), mY(point.y()) { } /*! Normalizes this vector. After this operation, the length of the vector is equal to 1. If the vector has both entries set to zero, this method does nothing. \see normalized, length, lengthSquared */ void QCPVector2D::normalize() { if (mX == 0.0 && mY == 0.0) return; const double lenInv = 1.0/length(); mX *= lenInv; mY *= lenInv; } /*! Returns a normalized version of this vector. The length of the returned vector is equal to 1. If the vector has both entries set to zero, this method returns the vector unmodified. \see normalize, length, lengthSquared */ QCPVector2D QCPVector2D::normalized() const { if (mX == 0.0 && mY == 0.0) return *this; const double lenInv = 1.0/length(); return QCPVector2D(mX*lenInv, mY*lenInv); } /*! \overload Returns the squared shortest distance of this vector (interpreted as a point) to the finite line segment given by \a start and \a end. \see distanceToStraightLine */ double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const { const QCPVector2D v(end-start); const double vLengthSqr = v.lengthSquared(); if (!qFuzzyIsNull(vLengthSqr)) { const double mu = v.dot(*this-start)/vLengthSqr; if (mu < 0) return (*this-start).lengthSquared(); else if (mu > 1) return (*this-end).lengthSquared(); else return ((start + mu*v)-*this).lengthSquared(); } else return (*this-start).lengthSquared(); } /*! \overload Returns the squared shortest distance of this vector (interpreted as a point) to the finite line segment given by \a line. \see distanceToStraightLine */ double QCPVector2D::distanceSquaredToLine(const QLineF &line) const { return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2())); } /*! Returns the shortest distance of this vector (interpreted as a point) to the infinite straight line given by a \a base point and a \a direction vector. \see distanceSquaredToLine */ double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const { return qAbs((*this-base).dot(direction.perpendicular()))/direction.length(); } /*! Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a factor. */ QCPVector2D &QCPVector2D::operator*=(double factor) { mX *= factor; mY *= factor; return *this; } /*! Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a divisor. */ QCPVector2D &QCPVector2D::operator/=(double divisor) { mX /= divisor; mY /= divisor; return *this; } /*! Adds the given \a vector to this vector component-wise. */ QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector) { mX += vector.mX; mY += vector.mY; return *this; } /*! subtracts the given \a vector from this vector component-wise. */ QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector) { mX -= vector.mX; mY -= vector.mY; return *this; } /* end of 'src/vector2d.cpp' */ /* including file 'src/painter.cpp' */ /* modified 2021-03-29T02:30:44, size 8656 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPainter //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPainter \brief QPainter subclass used internally This QPainter subclass is used to provide some extended functionality e.g. for tweaking position consistency between antialiased and non-antialiased painting. Further it provides workarounds for QPainter quirks. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and restore. So while it is possible to pass a QCPPainter instance to a function that expects a QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because it will call the base class implementations of the functions actually hidden by QCPPainter). */ /*! Creates a new QCPPainter instance and sets default values */ QCPPainter::QCPPainter() : mModes(pmDefault), mIsAntialiasing(false) { // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and // a call to begin() will follow } /*! Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just like the analogous QPainter constructor, begins painting on \a device immediately. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. */ QCPPainter::QCPPainter(QPaintDevice *device) : QPainter(device), mModes(pmDefault), mIsAntialiasing(false) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (isActive()) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif } /*! Sets the pen of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QPen &pen) { QPainter::setPen(pen); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QColor &color) { QPainter::setPen(color); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(Qt::PenStyle penStyle) { QPainter::setPen(penStyle); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to integer coordinates and then passes it to the original drawLine. \note this function hides the non-virtual base class implementation. */ void QCPPainter::drawLine(const QLineF &line) { if (mIsAntialiasing || mModes.testFlag(pmVectorized)) QPainter::drawLine(line); else QPainter::drawLine(line.toLine()); } /*! Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for AA/Non-AA painting). */ void QCPPainter::setAntialiasing(bool enabled) { setRenderHint(QPainter::Antialiasing, enabled); if (mIsAntialiasing != enabled) { mIsAntialiasing = enabled; if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs { if (mIsAntialiasing) translate(0.5, 0.5); else translate(-0.5, -0.5); } } } /*! Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setModes(QCPPainter::PainterModes modes) { mModes = modes; } /*! Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that behaviour. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets the render hint as appropriate. \note this function hides the non-virtual base class implementation. */ bool QCPPainter::begin(QPaintDevice *device) { bool result = QPainter::begin(device); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (result) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif return result; } /*! \overload Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) { if (!enabled && mModes.testFlag(mode)) mModes &= ~mode; else if (enabled && !mModes.testFlag(mode)) mModes |= mode; } /*! Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see restore */ void QCPPainter::save() { mAntialiasingStack.push(mIsAntialiasing); QPainter::save(); } /*! Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see save */ void QCPPainter::restore() { if (!mAntialiasingStack.isEmpty()) mIsAntialiasing = mAntialiasingStack.pop(); else qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; QPainter::restore(); } /*! Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen overrides when the \ref pmNonCosmetic mode is set. */ void QCPPainter::makeNonCosmetic() { if (qFuzzyIsNull(pen().widthF())) { QPen p = pen(); p.setWidth(1); QPainter::setPen(p); } } /* end of 'src/painter.cpp' */ /* including file 'src/paintbuffer.cpp' */ /* modified 2021-03-29T02:30:44, size 18915 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractPaintBuffer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractPaintBuffer \brief The abstract base class for paint buffers, which define the rendering backend This abstract base class defines the basic interface that a paint buffer needs to provide in order to be usable by QCustomPlot. A paint buffer manages both a surface to draw onto, and the matching paint device. The size of the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the painting is complete, \ref donePainting is called, so the paint buffer implementation can do clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the previous frame. The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo. They are used automatically if \ref QCustomPlot::setOpenGl is enabled. */ /* start documentation of pure virtual functions */ /*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0 Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the responsibility to delete the painter after the painting operations are complete is given to the caller of this method. Once you are done using the painter, delete the painter and call \ref donePainting. While a painter generated with this method is active, you must not call \ref setSize, \ref setDevicePixelRatio or \ref clear. This method may return 0, if a painter couldn't be activated on the buffer. This usually indicates a problem with the respective painting backend. */ /*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0 Draws the contents of this buffer with the provided \a painter. This is the method that is used to finally join all paint buffers and draw them onto the screen. */ /*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0 Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the named color \c Qt::transparent. This method must not be called if there is currently a painter (acquired with \ref startPainting) active. */ /*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0 Reallocates the internal buffer with the currently configured size (\ref setSize) and device pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those properties are changed on this paint buffer. \note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method in their constructor, to perform the first allocation (this can not be done by the base class because calling pure virtual methods in base class constructors is not possible). */ /* end documentation of pure virtual functions */ /* start documentation of inline functions */ /*! \fn virtual void QCPAbstractPaintBuffer::donePainting() If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting, call this method as soon as you are done with the painting operations and have deleted the painter. paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The default implementation does nothing. */ /* end documentation of inline functions */ /*! Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio. Subclasses must call their \ref reallocateBuffer implementation in their respective constructors. */ QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) : mSize(size), mDevicePixelRatio(devicePixelRatio), mInvalidated(true) { } QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer() { } /*! Sets the paint buffer size. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained by \ref startPainting are invalidated and must not be used after calling this method. If \a size is already the current buffer size, this method does nothing. */ void QCPAbstractPaintBuffer::setSize(const QSize &size) { if (mSize != size) { mSize = size; reallocateBuffer(); } } /*! Sets the invalidated flag to \a invalidated. This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested, QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also replots them, instead of only the layer on which the replot was called. The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers were added or removed from this buffer, or if they were reordered. It is set to false as soon as all associated \ref QCPLayer instances are drawn onto the buffer. Under normal circumstances, it is not necessary to manually call this method. */ void QCPAbstractPaintBuffer::setInvalidated(bool invalidated) { mInvalidated = invalidated; } /*! Sets the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices. The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained by \ref startPainting are invalidated and must not be used after calling this method. \note This method is only available for Qt versions 5.4 and higher. */ void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio) { if (!qFuzzyCompare(ratio, mDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED mDevicePixelRatio = ratio; reallocateBuffer(); #else qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; mDevicePixelRatio = 1.0; #endif } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPaintBufferPixmap //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPaintBufferPixmap \brief A paint buffer based on QPixmap, using software raster rendering This paint buffer is the default and fall-back paint buffer which uses software rendering and QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false. */ /*! Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if applicable. */ QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) : QCPAbstractPaintBuffer(size, devicePixelRatio) { QCPPaintBufferPixmap::reallocateBuffer(); } QCPPaintBufferPixmap::~QCPPaintBufferPixmap() { } /* inherits documentation from base class */ QCPPainter *QCPPaintBufferPixmap::startPainting() { QCPPainter *result = new QCPPainter(&mBuffer); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) result->setRenderHint(QPainter::HighQualityAntialiasing); #endif return result; } /* inherits documentation from base class */ void QCPPaintBufferPixmap::draw(QCPPainter *painter) const { if (painter && painter->isActive()) painter->drawPixmap(0, 0, mBuffer); else qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed"; } /* inherits documentation from base class */ void QCPPaintBufferPixmap::clear(const QColor &color) { mBuffer.fill(color); } /* inherits documentation from base class */ void QCPPaintBufferPixmap::reallocateBuffer() { setInvalidated(); if (!qFuzzyCompare(1.0, mDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED mBuffer = QPixmap(mSize*mDevicePixelRatio); mBuffer.setDevicePixelRatio(mDevicePixelRatio); #else qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; mDevicePixelRatio = 1.0; mBuffer = QPixmap(mSize); #endif } else { mBuffer = QPixmap(mSize); } } #ifdef QCP_OPENGL_PBUFFER //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPaintBufferGlPbuffer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPaintBufferGlPbuffer \brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0. (See \ref QCPPaintBufferGlFbo used in newer Qt versions.) The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are supported by the system. */ /*! Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a devicePixelRatio, if applicable. The parameter \a multisamples defines how many samples are used per pixel. Higher values thus result in higher quality antialiasing. If the specified \a multisamples value exceeds the capability of the graphics hardware, the highest supported multisampling is used. */ QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) : QCPAbstractPaintBuffer(size, devicePixelRatio), mGlPBuffer(0), mMultisamples(qMax(0, multisamples)) { QCPPaintBufferGlPbuffer::reallocateBuffer(); } QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer() { if (mGlPBuffer) delete mGlPBuffer; } /* inherits documentation from base class */ QCPPainter *QCPPaintBufferGlPbuffer::startPainting() { if (!mGlPBuffer->isValid()) { qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?"; return 0; } QCPPainter *result = new QCPPainter(mGlPBuffer); result->setRenderHint(QPainter::HighQualityAntialiasing); return result; } /* inherits documentation from base class */ void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const { if (!painter || !painter->isActive()) { qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed"; return; } if (!mGlPBuffer->isValid()) { qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?"; return; } painter->drawImage(0, 0, mGlPBuffer->toImage()); } /* inherits documentation from base class */ void QCPPaintBufferGlPbuffer::clear(const QColor &color) { if (mGlPBuffer->isValid()) { mGlPBuffer->makeCurrent(); glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mGlPBuffer->doneCurrent(); } else qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current"; } /* inherits documentation from base class */ void QCPPaintBufferGlPbuffer::reallocateBuffer() { if (mGlPBuffer) delete mGlPBuffer; QGLFormat format; format.setAlpha(true); format.setSamples(mMultisamples); mGlPBuffer = new QGLPixelBuffer(mSize, format); } #endif // QCP_OPENGL_PBUFFER #ifdef QCP_OPENGL_FBO //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPaintBufferGlFbo //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPaintBufferGlFbo \brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.) The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are supported by the system. */ /*! Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio, if applicable. All frame buffer objects shall share one OpenGL context and paint device, which need to be set up externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot instance. */ QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice) : QCPAbstractPaintBuffer(size, devicePixelRatio), mGlContext(glContext), mGlPaintDevice(glPaintDevice), mGlFrameBuffer(0) { QCPPaintBufferGlFbo::reallocateBuffer(); } QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo() { if (mGlFrameBuffer) delete mGlFrameBuffer; } /* inherits documentation from base class */ QCPPainter *QCPPaintBufferGlFbo::startPainting() { QSharedPointer paintDevice = mGlPaintDevice.toStrongRef(); QSharedPointer context = mGlContext.toStrongRef(); if (!paintDevice) { qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist"; return 0; } if (!context) { qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist"; return 0; } if (!mGlFrameBuffer) { qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?"; return 0; } if (QOpenGLContext::currentContext() != context.data()) context->makeCurrent(context->surface()); mGlFrameBuffer->bind(); QCPPainter *result = new QCPPainter(paintDevice.data()); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) result->setRenderHint(QPainter::HighQualityAntialiasing); #endif return result; } /* inherits documentation from base class */ void QCPPaintBufferGlFbo::donePainting() { if (mGlFrameBuffer && mGlFrameBuffer->isBound()) mGlFrameBuffer->release(); else qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound"; } /* inherits documentation from base class */ void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const { if (!painter || !painter->isActive()) { qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed"; return; } if (!mGlFrameBuffer) { qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?"; return; } painter->drawImage(0, 0, mGlFrameBuffer->toImage()); } /* inherits documentation from base class */ void QCPPaintBufferGlFbo::clear(const QColor &color) { QSharedPointer context = mGlContext.toStrongRef(); if (!context) { qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist"; return; } if (!mGlFrameBuffer) { qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?"; return; } if (QOpenGLContext::currentContext() != context.data()) context->makeCurrent(context->surface()); mGlFrameBuffer->bind(); glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mGlFrameBuffer->release(); } /* inherits documentation from base class */ void QCPPaintBufferGlFbo::reallocateBuffer() { // release and delete possibly existing framebuffer: if (mGlFrameBuffer) { if (mGlFrameBuffer->isBound()) mGlFrameBuffer->release(); delete mGlFrameBuffer; mGlFrameBuffer = 0; } QSharedPointer paintDevice = mGlPaintDevice.toStrongRef(); QSharedPointer context = mGlContext.toStrongRef(); if (!paintDevice) { qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist"; return; } if (!context) { qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist"; return; } // create new fbo with appropriate size: context->makeCurrent(context->surface()); QOpenGLFramebufferObjectFormat frameBufferFormat; frameBufferFormat.setSamples(context->format().samples()); frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat); if (paintDevice->size() != mSize*mDevicePixelRatio) paintDevice->setSize(mSize*mDevicePixelRatio); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED paintDevice->setDevicePixelRatio(mDevicePixelRatio); #endif } #endif // QCP_OPENGL_FBO /* end of 'src/paintbuffer.cpp' */ /* including file 'src/layer.cpp' */ /* modified 2021-03-29T02:30:44, size 37615 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayer \brief A layer that may contain objects, to control the rendering order The Layering system of QCustomPlot is the mechanism to control the rendering order of the elements inside the plot. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer, QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers bottom to top and successively draws the layerables of the layers into the paint buffer(s). A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base class from which almost all visible objects derive, like axes, grids, graphs, items, etc. \section qcplayer-defaultlayers Default layers Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and "overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain the default axes and legend, so they will be drawn above plottables. In the middle, there is the "main" layer. It is initially empty and set as the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of course, the layer affiliation of the individual objects can be changed as required (\ref QCPLayerable::setLayer). \section qcplayer-ordering Controlling the rendering order via layers Controlling the ordering of layerables in the plot is easy: Create a new layer in the position you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will be placed on the new layer automatically, due to the current layer setting. Alternatively you could have also ignored the current layer setting and just moved the objects with \ref QCPLayerable::setLayer to the desired layer after creating them. It is also possible to move whole layers. For example, If you want the grid to be shown in front of all plottables/items on the "main" layer, just move it above "main" with QCustomPlot::moveLayer. The rendering order within one layer is simply by order of creation or insertion. The item created last (or added last to the layer), is drawn on top of all other objects on that layer. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below the deleted layer, see QCustomPlot::removeLayer. \section qcplayer-buffering Replotting only a specific layer If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific layer by calling \ref replot. In certain situations this can provide better replot performance, compared with a full replot of all layers. Upon creation of a new layer, the layer mode is initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref QCustomPlot instance is the "overlay" layer, containing the selection rect. */ /* start documentation of inline functions */ /*! \fn QList QCPLayer::children() const Returns a list of all layerables on this layer. The order corresponds to the rendering order: layerables with higher indices are drawn above layerables with lower indices. */ /*! \fn int QCPLayer::index() const Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be accessed via \ref QCustomPlot::layer. Layers with higher indices will be drawn above layers with lower indices. */ /* end documentation of inline functions */ /*! Creates a new QCPLayer instance. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. This check is only performed by \ref QCustomPlot::addLayer. */ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : QObject(parentPlot), mParentPlot(parentPlot), mName(layerName), mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function mVisible(true), mMode(lmLogical) { // Note: no need to make sure layerName is unique, because layer // management is done with QCustomPlot functions. } QCPLayer::~QCPLayer() { // If child layerables are still on this layer, detach them, so they don't try to reach back to this // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) while (!mChildren.isEmpty()) mChildren.last()->setLayer(nullptr); // removes itself from mChildren via removeChild() if (mParentPlot->currentLayer() == this) qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or nullptr beforehand."; } /*! Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this layer will be invisible. This function doesn't change the visibility property of the layerables (\ref QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the visibility of the parent layer into account. */ void QCPLayer::setVisible(bool visible) { mVisible = visible; } /*! Sets the rendering mode of this layer. If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by the parent QCustomPlot instance. This means it may be replotted individually by calling \ref QCPLayer::replot, without needing to replot all other layers. Layers which are set to \ref lmLogical (the default) are used only to define the rendering order and can't be replotted individually. Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the layers below, above and for the layer itself. This increases the memory consumption and (slightly) decreases the repainting speed because multiple paint buffers need to be joined. So you should carefully choose which layers benefit from having their own paint buffer. A typical example would be a layer which contains certain layerables (e.g. items) that need to be changed and thus replotted regularly, while all other layerables on other layers stay static. By default, only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection rect. \see replot */ void QCPLayer::setMode(QCPLayer::LayerMode mode) { if (mMode != mode) { mMode = mode; if (QSharedPointer pb = mPaintBuffer.toStrongRef()) pb->setInvalidated(); } } /*! \internal Draws the contents of this layer with the provided \a painter. \see replot, drawToPaintBuffer */ void QCPLayer::draw(QCPPainter *painter) { foreach (QCPLayerable *child, mChildren) { if (child->realVisibility()) { painter->save(); painter->setClipRect(child->clipRect().translated(0, -1)); child->applyDefaultAntialiasingHint(painter); child->draw(painter); painter->restore(); } } } /*! \internal Draws the contents of this layer into the paint buffer which is associated with this layer. The association is established by the parent QCustomPlot, which manages all paint buffers (see \ref QCustomPlot::setupPaintBuffers). \see draw */ void QCPLayer::drawToPaintBuffer() { if (QSharedPointer pb = mPaintBuffer.toStrongRef()) { if (QCPPainter *painter = pb->startPainting()) { if (painter->isActive()) draw(painter); else qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter"; delete painter; pb->donePainting(); } else qDebug() << Q_FUNC_INFO << "paint buffer returned nullptr painter"; } else qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer"; } /*! If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only the layerables on this specific layer, without the need to replot all other layers (as a call to \ref QCustomPlot::replot would do). QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering or any layerable-layer-association has changed since the last full replot and any other paint buffers were thus invalidated. If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on the parent QCustomPlot instance. \see draw */ void QCPLayer::replot() { if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers()) { if (QSharedPointer pb = mPaintBuffer.toStrongRef()) { pb->clear(Qt::transparent); drawToPaintBuffer(); pb->setInvalidated(false); // since layer is lmBuffered, we know only this layer is on buffer and we can reset invalidated flag mParentPlot->update(); } else qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer"; } else mParentPlot->replot(); } /*! \internal Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will be prepended to the list, i.e. be drawn beneath the other layerables already in the list. This function does not change the \a mLayer member of \a layerable to this layer. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see removeChild */ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) { if (!mChildren.contains(layerable)) { if (prepend) mChildren.prepend(layerable); else mChildren.append(layerable); if (QSharedPointer pb = mPaintBuffer.toStrongRef()) pb->setInvalidated(); } else qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); } /*! \internal Removes the \a layerable from the list of this layer. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see addChild */ void QCPLayer::removeChild(QCPLayerable *layerable) { if (mChildren.removeOne(layerable)) { if (QSharedPointer pb = mPaintBuffer.toStrongRef()) pb->setInvalidated(); } else qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayerable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayerable \brief Base class for all drawable objects This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid etc. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking the layers accordingly. For details about the layering mechanism, see the QCPLayer documentation. */ /* start documentation of inline functions */ /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const Returns the parent layerable of this layerable. The parent layerable is used to provide visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables only get drawn if their parent layerables are visible, too. Note that a parent layerable is not necessarily also the QObject parent for memory management. Further, a layerable doesn't always have a parent layerable, so this function may return \c nullptr. A parent layerable is set implicitly when placed inside layout elements and doesn't need to be set manually by the user. */ /* end documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 \internal This function applies the default antialiasing setting to the specified \a painter, using the function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing setting may be specified individually, this function should set the antialiasing state of the most prominent entity. In this case however, the \ref draw function usually calls the specialized versions of this function before drawing each entity, effectively overriding the setting of the default antialiasing hint. First example: QCPGraph has multiple entities that have an antialiasing setting: The graph line, fills and scatters. Those can be configured via QCPGraph::setAntialiased, QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw calls the respective specialized applyAntialiasingHint function. Second example: QCPItemLine consists only of a line so there is only one antialiasing setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the respective layerable subclass.) Consequently it only has the normal QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to care about setting any antialiasing states, because the default antialiasing hint is already set on the painter when the \ref draw function is called, and that's the state it wants to draw the line with. */ /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 \internal This function draws the layerable with the specified \a painter. It is only called by QCustomPlot, if the layerable is visible (\ref setVisible). Before this function is called, the painter's antialiasing state is set via \ref applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was set to \ref clipRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to a different layer. \see setLayer */ /* end documentation of signals */ /*! Creates a new QCPLayerable instance. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the derived classes. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a targetLayer is an empty string, it places itself on the current layer of the plot (see \ref QCustomPlot::setCurrentLayer). It is possible to provide \c nullptr as \a plot. In that case, you should assign a parent plot at a later time with \ref initializeParentPlot. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents are mainly used to control visibility in a hierarchy of layerables. This means a layerable is only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a plot does. It is not uncommon to set the QObject-parent to something else in the constructors of QCPLayerable subclasses, to guarantee a working destruction hierarchy. */ QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : QObject(plot), mVisible(true), mParentPlot(plot), mParentLayerable(parentLayerable), mLayer(nullptr), mAntialiased(true) { if (mParentPlot) { if (targetLayer.isEmpty()) setLayer(mParentPlot->currentLayer()); else if (!setLayer(targetLayer)) qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; } } QCPLayerable::~QCPLayerable() { if (mLayer) { mLayer->removeChild(this); mLayer = nullptr; } } /*! Sets the visibility of this layerable object. If an object is not visible, it will not be drawn on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not possible. */ void QCPLayerable::setVisible(bool on) { mVisible = on; } /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a layer. If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or interact/receive events). Returns true if the layer of this layerable was successfully changed to \a layer. */ bool QCPLayerable::setLayer(QCPLayer *layer) { return moveToLayer(layer, false); } /*! \overload Sets the layer of this layerable object by name Returns true on success, i.e. if \a layerName is a valid layer name. */ bool QCPLayerable::setLayer(const QString &layerName) { if (!mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (QCPLayer *layer = mParentPlot->layer(layerName)) { return setLayer(layer); } else { qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; return false; } } /*! Sets whether this object will be drawn antialiased or not. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased(bool enabled) { mAntialiased = enabled; } /*! Returns whether this layerable is visible, taking the visibility of the layerable parent and the visibility of this layerable's layer into account. This is the method that is consulted to decide whether a layerable shall be drawn or not. If this layerable has a direct layerable parent (usually set via hierarchies implemented in subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this layerable has its visibility set to true and the parent layerable's \ref realVisibility returns true. */ bool QCPLayerable::realVisibility() const { return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); } /*! This function is used to decide whether a click hits a layerable object or not. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the shortest pixel distance of this point to the object. If the object is either invisible or the distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the object is not selectable, -1.0 is returned, too. If the object is represented not by single lines but by an area like a \ref QCPItemText or the bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In these cases this function thus returns a constant value greater zero but still below the parent plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99). Providing a constant value for area objects allows selecting line objects even when they are obscured by such area objects, by clicking close to the lines (i.e. closer than 0.99*selectionTolerance). The actual setting of the selection state is not done by this function. This is handled by the parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified via the \ref selectEvent/\ref deselectEvent methods. \a details is an optional output parameter. Every layerable subclass may place any information in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot decides on the basis of this selectTest call, that the object was successfully selected. The subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be placed in \a details. So in the subsequent \ref selectEvent, the decision which part was selected doesn't have to be done a second time for a single selection operation. In the case of 1D Plottables (\ref QCPAbstractPlottable1D, like \ref QCPGraph or \ref QCPBars) \a details will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. You may pass \c nullptr as \a details to indicate that you are not interested in those selection details. \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions, QCPAbstractPlottable1D::selectTestRect */ double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(pos) Q_UNUSED(onlySelectable) Q_UNUSED(details) return -1.0; } /*! \internal Sets the parent plot of this layerable. Use this function once to set the parent plot if you have passed \c nullptr in the constructor. It can not be used to move a layerable from one QCustomPlot to another one. Note that, unlike when passing a non \c nullptr parent plot in the constructor, this function does not make \a parentPlot the QObject-parent of this layerable. If you want this, call QObject::setParent(\a parentPlot) in addition to this function. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to make the layerable appear on the QCustomPlot. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized so they can react accordingly (e.g. also initialize the parent plot of child layerables, like QCPLayout does). */ void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) { if (mParentPlot) { qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; return; } if (!parentPlot) qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; mParentPlot = parentPlot; parentPlotInitialized(mParentPlot); } /*! \internal Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable. The parent layerable has influence on the return value of the \ref realVisibility method. Only layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be drawn. \see realVisibility */ void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) { mParentLayerable = parentLayerable; } /*! \internal Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is false, the object will be appended. Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) { if (layer && !mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (layer && layer->parentPlot() != mParentPlot) { qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; return false; } QCPLayer *oldLayer = mLayer; if (mLayer) mLayer->removeChild(this); mLayer = layer; if (mLayer) mLayer->addChild(this, prepend); if (mLayer != oldLayer) emit layerChanged(mLayer); return true; } /*! \internal Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is controlled via \a overrideElement. */ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const { if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(false); else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(true); else painter->setAntialiasing(localAntialiased); } /*! \internal This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting of a parent plot. This is the case when \c nullptr was passed as parent plot in the constructor, and the parent plot is set at a later time. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To propagate the parent plot to all the children of the hierarchy, the top level element then uses this function to pass the parent plot on to its child elements. The default implementation does nothing. \see initializeParentPlot */ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) { Q_UNUSED(parentPlot) } /*! \internal Returns the selection category this layerable shall belong to. The selection category is used in conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and which aren't. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref QCP::iSelectOther. This is what the default implementation returns. \see QCustomPlot::setInteractions */ QCP::Interaction QCPLayerable::selectionCategory() const { return QCP::iSelectOther; } /*! \internal Returns the clipping rectangle of this layerable object. By default, this is the viewport of the parent QCustomPlot. Specific subclasses may reimplement this function to provide different clipping rects. The returned clipping rect is set on the painter before the draw function of the respective object is called. */ QRect QCPLayerable::clipRect() const { if (mParentPlot) return mParentPlot->viewport(); else return {}; } /*! \internal This event is called when the layerable shall be selected, as a consequence of a click by the user. Subclasses should react to it by setting their selection state appropriately. The default implementation does nothing. \a event is the mouse event that caused the selection. \a additive indicates, whether the user was holding the multi-select-modifier while performing the selection (see \ref QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled (i.e. become selected when unselected and unselected when selected). Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). The \a details data you output from \ref selectTest is fed back via \a details here. You may use it to transport any kind of information from the selectTest to the possibly subsequent selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need to do the calculation again to find out which part was actually clicked. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must set the value either to true or false, depending on whether the selection state of this layerable was actually changed. For layerables that only are selectable as a whole and not in parts, this is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the layerable was previously unselected and now is switched to the selected state. \see selectTest, deselectEvent */ void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(additive) Q_UNUSED(details) Q_UNUSED(selectionStateChanged) } /*! \internal This event is called when the layerable shall be deselected, either as consequence of a user interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by unsetting their selection appropriately. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must return true or false when the selection state of this layerable has changed or not changed, respectively. \see selectTest, selectEvent */ void QCPLayerable::deselectEvent(bool *selectionStateChanged) { Q_UNUSED(selectionStateChanged) } /*! This event gets called when the user presses a mouse button while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref selectTest. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c event->pos(). The parameter \a details contains layerable-specific details about the hit, which were generated in the previous call to \ref selectTest. For example, One-dimensional plottables like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes). QCustomPlot uses an event propagation system that works the same as Qt's system. If your layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in its reimplementation, the event will be propagated to the next layerable in the stacking order. Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends with the release). The default implementation does nothing except explicitly ignoring the event with \c event->ignore(). \see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent */ void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details) { Q_UNUSED(details) event->ignore(); } /*! This event gets called when the user moves the mouse while holding a mouse button, after this layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c event->pos(). The parameter \a startPos indicates the position where the initial \ref mousePressEvent occurred, that started the mouse interaction. The default implementation does nothing. \see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent */ void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(startPos) event->ignore(); } /*! This event gets called when the user releases the mouse button, after this layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c event->pos(). The parameter \a startPos indicates the position where the initial \ref mousePressEvent occurred, that started the mouse interaction. The default implementation does nothing. \see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent */ void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(startPos) event->ignore(); } /*! This event gets called when the user presses the mouse button a second time in a double-click, while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref selectTest. The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the case of a double-click, the event succession is pressEvent – releaseEvent – doubleClickEvent – releaseEvent. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c event->pos(). The parameter \a details contains layerable-specific details about the hit, which were generated in the previous call to \ref selectTest. For example, One-dimensional plottables like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes). Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent, it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends with the release). The default implementation does nothing except explicitly ignoring the event with \c event->ignore(). \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent */ void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) { Q_UNUSED(details) event->ignore(); } /*! This event gets called when the user turns the mouse scroll wheel while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref selectTest. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c event->pos(). The \c event->angleDelta() indicates how far the mouse wheel was turned, which is usually +/- 120 for single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may accumulate to one event, making the delta larger. On the other hand, if the wheel has very smooth steps or none at all, the delta may be smaller. The default implementation does nothing. \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent */ void QCPLayerable::wheelEvent(QWheelEvent *event) { event->ignore(); } /* end of 'src/layer.cpp' */ /* including file 'src/axis/range.cpp' */ /* modified 2021-03-29T02:30:44, size 12221 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPRange //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPRange \brief Represents the range an axis is encompassing. contains a \a lower and \a upper double value and provides convenience input, output and modification functions. \see QCPAxis::setRange */ /* start of documentation of inline functions */ /*! \fn double QCPRange::size() const Returns the size of the range, i.e. \a upper-\a lower */ /*! \fn double QCPRange::center() const Returns the center of the range, i.e. (\a upper+\a lower)*0.5 */ /*! \fn void QCPRange::normalize() Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are swapped. */ /*! \fn bool QCPRange::contains(double value) const Returns true when \a value lies within or exactly on the borders of the range. */ /*! \fn QCPRange &QCPRange::operator+=(const double& value) Adds \a value to both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator-=(const double& value) Subtracts \a value from both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator*=(const double& value) Multiplies both boundaries of the range by \a value. */ /*! \fn QCPRange &QCPRange::operator/=(const double& value) Divides both boundaries of the range by \a value. */ /* end of documentation of inline functions */ /*! Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller intervals would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a minimum magnitude of roughly 1e-308. \warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to prevent axis ranges from obtaining underflowing ranges. \see validRange, maxRange */ const double QCPRange::minRange = 1e-280; /*! Maximum values (negative and positive) the range will accept in range-changing functions. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a maximum magnitude of roughly 1e308. \warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to prevent axis ranges from obtaining overflowing ranges. \see validRange, minRange */ const double QCPRange::maxRange = 1e250; /*! Constructs a range with \a lower and \a upper set to zero. */ QCPRange::QCPRange() : lower(0), upper(0) { } /*! \overload Constructs a range with the specified \a lower and \a upper values. The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically smaller than \a upper, they will be swapped. */ QCPRange::QCPRange(double lower, double upper) : lower(lower), upper(upper) { normalize(); } /*! \overload Expands this range such that \a otherRange is contained in the new range. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). If this range contains NaN as lower or upper bound, it will be replaced by the respective bound of \a otherRange. If \a otherRange is already inside the current range, this function does nothing. \see expanded */ void QCPRange::expand(const QCPRange &otherRange) { if (lower > otherRange.lower || qIsNaN(lower)) lower = otherRange.lower; if (upper < otherRange.upper || qIsNaN(upper)) upper = otherRange.upper; } /*! \overload Expands this range such that \a includeCoord is contained in the new range. It is assumed that this range is normalized (see \ref normalize). If this range contains NaN as lower or upper bound, the respective bound will be set to \a includeCoord. If \a includeCoord is already inside the current range, this function does nothing. \see expand */ void QCPRange::expand(double includeCoord) { if (lower > includeCoord || qIsNaN(lower)) lower = includeCoord; if (upper < includeCoord || qIsNaN(upper)) upper = includeCoord; } /*! \overload Returns an expanded range that contains this and \a otherRange. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). If this range contains NaN as lower or upper bound, the returned range's bound will be taken from \a otherRange. \see expand */ QCPRange QCPRange::expanded(const QCPRange &otherRange) const { QCPRange result = *this; result.expand(otherRange); return result; } /*! \overload Returns an expanded range that includes the specified \a includeCoord. It is assumed that this range is normalized (see \ref normalize). If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a includeCoord. \see expand */ QCPRange QCPRange::expanded(double includeCoord) const { QCPRange result = *this; result.expand(includeCoord); return result; } /*! Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a upperBound. If possible, the size of the current range is preserved in the process. If the range shall only be bounded at the lower side, you can set \a upperBound to \ref QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref QCPRange::maxRange. */ QCPRange QCPRange::bounded(double lowerBound, double upperBound) const { if (lowerBound > upperBound) qSwap(lowerBound, upperBound); QCPRange result(lower, upper); if (result.lower < lowerBound) { result.lower = lowerBound; result.upper = lowerBound + size(); if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound)) result.upper = upperBound; } else if (result.upper > upperBound) { result.upper = upperBound; result.lower = upperBound - size(); if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound)) result.lower = lowerBound; } return result; } /*! Returns a sanitized version of the range. Sanitized means for logarithmic scales, that the range won't span the positive and negative sign domain, i.e. contain zero. Further \a lower will always be numerically smaller (or equal) to \a upper. If the original range does span positive and negative sign domains or contains zero, the returned range will try to approximate the original range as good as possible. If the positive interval of the original range is wider than the negative interval, the returned range will only contain the positive interval, with lower bound set to \a rangeFac or \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval is wider than the positive interval, this time by changing the \a upper bound. */ QCPRange QCPRange::sanitizedForLogScale() const { double rangeFac = 1e-3; QCPRange sanitizedRange(lower, upper); sanitizedRange.normalize(); // can't have range spanning negative and positive values in log plot, so change range to fix it //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) { // case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) { // case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) { // find out whether negative or positive interval is wider to decide which sign domain will be chosen if (-sanitizedRange.lower > sanitizedRange.upper) { // negative is wider, do same as in case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else { // positive is wider, do same as in case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } } // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper -maxRange && upper < maxRange && qAbs(lower-upper) > minRange && qAbs(lower-upper) < maxRange && !(lower > 0 && qIsInf(upper/lower)) && !(upper < 0 && qIsInf(lower/upper))); } /*! \overload Checks, whether the specified range is within valid bounds, which are defined as QCPRange::maxRange and QCPRange::minRange. A valid range means: \li range bounds within -maxRange and maxRange \li range size above minRange \li range size below maxRange */ bool QCPRange::validRange(const QCPRange &range) { return (range.lower > -maxRange && range.upper < maxRange && qAbs(range.lower-range.upper) > minRange && qAbs(range.lower-range.upper) < maxRange && !(range.lower > 0 && qIsInf(range.upper/range.lower)) && !(range.upper < 0 && qIsInf(range.lower/range.upper))); } /* end of 'src/axis/range.cpp' */ /* including file 'src/selection.cpp' */ /* modified 2021-03-29T02:30:44, size 21837 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPDataRange //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPDataRange \brief Describes a data range given by begin and end index QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index of a contiguous set of data points. The \a end index corresponds to the data point just after the last data point of the data range, like in standard iterators. Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref QCPDataSelection is thus used. Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them, e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding \ref QCPDataSelection. %QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and QCPDataRange. \note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval in floating point plot coordinates, e.g. the current axis range. */ /* start documentation of inline functions */ /*! \fn int QCPDataRange::size() const Returns the number of data points described by this data range. This is equal to the end index minus the begin index. \see length */ /*! \fn int QCPDataRange::length() const Returns the number of data points described by this data range. Equivalent to \ref size. */ /*! \fn void QCPDataRange::setBegin(int begin) Sets the begin of this data range. The \a begin index points to the first data point that is part of the data range. No checks or corrections are made to ensure the resulting range is valid (\ref isValid). \see setEnd */ /*! \fn void QCPDataRange::setEnd(int end) Sets the end of this data range. The \a end index points to the data point just after the last data point that is part of the data range. No checks or corrections are made to ensure the resulting range is valid (\ref isValid). \see setBegin */ /*! \fn bool QCPDataRange::isValid() const Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and an end index greater or equal to the begin index. \note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods (unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary invalid begin/end values while manipulating the range. An invalid range is not necessarily empty (\ref isEmpty), since its \ref length can be negative and thus non-zero. */ /*! \fn bool QCPDataRange::isEmpty() const Returns whether this range is empty, i.e. whether its begin index equals its end index. \see size, length */ /*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end indices, respectively. */ /* end documentation of inline functions */ /*! Creates an empty QCPDataRange, with begin and end set to 0. */ QCPDataRange::QCPDataRange() : mBegin(0), mEnd(0) { } /*! Creates a QCPDataRange, initialized with the specified \a begin and \a end. No checks or corrections are made to ensure the resulting range is valid (\ref isValid). */ QCPDataRange::QCPDataRange(int begin, int end) : mBegin(begin), mEnd(end) { } /*! Returns a data range that matches this data range, except that parts exceeding \a other are excluded. This method is very similar to \ref intersection, with one distinction: If this range and the \a other range share no intersection, the returned data range will be empty with begin and end set to the respective boundary side of \a other, at which this range is residing. (\ref intersection would just return a range with begin and end set to 0.) */ QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const { QCPDataRange result(intersection(other)); if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value { if (mEnd <= other.mBegin) result = QCPDataRange(other.mBegin, other.mBegin); else result = QCPDataRange(other.mEnd, other.mEnd); } return result; } /*! Returns a data range that contains both this data range as well as \a other. */ QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const { return {qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd)}; } /*! Returns the data range which is contained in both this data range and \a other. This method is very similar to \ref bounded, with one distinction: If this range and the \a other range share no intersection, the returned data range will be empty with begin and end set to 0. (\ref bounded would return a range with begin and end set to one of the boundaries of \a other, depending on which side this range is on.) \see QCPDataSelection::intersection */ QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const { QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd)); if (result.isValid()) return result; else return {}; } /*! Returns whether this data range and \a other share common data points. \see intersection, contains */ bool QCPDataRange::intersects(const QCPDataRange &other) const { return !( (mBegin > other.mBegin && mBegin >= other.mEnd) || (mEnd <= other.mBegin && mEnd < other.mEnd) ); } /*! Returns whether all data points of \a other are also contained inside this data range. \see intersects */ bool QCPDataRange::contains(const QCPDataRange &other) const { return mBegin <= other.mBegin && mEnd >= other.mEnd; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPDataSelection //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPDataSelection \brief Describes a data set by holding multiple QCPDataRange instances QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly disjoint) set of data selection. The data selection can be modified with addition and subtraction operators which take QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and \ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc. The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange instances. QCPDataSelection automatically simplifies when using the addition/subtraction operators. The only case when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data ranges will be added to the selection successively and the overhead for simplifying after each iteration shall be avoided. In this case, you should make sure to call \ref simplify after completing the operation. Use \ref enforceType to bring the data selection into a state complying with the constraints for selections defined in \ref QCP::SelectionType. %QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and QCPDataRange. \section qcpdataselection-iterating Iterating over a data selection As an example, the following code snippet calculates the average value of a graph's data \ref QCPAbstractPlottable::selection "selection": \snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1 */ /* start documentation of inline functions */ /*! \fn int QCPDataSelection::dataRangeCount() const Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref dataRange via their index. \see dataRange, dataPointCount */ /*! \fn QList QCPDataSelection::dataRanges() const Returns all data ranges that make up the data selection. If the data selection is simplified (the usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point index. \see dataRange */ /*! \fn bool QCPDataSelection::isEmpty() const Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection instance. \see dataRangeCount */ /* end documentation of inline functions */ /*! Creates an empty QCPDataSelection. */ QCPDataSelection::QCPDataSelection() { } /*! Creates a QCPDataSelection containing the provided \a range. */ QCPDataSelection::QCPDataSelection(const QCPDataRange &range) { mDataRanges.append(range); } /*! Returns true if this selection is identical (contains the same data ranges with the same begin and end indices) to \a other. Note that both data selections must be in simplified state (the usual state of the selection, see \ref simplify) for this operator to return correct results. */ bool QCPDataSelection::operator==(const QCPDataSelection &other) const { if (mDataRanges.size() != other.mDataRanges.size()) return false; for (int i=0; i= other.end()) break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored { if (thisBegin >= other.begin()) // range leading segment is encompassed { if (thisEnd <= other.end()) // range fully encompassed, remove completely { mDataRanges.removeAt(i); continue; } else // only leading segment is encompassed, trim accordingly mDataRanges[i].setBegin(other.end()); } else // leading segment is not encompassed { if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly { mDataRanges[i].setEnd(other.begin()); } else // other lies inside this range, so split range { mDataRanges[i].setEnd(other.begin()); mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd)); break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here } } } ++i; } return *this; } /*! Returns the total number of data points contained in all data ranges that make up this data selection. */ int QCPDataSelection::dataPointCount() const { int result = 0; foreach (QCPDataRange dataRange, mDataRanges) result += dataRange.length(); return result; } /*! Returns the data range with the specified \a index. If the data selection is simplified (the usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point index. \see dataRangeCount */ QCPDataRange QCPDataSelection::dataRange(int index) const { if (index >= 0 && index < mDataRanges.size()) { return mDataRanges.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of range:" << index; return {}; } } /*! Returns a \ref QCPDataRange which spans the entire data selection, including possible intermediate segments which are not part of the original data selection. */ QCPDataRange QCPDataSelection::span() const { if (isEmpty()) return {}; else return {mDataRanges.first().begin(), mDataRanges.last().end()}; } /*! Adds the given \a dataRange to this data selection. This is equivalent to the += operator but allows disabling immediate simplification by setting \a simplify to false. This can improve performance if adding a very large amount of data ranges successively. In this case, make sure to call \ref simplify manually, after the operation. */ void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify) { mDataRanges.append(dataRange); if (simplify) this->simplify(); } /*! Removes all data ranges. The data selection then contains no data points. \ref isEmpty */ void QCPDataSelection::clear() { mDataRanges.clear(); } /*! Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent or overlapping ranges. This can reduce the number of individual data ranges in the selection, and prevents possible double-counting when iterating over the data points held by the data ranges. This method is automatically called when using the addition/subtraction operators. The only case when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a simplify explicitly set to false. */ void QCPDataSelection::simplify() { // remove any empty ranges: for (int i=mDataRanges.size()-1; i>=0; --i) { if (mDataRanges.at(i).isEmpty()) mDataRanges.removeAt(i); } if (mDataRanges.isEmpty()) return; // sort ranges by starting value, ascending: std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin); // join overlapping/contiguous ranges: int i = 1; while (i < mDataRanges.size()) { if (mDataRanges.at(i-1).end() >= mDataRanges.at(i).begin()) // range i overlaps/joins with i-1, so expand range i-1 appropriately and remove range i from list { mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end())); mDataRanges.removeAt(i); } else ++i; } } /*! Makes sure this data selection conforms to the specified \a type selection type. Before the type is enforced, \ref simplify is called. Depending on \a type, enforcing means adding new data points that were previously not part of the selection, or removing data points from the selection. If the current selection already conforms to \a type, the data selection is not changed. \see QCP::SelectionType */ void QCPDataSelection::enforceType(QCP::SelectionType type) { simplify(); switch (type) { case QCP::stNone: { mDataRanges.clear(); break; } case QCP::stWhole: { // whole selection isn't defined by data range, so don't change anything (is handled in plottable methods) break; } case QCP::stSingleData: { // reduce all data ranges to the single first data point: if (!mDataRanges.isEmpty()) { if (mDataRanges.size() > 1) mDataRanges = QList() << mDataRanges.first(); if (mDataRanges.first().length() > 1) mDataRanges.first().setEnd(mDataRanges.first().begin()+1); } break; } case QCP::stDataRange: { if (!isEmpty()) mDataRanges = QList() << span(); break; } case QCP::stMultipleDataRanges: { // this is the selection type that allows all concievable combinations of ranges, so do nothing break; } } } /*! Returns true if the data selection \a other is contained entirely in this data selection, i.e. all data point indices that are in \a other are also in this data selection. \see QCPDataRange::contains */ bool QCPDataSelection::contains(const QCPDataSelection &other) const { if (other.isEmpty()) return false; int otherIndex = 0; int thisIndex = 0; while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size()) { if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex))) ++otherIndex; else ++thisIndex; } return thisIndex < mDataRanges.size(); // if thisIndex ran all the way to the end to find a containing range for the current otherIndex, other is not contained in this } /*! Returns a data selection containing the points which are both in this data selection and in the data range \a other. A common use case is to limit an unknown data selection to the valid range of a data container, using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned data selection without exceeding the data container's bounds. */ QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const { QCPDataSelection result; foreach (QCPDataRange dataRange, mDataRanges) result.addDataRange(dataRange.intersection(other), false); result.simplify(); return result; } /*! Returns a data selection containing the points which are both in this data selection and in the data selection \a other. */ QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const { QCPDataSelection result; for (int i=0; iorientation() == Qt::Horizontal) return {axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width())}; else return {axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top())}; } else { qDebug() << Q_FUNC_INFO << "called with axis zero"; return {}; } } /*! Sets the pen that will be used to draw the selection rect outline. \see setBrush */ void QCPSelectionRect::setPen(const QPen &pen) { mPen = pen; } /*! Sets the brush that will be used to fill the selection rect. By default the selection rect is not filled, i.e. \a brush is Qt::NoBrush. \see setPen */ void QCPSelectionRect::setBrush(const QBrush &brush) { mBrush = brush; } /*! If there is currently a selection interaction going on (\ref isActive), the interaction is canceled. The selection rect will emit the \ref canceled signal. */ void QCPSelectionRect::cancel() { if (mActive) { mActive = false; emit canceled(mRect, nullptr); } } /*! \internal This method is called by QCustomPlot to indicate that a selection rect interaction was initiated. The default implementation sets the selection rect to active, initializes the selection rect geometry and emits the \ref started signal. */ void QCPSelectionRect::startSelection(QMouseEvent *event) { mActive = true; mRect = QRect(event->pos(), event->pos()); emit started(event); } /*! \internal This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs to update its geometry. The default implementation updates the rect and emits the \ref changed signal. */ void QCPSelectionRect::moveSelection(QMouseEvent *event) { mRect.setBottomRight(event->pos()); emit changed(mRect, event); layer()->replot(); } /*! \internal This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has finished by the user releasing the mouse button. The default implementation deactivates the selection rect and emits the \ref accepted signal. */ void QCPSelectionRect::endSelection(QMouseEvent *event) { mRect.setBottomRight(event->pos()); mActive = false; emit accepted(mRect, event); } /*! \internal This method is called by QCustomPlot when a key has been pressed by the user while the selection rect interaction is active. The default implementation allows to \ref cancel the interaction by hitting the escape key. */ void QCPSelectionRect::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape && mActive) { mActive = false; emit canceled(mRect, event); } } /* inherits documentation from base class */ void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeOther); } /*! \internal If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect. \seebaseclassmethod */ void QCPSelectionRect::draw(QCPPainter *painter) { if (mActive) { painter->setPen(mPen); painter->setBrush(mBrush); painter->drawRect(mRect); } } /* end of 'src/selectionrect.cpp' */ /* including file 'src/layout.cpp' */ /* modified 2021-03-29T02:30:44, size 78863 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPMarginGroup //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPMarginGroup \brief A margin group allows synchronization of margin sides if working with multiple layout elements. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that they will all have the same size, based on the largest required margin in the group. \n \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" \n In certain situations it is desirable that margins at specific sides are synchronized across layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will provide a cleaner look to the user if the left and right margins of the two axis rects are of the same size. The left axis of the top axis rect will then be at the same horizontal position as the left axis of the lower axis rect, making them appear aligned. The same applies for the right axes. This is what QCPMarginGroup makes possible. To add/remove a specific side of a layout element to/from a margin group, use the \ref QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call \ref clear, or just delete the margin group. \section QCPMarginGroup-example Example First create a margin group: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1 Then set this group on the layout element sides: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2 Here, we've used the first two axis rects of the plot and synchronized their left margins with each other and their right margins with each other. */ /* start documentation of inline functions */ /*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const Returns a list of all layout elements that have their margin \a side associated with this margin group. */ /* end documentation of inline functions */ /*! Creates a new QCPMarginGroup instance in \a parentPlot. */ QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : QObject(parentPlot), mParentPlot(parentPlot) { mChildren.insert(QCP::msLeft, QList()); mChildren.insert(QCP::msRight, QList()); mChildren.insert(QCP::msTop, QList()); mChildren.insert(QCP::msBottom, QList()); } QCPMarginGroup::~QCPMarginGroup() { clear(); } /*! Returns whether this margin group is empty. If this function returns true, no layout elements use this margin group to synchronize margin sides. */ bool QCPMarginGroup::isEmpty() const { QHashIterator > it(mChildren); while (it.hasNext()) { it.next(); if (!it.value().isEmpty()) return false; } return true; } /*! Clears this margin group. The synchronization of the margin sides that use this margin group is lifted and they will use their individual margin sizes again. */ void QCPMarginGroup::clear() { // make all children remove themselves from this margin group: QHashIterator > it(mChildren); while (it.hasNext()) { it.next(); const QList elements = it.value(); for (int i=elements.size()-1; i>=0; --i) elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild } } /*! \internal Returns the synchronized common margin for \a side. This is the margin value that will be used by the layout element on the respective side, if it is part of this margin group. The common margin is calculated by requesting the automatic margin (\ref QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into account, too.) */ int QCPMarginGroup::commonMargin(QCP::MarginSide side) const { // query all automatic margins of the layout elements in this margin group side and find maximum: int result = 0; foreach (QCPLayoutElement *el, mChildren.value(side)) { if (!el->autoMargins().testFlag(side)) continue; int m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side)); if (m > result) result = m; } return result; } /*! \internal Adds \a element to the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].contains(element)) mChildren[side].append(element); else qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); } /*! \internal Removes \a element from the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].removeOne(element)) qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutElement //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutElement \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference between outer and inner rect is called its margin. The margin can either be set to automatic or manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, the layout element subclass will control the value itself (via \ref calculateAutoMargin). Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are invisible by themselves, because they don't draw anything. Their only purpose is to manage the position and size of other layout elements. This category of layout elements usually use QCPLayout as base class. Then there is the category of layout elements which actually draw something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does not necessarily mean that the latter category can't have child layout elements. QCPLegend for instance, actually derives from QCPLayoutGrid and the individual legend items are child layout elements in the grid layout. */ /* start documentation of inline functions */ /*! \fn QCPLayout *QCPLayoutElement::layout() const Returns the parent layout of this layout element. */ /*! \fn QRect QCPLayoutElement::rect() const Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). In some cases, the area between outer and inner rect is left blank. In other cases the margin area is used to display peripheral graphics while the main content is in the inner rect. This is where automatic margin calculation becomes interesting because it allows the layout element to adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if \ref setAutoMargins is enabled) according to the space required by the labels of the axes. \see outerRect */ /*! \fn QRect QCPLayoutElement::outerRect() const Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref setOuterRect) by the parent \ref QCPLayout to control the size of this layout element. \see rect */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutElement and sets default values. */ QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) mParentLayout(nullptr), mMinimumSize(), mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), mSizeConstraintRect(scrInnerRect), mRect(0, 0, 0, 0), mOuterRect(0, 0, 0, 0), mMargins(0, 0, 0, 0), mMinimumMargins(0, 0, 0, 0), mAutoMargins(QCP::msAll) { } QCPLayoutElement::~QCPLayoutElement() { setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any // unregister at layout: if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor mParentLayout->take(this); } /*! Sets the outer rect of this layout element. If the layout element is inside a layout, the layout sets the position and size of this layout element using this function. Calling this function externally has no effect, since the layout will overwrite any changes to the outer rect upon the next replot. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. \see rect */ void QCPLayoutElement::setOuterRect(const QRect &rect) { if (mOuterRect != rect) { mOuterRect = rect; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all sides, this function is used to manually set the margin on those sides. Sides that are still set to be handled automatically are ignored and may have any value in \a margins. The margin is the distance between the outer rect (controlled by the parent layout via \ref setOuterRect) and the inner \ref rect (which usually contains the main content of this layout element). \see setAutoMargins */ void QCPLayoutElement::setMargins(const QMargins &margins) { if (mMargins != margins) { mMargins = margins; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! If \ref setAutoMargins is enabled on some or all margins, this function is used to provide minimum values for those margins. The minimum values are not enforced on margin sides that were set to be under manual control via \ref setAutoMargins. \see setAutoMargins */ void QCPLayoutElement::setMinimumMargins(const QMargins &margins) { if (mMinimumMargins != margins) { mMinimumMargins = margins; } } /*! Sets on which sides the margin shall be calculated automatically. If a side is calculated automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is set to be controlled manually, the value may be specified with \ref setMargins. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref setMarginGroup), to synchronize (align) it with other layout elements in the plot. \see setMinimumMargins, setMargins, QCP::MarginSide */ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) { mAutoMargins = sides; } /*! Sets the minimum size of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot propagates the layout's size constraints to the outside by setting its own minimum QWidget size accordingly, so violations of \a size should be exceptions. Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMinimumSize(const QSize &size) { if (mMinimumSize != size) { mMinimumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the minimum size of this layout element. Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMinimumSize(int width, int height) { setMinimumSize(QSize(width, height)); } /*! Sets the maximum size of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMaximumSize(const QSize &size) { if (mMaximumSize != size) { mMaximumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the maximum size of this layout element. Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMaximumSize(int width, int height) { setMaximumSize(QSize(width, height)); } /*! Sets to which rect of a layout element the size constraints apply. Size constraints can be set via \ref setMinimumSize and \ref setMaximumSize. The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) does not. \see setMinimumSize, setMaximumSize */ void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect) { if (mSizeConstraintRect != constraintRect) { mSizeConstraintRect = constraintRect; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! Sets the margin \a group of the specified margin \a sides. Margin groups allow synchronizing specified margins across layout elements, see the documentation of \ref QCPMarginGroup. To unset the margin group of \a sides, set \a group to \c nullptr. Note that margin groups only work for margin sides that are set to automatic (\ref setAutoMargins). \see QCP::MarginSide */ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) { QVector sideVector; if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); foreach (QCP::MarginSide side, sideVector) { if (marginGroup(side) != group) { QCPMarginGroup *oldGroup = marginGroup(side); if (oldGroup) // unregister at old group oldGroup->removeChild(side, this); if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there { mMarginGroups.remove(side); } else // setting to a new group { mMarginGroups[side] = group; group->addChild(side, this); } } } } /*! Updates the layout element and sub-elements. This function is automatically called before every replot by the parent layout element. It is called multiple times, once for every \ref UpdatePhase. The phases are run through in the order of the enum values. For details about what happens at the different phases, see the documentation of \ref UpdatePhase. Layout elements that have child elements should call the \ref update method of their child elements, and pass the current \a phase unchanged. The default implementation executes the automatic margin mechanism in the \ref upMargins phase. Subclasses should make sure to call the base class implementation. */ void QCPLayoutElement::update(UpdatePhase phase) { if (phase == upMargins) { if (mAutoMargins != QCP::msNone) { // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: QMargins newMargins = mMargins; const QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; foreach (QCP::MarginSide side, allMarginSides) { if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically { if (mMarginGroups.contains(side)) QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group else QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly // apply minimum margin restrictions: if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); } } setMargins(newMargins); } } } /*! Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to, if no manual minimum size is set. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum allowed size of this layout element. A manual minimum size is considered set if it is non-zero. The default implementation simply returns the sum of the horizontal margins for the width and the sum of the vertical margins for the height. Reimplementations may use their detailed knowledge about the layout element's content to provide size hints. */ QSize QCPLayoutElement::minimumOuterSizeHint() const { return {mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()}; } /*! Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to, if no manual maximum size is set. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the maximum allowed size of this layout element. A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX. The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying no suggested maximum size. Reimplementations may use their detailed knowledge about the layout element's content to provide size hints. */ QSize QCPLayoutElement::maximumOuterSizeHint() const { return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX}; } /*! Returns a list of all child elements in this layout element. If \a recursive is true, all sub-child elements are included in the list, too. \warning There may be \c nullptr entries in the returned list. For example, QCPLayoutGrid may have empty cells which yield \c nullptr at the respective index. */ QList QCPLayoutElement::elements(bool recursive) const { Q_UNUSED(recursive) return QList(); } /*! Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer rect, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is true, -1.0 is returned. See \ref QCPLayerable::selectTest for a general explanation of this virtual method. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test behaviour. */ double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable) return -1; if (QRectF(mOuterRect).contains(pos)) { if (mParentPlot) return mParentPlot->selectionTolerance()*0.99; else { qDebug() << Q_FUNC_INFO << "parent plot not defined"; return -1; } } else return -1; } /*! \internal propagates the parent plot initialization to all child elements, by calling \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) { foreach (QCPLayoutElement *el, elements(false)) { if (!el->parentPlot()) el->initializeParentPlot(parentPlot); } } /*! \internal Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the returned value will not be smaller than the specified minimum margin. The default implementation just returns the respective manual margin (\ref setMargins) or the minimum margin, whichever is larger. */ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) { return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); } /*! \internal This virtual method is called when this layout element was moved to a different QCPLayout, or when this layout element has changed its logical position (e.g. row and/or column) within the same QCPLayout. Subclasses may use this to react accordingly. Since this method is called after the completion of the move, you can access the new parent layout via \ref layout(). The default implementation does nothing. */ void QCPLayoutElement::layoutChanged() { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayout //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayout \brief The abstract base class for layouts This is an abstract base class for layout elements whose main purpose is to define the position and size of other child layout elements. In most cases, layouts don't draw anything themselves (but there are exceptions to this, e.g. QCPLegend). QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions to this interface which are more specialized to the form of the layout. For example, \ref QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid more conveniently. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its subclasses like QCPLayoutGrid or QCPLayoutInset. For a general introduction to the layout system, see the dedicated documentation page \ref thelayoutsystem "The Layout System". */ /* start documentation of pure virtual functions */ /*! \fn virtual int QCPLayout::elementCount() const = 0 Returns the number of elements/cells in the layout. \see elements, elementAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 Returns the element in the cell with the given \a index. If \a index is invalid, returns \c nullptr. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. QCPLayoutGrid), so this function may return \c nullptr in those cases. You may use this function to check whether a cell is empty or not. \see elements, elementCount, takeAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 Removes the element with the given \a index from the layout and returns it. If the \a index is invalid or the cell with that index is empty, returns \c nullptr. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see elementAt, take */ /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 Removes the specified \a element from the layout and returns true on success. If the \a element isn't in this layout, returns false. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see takeAt */ /* end documentation of pure virtual functions */ /*! Creates an instance of QCPLayout and sets default values. Note that since QCPLayout is an abstract base class, it can't be instantiated directly. */ QCPLayout::QCPLayout() { } /*! If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to reposition and resize their cells. Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements". For details about this method and the update phases, see the documentation of \ref QCPLayoutElement::update. */ void QCPLayout::update(UpdatePhase phase) { QCPLayoutElement::update(phase); // set child element rects according to layout: if (phase == upLayout) updateLayout(); // propagate update call to child elements: const int elCount = elementCount(); for (int i=0; iupdate(phase); } } /* inherits documentation from base class */ QList QCPLayout::elements(bool recursive) const { const int c = elementCount(); QList result; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(c); #endif for (int i=0; ielements(recursive); } } return result; } /*! Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the default implementation does nothing. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit simplification while QCPLayoutGrid does. */ void QCPLayout::simplify() { } /*! Removes and deletes the element at the provided \a index. Returns true on success. If \a index is invalid or points to an empty cell, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the returned element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see remove, takeAt */ bool QCPLayout::removeAt(int index) { if (QCPLayoutElement *el = takeAt(index)) { delete el; return true; } else return false; } /*! Removes and deletes the provided \a element. Returns true on success. If \a element is not in the layout, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see removeAt, take */ bool QCPLayout::remove(QCPLayoutElement *element) { if (take(element)) { delete element; return true; } else return false; } /*! Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure all empty cells are collapsed. \see remove, removeAt */ void QCPLayout::clear() { for (int i=elementCount()-1; i>=0; --i) { if (elementAt(i)) removeAt(i); } simplify(); } /*! Subclasses call this method to report changed (minimum/maximum) size constraints. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, it may update itself and resize cells accordingly. */ void QCPLayout::sizeConstraintsChanged() const { if (QWidget *w = qobject_cast(parent())) w->updateGeometry(); else if (QCPLayout *l = qobject_cast(parent())) l->sizeConstraintsChanged(); } /*! \internal Subclasses reimplement this method to update the position and sizes of the child elements/cells via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay within that rect. \ref getSectionSizes may help with the reimplementation of this function. \see update */ void QCPLayout::updateLayout() { } /*! \internal Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the \ref QCPLayerable::parentLayerable and the QObject parent to this layout. Further, if \a el didn't previously have a parent plot, calls \ref QCPLayerable::initializeParentPlot on \a el to set the paret plot. This method is used by subclass specific methods that add elements to the layout. Note that this method only changes properties in \a el. The removal from the old layout and the insertion into the new layout must be done additionally. */ void QCPLayout::adoptElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = this; el->setParentLayerable(this); el->setParent(this); if (!el->parentPlot()) el->initializeParentPlot(mParentPlot); el->layoutChanged(); } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent QCustomPlot. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref take or \ref takeAt). Note that this method only changes properties in \a el. The removal from the old layout must be done additionally. */ void QCPLayout::releaseElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = nullptr; el->setParentLayerable(nullptr); el->setParent(mParentPlot); // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal This is a helper function for the implementation of \ref updateLayout in subclasses. It calculates the sizes of one-dimensional sections with provided constraints on maximum section sizes, minimum section sizes, relative stretch factors and the final total size of all sections. The QVector entries refer to the sections. Thus all QVectors must have the same size. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size imposed, set all vector values to Qt's QWIDGETSIZE_MAX. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, not exceeding the allowed total size is taken to be more important than not going below minimum section sizes.) \a stretchFactors give the relative proportions of the sections to each other. If all sections shall be scaled equally, set all values equal. If the first section shall be double the size of each individual other section, set the first number of \a stretchFactors to double the value of the other individual values (e.g. {2, 1, 1, 1}). \a totalSize is the value that the final section sizes will add up to. Due to rounding, the actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, you could distribute the remaining difference on the sections. The return value is a QVector containing the section sizes. */ QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const { if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) { qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; return QVector(); } if (stretchFactors.isEmpty()) return QVector(); int sectionCount = stretchFactors.size(); QVector sectionSizes(sectionCount); // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): int minSizeSum = 0; for (int i=0; i minimumLockedSections; QList unfinishedSections; for (int i=0; i result(sectionCount); for (int i=0; iminimumOuterSizeHint(); QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0) if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) minOuter.rwidth() += el->margins().left() + el->margins().right(); if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) minOuter.rheight() += el->margins().top() + el->margins().bottom(); return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(), minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()}; } /*! \internal This is a helper function for the implementation of subclasses. It returns the maximum size that should finally be used for the outer rect of the passed layout element \a el. It takes into account whether a manual maximum size is set (\ref QCPLayoutElement::setMaximumSize), which size constraint is set (\ref QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum size was set (\ref QCPLayoutElement::maximumOuterSizeHint). */ QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el) { QSize maxOuterHint = el->maximumOuterSizeHint(); QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX) if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) maxOuter.rwidth() += el->margins().left() + el->margins().right(); if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) maxOuter.rheight() += el->margins().top() + el->margins().bottom(); return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(), maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()}; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutGrid \brief A layout that arranges child elements in a grid Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor, \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing). Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref hasElement, that element can be retrieved with \ref element. If rows and columns that only have empty cells shall be removed, call \ref simplify. Removal of elements is either done by just adding the element to a different layout or by using the QCPLayout interface \ref take or \ref remove. If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a column, the grid layout will choose the position according to the current \ref setFillOrder and the wrapping (\ref setWrap). Row and column insertion can be performed with \ref insertRow and \ref insertColumn. */ /* start documentation of inline functions */ /*! \fn int QCPLayoutGrid::rowCount() const Returns the number of rows in the layout. \see columnCount */ /*! \fn int QCPLayoutGrid::columnCount() const Returns the number of columns in the layout. \see rowCount */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutGrid and sets default values. */ QCPLayoutGrid::QCPLayoutGrid() : mColumnSpacing(5), mRowSpacing(5), mWrap(0), mFillOrder(foColumnsFirst) { } QCPLayoutGrid::~QCPLayoutGrid() { // clear all child layout elements. This is important because only the specific layouts know how // to handle removing elements (clear calls virtual removeAt method to do that). clear(); } /*! Returns the element in the cell in \a row and \a column. Returns \c nullptr if either the row/column is invalid or if the cell is empty. In those cases, a qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement. \see addElement, hasElement */ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const { if (row >= 0 && row < mElements.size()) { if (column >= 0 && column < mElements.first().size()) { if (QCPLayoutElement *result = mElements.at(row).at(column)) return result; else qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; return nullptr; } /*! \overload Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it is first removed from there. If \a row or \a column don't exist yet, the layout is expanded accordingly. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column didn't already have an element. Use the overload of this method without explicit row/column index to place the element according to the configured fill order and wrapping settings. \see element, hasElement, take, remove */ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) { if (!hasElement(row, column)) { if (element && element->layout()) // remove from old layout first element->layout()->take(element); expandTo(row+1, column+1); mElements[row][column] = element; if (element) adoptElement(element); return true; } else qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; return false; } /*! \overload Adds the \a element to the next empty cell according to the current fill order (\ref setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first removed from there. If necessary, the layout is expanded to hold the new element. Returns true if the element was added successfully. \see setFillOrder, setWrap, element, hasElement, take, remove */ bool QCPLayoutGrid::addElement(QCPLayoutElement *element) { int rowIndex = 0; int colIndex = 0; if (mFillOrder == foColumnsFirst) { while (hasElement(rowIndex, colIndex)) { ++colIndex; if (colIndex >= mWrap && mWrap > 0) { colIndex = 0; ++rowIndex; } } } else { while (hasElement(rowIndex, colIndex)) { ++rowIndex; if (rowIndex >= mWrap && mWrap > 0) { rowIndex = 0; ++colIndex; } } } return addElement(rowIndex, colIndex, element); } /*! Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't empty. \see element */ bool QCPLayoutGrid::hasElement(int row, int column) { if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) return mElements.at(row).at(column); else return false; } /*! Sets the stretch \a factor of \a column. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) { if (column >= 0 && column < columnCount()) { if (factor > 0) mColumnStretchFactors[column] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid column:" << column; } /*! Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactor, setRowStretchFactors */ void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) { if (factors.size() == mColumnStretchFactors.size()) { mColumnStretchFactors = factors; for (int i=0; i= 0 && row < rowCount()) { if (factor > 0) mRowStretchFactors[row] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid row:" << row; } /*! Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) The default stretch factor of newly created rows/columns is 1. \see setRowStretchFactor, setColumnStretchFactors */ void QCPLayoutGrid::setRowStretchFactors(const QList &factors) { if (factors.size() == mRowStretchFactors.size()) { mRowStretchFactors = factors; for (int i=0; i tempElements; if (rearrange) { tempElements.reserve(elCount); for (int i=0; i()); mRowStretchFactors.append(1); } // go through rows and expand columns as necessary: int newColCount = qMax(columnCount(), newColumnCount); for (int i=0; i rowCount()) newIndex = rowCount(); mRowStretchFactors.insert(newIndex, 1); QList newRow; for (int col=0; col columnCount()) newIndex = columnCount(); mColumnStretchFactors.insert(newIndex, 1); for (int row=0; row= 0 && row < rowCount()) { if (column >= 0 && column < columnCount()) { switch (mFillOrder) { case foRowsFirst: return column*rowCount() + row; case foColumnsFirst: return row*columnCount() + column; } } else qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row; } else qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column; return 0; } /*! Converts the linear index to row and column indices and writes the result to \a row and \a column. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices increase top to bottom and then left to right. If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1. For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself, i.e. greater or equal to zero and smaller than the current \ref elementCount. \see rowColToIndex */ void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const { row = -1; column = -1; const int nCols = columnCount(); const int nRows = rowCount(); if (nCols == 0 || nRows == 0) return; if (index < 0 || index >= elementCount()) { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return; } switch (mFillOrder) { case foRowsFirst: { column = index / nRows; row = index % nRows; break; } case foColumnsFirst: { row = index / nCols; column = index % nCols; break; } } } /* inherits documentation from base class */ void QCPLayoutGrid::updateLayout() { QVector minColWidths, minRowHeights, maxColWidths, maxRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); getMaximumRowColSizes(&maxColWidths, &maxRowHeights); int totalRowSpacing = (rowCount()-1) * mRowSpacing; int totalColSpacing = (columnCount()-1) * mColumnSpacing; QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); // go through cells and set rects accordingly: int yOffset = mRect.top(); for (int row=0; row 0) yOffset += rowHeights.at(row-1)+mRowSpacing; int xOffset = mRect.left(); for (int col=0; col 0) xOffset += colWidths.at(col-1)+mColumnSpacing; if (mElements.at(row).at(col)) mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); } } } /*! \seebaseclassmethod Note that the association of the linear \a index to the row/column based cells depends on the current setting of \ref setFillOrder. \see rowColToIndex */ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const { if (index >= 0 && index < elementCount()) { int row, col; indexToRowCol(index, row, col); return mElements.at(row).at(col); } else return nullptr; } /*! \seebaseclassmethod Note that the association of the linear \a index to the row/column based cells depends on the current setting of \ref setFillOrder. \see rowColToIndex */ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); int row, col; indexToRowCol(index, row, col); mElements[row][col] = nullptr; return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return nullptr; } } /* inherits documentation from base class */ bool QCPLayoutGrid::take(QCPLayoutElement *element) { if (element) { for (int i=0; i QCPLayoutGrid::elements(bool recursive) const { QList result; const int elCount = elementCount(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(elCount); #endif for (int i=0; ielements(recursive); } } return result; } /*! Simplifies the layout by collapsing rows and columns which only contain empty cells. */ void QCPLayoutGrid::simplify() { // remove rows with only empty cells: for (int row=rowCount()-1; row>=0; --row) { bool hasElements = false; for (int col=0; col=0; --col) { bool hasElements = false; for (int row=0; row minColWidths, minRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); QSize result(0, 0); foreach (int w, minColWidths) result.rwidth() += w; foreach (int h, minRowHeights) result.rheight() += h; result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing; result.rheight() += qMax(0, rowCount()-1) * mRowSpacing; result.rwidth() += mMargins.left()+mMargins.right(); result.rheight() += mMargins.top()+mMargins.bottom(); return result; } /* inherits documentation from base class */ QSize QCPLayoutGrid::maximumOuterSizeHint() const { QVector maxColWidths, maxRowHeights; getMaximumRowColSizes(&maxColWidths, &maxRowHeights); QSize result(0, 0); foreach (int w, maxColWidths) result.setWidth(qMin(result.width()+w, QWIDGETSIZE_MAX)); foreach (int h, maxRowHeights) result.setHeight(qMin(result.height()+h, QWIDGETSIZE_MAX)); result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing; result.rheight() += qMax(0, rowCount()-1) * mRowSpacing; result.rwidth() += mMargins.left()+mMargins.right(); result.rheight() += mMargins.top()+mMargins.bottom(); if (result.height() > QWIDGETSIZE_MAX) result.setHeight(QWIDGETSIZE_MAX); if (result.width() > QWIDGETSIZE_MAX) result.setWidth(QWIDGETSIZE_MAX); return result; } /*! \internal Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights respectively. The minimum height of a row is the largest minimum height of any element's outer rect in that row. The minimum width of a column is the largest minimum width of any element's outer rect in that column. This is a helper function for \ref updateLayout. \see getMaximumRowColSizes */ void QCPLayoutGrid::getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const { *minColWidths = QVector(columnCount(), 0); *minRowHeights = QVector(rowCount(), 0); for (int row=0; rowat(col) < minSize.width()) (*minColWidths)[col] = minSize.width(); if (minRowHeights->at(row) < minSize.height()) (*minRowHeights)[row] = minSize.height(); } } } } /*! \internal Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights respectively. The maximum height of a row is the smallest maximum height of any element's outer rect in that row. The maximum width of a column is the smallest maximum width of any element's outer rect in that column. This is a helper function for \ref updateLayout. \see getMinimumRowColSizes */ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const { *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); for (int row=0; rowat(col) > maxSize.width()) (*maxColWidths)[col] = maxSize.width(); if (maxRowHeights->at(row) > maxSize.height()) (*maxRowHeights)[row] = maxSize.height(); } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutInset //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutInset \brief A layout that places child elements aligned to the border or arbitrarily positioned Elements are placed either aligned to the border or at arbitrary position in the area of the layout. Which placement applies is controlled with the \ref InsetPlacement (\ref setInsetPlacement). Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset placement will default to \ref ipBorderAligned and the element will be aligned according to the \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at arbitrary position and size, defined by \a rect. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout. */ /* start documentation of inline functions */ /*! \fn virtual void QCPLayoutInset::simplify() The QCPInsetLayout does not need simplification since it can never have empty cells due to its linear index structure. This method does nothing. */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutInset and sets default values. */ QCPLayoutInset::QCPLayoutInset() { } QCPLayoutInset::~QCPLayoutInset() { // clear all child layout elements. This is important because only the specific layouts know how // to handle removing elements (clear calls virtual removeAt method to do that). clear(); } /*! Returns the placement type of the element with the specified \a index. */ QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const { if (elementAt(index)) return mInsetPlacement.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return ipFree; } } /*! Returns the alignment of the element with the specified \a index. The alignment only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned. */ Qt::Alignment QCPLayoutInset::insetAlignment(int index) const { if (elementAt(index)) return mInsetAlignment.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0) return nullptr; #else return {}; #endif } } /*! Returns the rect of the element with the specified \a index. The rect only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree. */ QRectF QCPLayoutInset::insetRect(int index) const { if (elementAt(index)) return mInsetRect.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return {}; } } /*! Sets the inset placement type of the element with the specified \a index to \a placement. \see InsetPlacement */ void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement) { if (elementAt(index)) mInsetPlacement[index] = placement; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function is used to set the alignment of the element with the specified \a index to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. */ void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment) { if (elementAt(index)) mInsetAlignment[index] = alignment; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the position and size of the element with the specified \a index to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. Note that the minimum and maximum sizes of the embedded element (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced. */ void QCPLayoutInset::setInsetRect(int index, const QRectF &rect) { if (elementAt(index)) mInsetRect[index] = rect; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /* inherits documentation from base class */ void QCPLayoutInset::updateLayout() { for (int i=0; i finalMaxSize.width()) insetRect.setWidth(finalMaxSize.width()); if (insetRect.size().height() > finalMaxSize.height()) insetRect.setHeight(finalMaxSize.height()); } else if (mInsetPlacement.at(i) == ipBorderAligned) { insetRect.setSize(finalMinSize); Qt::Alignment al = mInsetAlignment.at(i); if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); else insetRect.moveLeft(int( rect().x()+rect().width()*0.5-finalMinSize.width()*0.5 )); // default to Qt::AlignHCenter if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); else insetRect.moveTop(int( rect().y()+rect().height()*0.5-finalMinSize.height()*0.5 )); // default to Qt::AlignVCenter } mElements.at(i)->setOuterRect(insetRect); } } /* inherits documentation from base class */ int QCPLayoutInset::elementCount() const { return mElements.size(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::elementAt(int index) const { if (index >= 0 && index < mElements.size()) return mElements.at(index); else return nullptr; } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); mElements.removeAt(index); mInsetPlacement.removeAt(index); mInsetAlignment.removeAt(index); mInsetRect.removeAt(index); return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return nullptr; } } /* inherits documentation from base class */ bool QCPLayoutInset::take(QCPLayoutElement *element) { if (element) { for (int i=0; irealVisibility() && el->selectTest(pos, onlySelectable) >= 0) return mParentPlot->selectionTolerance()*0.99; } return -1; } /*! Adds the specified \a element to the layout as an inset aligned at the border (\ref setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. \see addElement(QCPLayoutElement *element, const QRectF &rect) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipBorderAligned); mInsetAlignment.append(alignment); mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add nullptr element"; } /*! Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipFree); mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); mInsetRect.append(rect); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add nullptr element"; } /* end of 'src/layout.cpp' */ /* including file 'src/lineending.cpp' */ /* modified 2021-03-29T02:30:44, size 11189 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLineEnding //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLineEnding \brief Handles the different ending decorations for line-like items \image html QCPLineEnding.png "The various ending styles currently supported" For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite directions, e.g. "outward". This can be changed by \ref setInverted, which would make the respective arrow point inward. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead */ /*! Creates a QCPLineEnding instance with default values (style \ref esNone). */ QCPLineEnding::QCPLineEnding() : mStyle(esNone), mWidth(8), mLength(10), mInverted(false) { } /*! Creates a QCPLineEnding instance with the specified values. */ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : mStyle(style), mWidth(width), mLength(length), mInverted(inverted) { } /*! Sets the style of the ending decoration. */ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) { mStyle = style; } /*! Sets the width of the ending decoration, if the style supports it. On arrows, for example, the width defines the size perpendicular to the arrow's pointing direction. \see setLength */ void QCPLineEnding::setWidth(double width) { mWidth = width; } /*! Sets the length of the ending decoration, if the style supports it. On arrows, for example, the length defines the size in pointing direction. \see setWidth */ void QCPLineEnding::setLength(double length) { mLength = length; } /*! Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point inward when \a inverted is set to true. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are affected by it, which can be used to control to which side the half bar points to. */ void QCPLineEnding::setInverted(bool inverted) { mInverted = inverted; } /*! \internal Returns the maximum pixel radius the ending decoration might cover, starting from the position the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). This is relevant for clipping. Only omit painting of the decoration when the position where the decoration is supposed to be drawn is farther away from the clipping rect than the returned distance. */ double QCPLineEnding::boundingDistance() const { switch (mStyle) { case esNone: return 0; case esFlatArrow: case esSpikeArrow: case esLineArrow: case esSkewedBar: return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length case esDisc: case esSquare: case esDiamond: case esBar: case esHalfBar: return mWidth*1.42; // items that only have a width -> width*sqrt(2) } return 0; } /*! Starting from the origin of this line ending (which is style specific), returns the length covered by the line ending symbol, in backward direction. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if both have the same \ref setLength value, because the spike arrow has an inward curved back, which reduces the length along its center axis (the drawing origin for arrows is at the tip). This function is used for precise, style specific placement of line endings, for example in QCPAxes. */ double QCPLineEnding::realLength() const { switch (mStyle) { case esNone: case esLineArrow: case esSkewedBar: case esBar: case esHalfBar: return 0; case esFlatArrow: return mLength; case esDisc: case esSquare: case esDiamond: return mWidth*0.5; case esSpikeArrow: return mLength*0.8; } return 0; } /*! \internal Draws the line ending with the specified \a painter at the position \a pos. The direction of the line ending is controlled with \a dir. */ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const { if (mStyle == esNone) return; QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1); if (lengthVec.isNull()) lengthVec = QCPVector2D(1, 0); QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1); QPen penBackup = painter->pen(); QBrush brushBackup = painter->brush(); QPen miterPen = penBackup; miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey QBrush brush(painter->pen().color(), Qt::SolidPattern); switch (mStyle) { case esNone: break; case esFlatArrow: { QPointF points[3] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 3); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esSpikeArrow: { QPointF points[4] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec*0.8).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esLineArrow: { QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), pos.toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->drawPolyline(points, 3); painter->setPen(penBackup); break; } case esDisc: { painter->setBrush(brush); painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); painter->setBrush(brushBackup); break; } case esSquare: { QCPVector2D widthVecPerp = widthVec.perpendicular(); QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), (pos-widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esDiamond: { QCPVector2D widthVecPerp = widthVec.perpendicular(); QPointF points[4] = {(pos-widthVecPerp).toPointF(), (pos-widthVec).toPointF(), (pos+widthVecPerp).toPointF(), (pos+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esBar: { painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); break; } case esHalfBar: { painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); break; } case esSkewedBar: { QCPVector2D shift; if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic)) shift = dir.normalized()*qMax(qreal(1.0), painter->pen().widthF())*qreal(0.5); // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+shift).toPointF(), (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+shift).toPointF()); break; } } } /*! \internal \overload Draws the line ending. The direction is controlled with the \a angle parameter in radians. */ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const { draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle))); } /* end of 'src/lineending.cpp' */ /* including file 'src/axis/labelpainter.cpp' */ /* modified 2021-03-29T02:30:44, size 27296 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLabelPainterPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLabelPainterPrivate \internal \brief (Private) This is a private class and not part of the public QCustomPlot interface. */ const QChar QCPLabelPainterPrivate::SymbolDot(183); const QChar QCPLabelPainterPrivate::SymbolCross(215); /*! Constructs a QCPLabelPainterPrivate instance. Make sure to not create a new instance on every redraw, to utilize the caching mechanisms. the \a parentPlot does not take ownership of the label painter. Make sure to delete it appropriately. */ QCPLabelPainterPrivate::QCPLabelPainterPrivate(QCustomPlot *parentPlot) : mAnchorMode(amRectangular), mAnchorSide(asLeft), mAnchorReferenceType(artNormal), mColor(Qt::black), mPadding(0), mRotation(0), mSubstituteExponent(true), mMultiplicationSymbol(QChar(215)), mAbbreviateDecimalPowers(false), mParentPlot(parentPlot), mLabelCache(16) { analyzeFontMetrics(); } QCPLabelPainterPrivate::~QCPLabelPainterPrivate() { } void QCPLabelPainterPrivate::setAnchorSide(AnchorSide side) { mAnchorSide = side; } void QCPLabelPainterPrivate::setAnchorMode(AnchorMode mode) { mAnchorMode = mode; } void QCPLabelPainterPrivate::setAnchorReference(const QPointF &pixelPoint) { mAnchorReference = pixelPoint; } void QCPLabelPainterPrivate::setAnchorReferenceType(AnchorReferenceType type) { mAnchorReferenceType = type; } void QCPLabelPainterPrivate::setFont(const QFont &font) { if (mFont != font) { mFont = font; analyzeFontMetrics(); } } void QCPLabelPainterPrivate::setColor(const QColor &color) { mColor = color; } void QCPLabelPainterPrivate::setPadding(int padding) { mPadding = padding; } void QCPLabelPainterPrivate::setRotation(double rotation) { mRotation = qBound(-90.0, rotation, 90.0); } void QCPLabelPainterPrivate::setSubstituteExponent(bool enabled) { mSubstituteExponent = enabled; } void QCPLabelPainterPrivate::setMultiplicationSymbol(QChar symbol) { mMultiplicationSymbol = symbol; } void QCPLabelPainterPrivate::setAbbreviateDecimalPowers(bool enabled) { mAbbreviateDecimalPowers = enabled; } void QCPLabelPainterPrivate::setCacheSize(int labelCount) { mLabelCache.setMaxCost(labelCount); } int QCPLabelPainterPrivate::cacheSize() const { return mLabelCache.maxCost(); } void QCPLabelPainterPrivate::drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text) { double realRotation = mRotation; AnchorSide realSide = mAnchorSide; // for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference if (mAnchorMode == amSkewedUpright) { realSide = skewedAnchorSide(tickPos, 0.2, 0.3); } else if (mAnchorMode == amSkewedRotated) // in this mode every label is individually rotated to match circle tangent { realSide = skewedAnchorSide(tickPos, 0, 0); realRotation += QCPVector2D(tickPos-mAnchorReference).angle()/M_PI*180.0; if (realRotation > 90) realRotation -= 180; else if (realRotation < -90) realRotation += 180; } realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text); } /*! \internal Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ /* TODO: needed? int QCPLabelPainterPrivate::size() const { int result = 0; // get length of tick marks pointing outwards: if (!tickPositions.isEmpty()) result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // calculate size of tick labels: if (tickLabelSide == QCPAxis::lsOutside) { QSize tickLabelsSize(0, 0); if (!tickLabels.isEmpty()) { for (int i=0; ibufferDevicePixelRatio())); result.append(QByteArray::number(mRotation)); //result.append(QByteArray::number((int)tickLabelSide)); TODO: check whether this is really a cache-invalidating property result.append(QByteArray::number((int)mSubstituteExponent)); result.append(QString(mMultiplicationSymbol).toUtf8()); result.append(mColor.name().toLatin1()+QByteArray::number(mColor.alpha(), 16)); result.append(mFont.toString().toLatin1()); return result; } /*! \internal Draws a single tick label with the provided \a painter, utilizing the internal label cache to significantly speed up drawing of labels that were drawn in previous calls. The tick label is always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate), at which the label should be drawn. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently holds. The label is drawn with the font and pen that are currently set on the \a painter. To draw superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref getTickLabelData). */ void QCPLabelPainterPrivate::drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text) { // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! if (text.isEmpty()) return; QSize finalSize; if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled { QByteArray key = cacheKey(text, color, rotation, side); CachedLabel *cachedLabel = mLabelCache.take(QString::fromUtf8(key)); // attempt to take label from cache (don't use object() because we want ownership/prevent deletion during our operations, we re-insert it afterwards) if (!cachedLabel) // no cached label existed, create it { LabelData labelData = getTickLabelData(font, color, rotation, side, text); cachedLabel = createCachedLabel(labelData); } // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; /* if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left(); else labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); } */ if (!labelClippedByBorder) { painter->drawPixmap(pos+cachedLabel->offset, cachedLabel->pixmap); finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list? } mLabelCache.insert(QString::fromUtf8(key), cachedLabel); } else // label caching disabled, draw text directly on surface: { LabelData labelData = getTickLabelData(font, color, rotation, side, text); // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; /* if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); else labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); } */ if (!labelClippedByBorder) { drawText(painter, pos, labelData); finalSize = labelData.rotatedTotalBounds.size(); } } /* // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); */ } QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos) { switch (mAnchorMode) { case amRectangular: { switch (mAnchorSide) { case asLeft: return tickPos+QPointF(mPadding, 0); case asRight: return tickPos+QPointF(-mPadding, 0); case asTop: return tickPos+QPointF(0, mPadding); case asBottom: return tickPos+QPointF(0, -mPadding); case asTopLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2); case asTopRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2); case asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2); case asBottomLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2); } } case amSkewedUpright: case amSkewedRotated: { QCPVector2D anchorNormal(tickPos-mAnchorReference); if (mAnchorReferenceType == artTangent) anchorNormal = anchorNormal.perpendicular(); anchorNormal.normalize(); return tickPos+(anchorNormal*mPadding).toPointF(); } } return tickPos; } /*! \internal This is a \ref placeTickLabel helper function. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when QCP::phCacheLabels plotting hint is not set. */ void QCPLabelPainterPrivate::drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const { // backup painter settings that we're about to change: QTransform oldTransform = painter->transform(); QFont oldFont = painter->font(); QPen oldPen = painter->pen(); // transform painter to position/rotation: painter->translate(pos); painter->setTransform(labelData.transform, true); // draw text: painter->setFont(labelData.baseFont); painter->setPen(QPen(labelData.color)); if (!labelData.expPart.isEmpty()) // use superscripted exponent typesetting { painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); if (!labelData.suffixPart.isEmpty()) painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart); painter->setFont(labelData.expFont); painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); } else { painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); } /* Debug code to draw label bounding boxes, baseline, and capheight painter->save(); painter->setPen(QPen(QColor(0, 0, 0, 150))); painter->drawRect(labelData.totalBounds); const int baseline = labelData.totalBounds.height()-mLetterDescent; painter->setPen(QPen(QColor(255, 0, 0, 150))); painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline)); painter->setPen(QPen(QColor(0, 0, 255, 150))); painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight)); painter->restore(); */ // reset painter settings to what it was before: painter->setTransform(oldTransform); painter->setFont(oldFont); painter->setPen(oldPen); } /*! \internal This is a \ref placeTickLabel helper function. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPLabelPainterPrivate::LabelData QCPLabelPainterPrivate::getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const { LabelData result; result.rotation = rotation; result.side = side; result.color = color; // determine whether beautiful decimal powers should be used bool useBeautifulPowers = false; int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart if (mSubstituteExponent) { ePos = text.indexOf(QLatin1Char('e')); if (ePos > 0 && text.at(ePos-1).isDigit()) { eLast = ePos; while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit())) ++eLast; if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power useBeautifulPowers = true; } } // calculate text bounding rects and do string preparation for beautiful decimal powers: result.baseFont = font; if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding QFontMetrics baseFontMetrics(result.baseFont); if (useBeautifulPowers) { // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: result.basePart = text.left(ePos); result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: if (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1")) result.basePart = QLatin1String("10"); else result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10"); result.expPart = text.mid(ePos+1, eLast-ePos); // clip "+" and leading zeros off expPart: while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e' result.expPart.remove(1, 1); if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) result.expPart.remove(0, 1); // prepare smaller font for exponent: result.expFont = font; if (result.expFont.pointSize() > 0) result.expFont.setPointSize(result.expFont.pointSize()*0.75); else result.expFont.setPixelSize(result.expFont.pixelSize()*0.75); // calculate bounding rects of base part(s), exponent part and total one: result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); if (!result.suffixPart.isEmpty()) result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart); result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA } else // useBeautifulPowers == false { result.basePart = text; result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); } result.totalBounds.moveTopLeft(QPoint(0, 0)); applyAnchorTransform(result); result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds); return result; } void QCPLabelPainterPrivate::applyAnchorTransform(LabelData &labelData) const { if (!qFuzzyIsNull(labelData.rotation)) labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system) // from now on we translate in rotated label-local coordinate system. // shift origin of coordinate system to appropriate point on label: labelData.transform.translate(0, -labelData.totalBounds.height()+mLetterDescent+mLetterCapHeight); // shifts origin to true top of capital (or number) characters if (labelData.side == asLeft || labelData.side == asRight) // anchor is centered vertically labelData.transform.translate(0, -mLetterCapHeight/2.0); else if (labelData.side == asTop || labelData.side == asBottom) // anchor is centered horizontally labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0); if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) // anchor is at right labelData.transform.translate(-labelData.totalBounds.width(), 0); if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) // anchor is at bottom (no elseif!) labelData.transform.translate(0, -mLetterCapHeight); } /*! \internal Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a smaller width/height. */ /* void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { // note: this function must return the same tick label sizes as the placeTickLabel function. QSize finalSize; if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label { const CachedLabel *cachedLabel = mLabelCache.object(text); finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); } else // label caching disabled or no label with this text cached: { // TODO: LabelData labelData = getTickLabelData(font, text); // TODO: finalSize = labelData.rotatedTotalBounds.size(); } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } */ QCPLabelPainterPrivate::CachedLabel *QCPLabelPainterPrivate::createCachedLabel(const LabelData &labelData) const { CachedLabel *result = new CachedLabel; // allocate pixmap with the correct size and pixel ratio: if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio())) { result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio()); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED # ifdef QCP_DEVICEPIXELRATIO_FLOAT result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); # else result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); # endif #endif } else result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); result->pixmap.fill(Qt::transparent); // draw the label into the pixmap // offset is between label anchor and topleft of cache pixmap, so pixmap can be drawn at pos+offset to make the label anchor appear at pos. // We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0) result->offset = labelData.rotatedTotalBounds.topLeft(); QCPPainter cachePainter(&result->pixmap); drawText(&cachePainter, -result->offset, labelData); return result; } QByteArray QCPLabelPainterPrivate::cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const { return text.toUtf8()+ QByteArray::number(color.red()+256*color.green()+65536*color.blue(), 36)+ QByteArray::number(color.alpha()+256*(int)side, 36)+ QByteArray::number((int)(rotation*100)%36000, 36); } QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const { QCPVector2D anchorNormal = QCPVector2D(tickPos-mAnchorReference); if (mAnchorReferenceType == artTangent) anchorNormal = anchorNormal.perpendicular(); const double radius = anchorNormal.length(); const double sideHorz = sideExpandHorz*radius; const double sideVert = sideExpandVert*radius; if (anchorNormal.x() > sideHorz) { if (anchorNormal.y() > sideVert) return asTopLeft; else if (anchorNormal.y() < -sideVert) return asBottomLeft; else return asLeft; } else if (anchorNormal.x() < -sideHorz) { if (anchorNormal.y() > sideVert) return asTopRight; else if (anchorNormal.y() < -sideVert) return asBottomRight; else return asRight; } else { if (anchorNormal.y() > 0) return asTop; else return asBottom; } return asBottom; // should never be reached } QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::rotationCorrectedSide(AnchorSide side, double rotation) const { AnchorSide result = side; const bool rotateClockwise = rotation > 0; if (!qFuzzyIsNull(rotation)) { if (!qFuzzyCompare(qAbs(rotation), 90)) // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately: { if (side == asTop) result = rotateClockwise ? asLeft : asRight; else if (side == asBottom) result = rotateClockwise ? asRight : asLeft; else if (side == asTopLeft) result = rotateClockwise ? asLeft : asTop; else if (side == asTopRight) result = rotateClockwise ? asTop : asRight; else if (side == asBottomLeft) result = rotateClockwise ? asBottom : asLeft; else if (side == asBottomRight) result = rotateClockwise ? asRight : asBottom; } else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor: { if (side == asLeft) result = rotateClockwise ? asBottom : asTop; else if (side == asRight) result = rotateClockwise ? asTop : asBottom; else if (side == asTop) result = rotateClockwise ? asLeft : asRight; else if (side == asBottom) result = rotateClockwise ? asRight : asLeft; else if (side == asTopLeft) result = rotateClockwise ? asBottomLeft : asTopRight; else if (side == asTopRight) result = rotateClockwise ? asTopLeft : asBottomRight; else if (side == asBottomLeft) result = rotateClockwise ? asBottomRight : asTopLeft; else if (side == asBottomRight) result = rotateClockwise ? asTopRight : asBottomLeft; } } return result; } void QCPLabelPainterPrivate::analyzeFontMetrics() { const QFontMetrics fm(mFont); mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change mLetterDescent = fm.descent(); } /* end of 'src/axis/labelpainter.cpp' */ /* including file 'src/axis/axisticker.cpp' */ /* modified 2021-03-29T02:30:44, size 18688 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisTicker //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisTicker \brief The base class tick generator used by QCPAxis to create tick positions and tick labels Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions and tick labels for the current axis range. The ticker of an axis can be set via \ref QCPAxis::setTicker. Since that method takes a QSharedPointer, multiple axes can share the same ticker instance. This base class generates normal tick coordinates and numeric labels for linear axes. It picks a reasonable tick step (the separation between ticks) which results in readable tick labels. The number of ticks that should be approximately generated can be set via \ref setTickCount. Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either sacrifices readability to better match the specified tick count (\ref QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref QCPAxisTicker::tssReadability), which is the default. The following more specialized axis ticker subclasses are available, see details in the respective class documentation:
QCPAxisTickerFixed\image html axisticker-fixed.png
QCPAxisTickerLog\image html axisticker-log.png
QCPAxisTickerPi\image html axisticker-pi.png
QCPAxisTickerText\image html axisticker-text.png
QCPAxisTickerDateTime\image html axisticker-datetime.png
QCPAxisTickerTime\image html axisticker-time.png \image html axisticker-time2.png
\section axisticker-subclassing Creating own axis tickers Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and reimplementing some or all of the available virtual methods. In the simplest case you might wish to just generate different tick steps than the other tickers, so you only reimplement the method \ref getTickStep. If you additionally want control over the string that will be shown as tick label, reimplement \ref getTickLabel. If you wish to have complete control, you can generate the tick vectors and tick label vectors yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default implementations use the previously mentioned virtual methods \ref getTickStep and \ref getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored. The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick placement control is obtained by reimplementing \ref createSubTickVector. See the documentation of all these virtual methods in QCPAxisTicker for detailed information about the parameters and expected return values. */ /*! Constructs the ticker and sets reasonable default values. Axis tickers are commonly created managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTicker::QCPAxisTicker() : mTickStepStrategy(tssReadability), mTickCount(5), mTickOrigin(0) { } QCPAxisTicker::~QCPAxisTicker() { } /*! Sets which strategy the axis ticker follows when choosing the size of the tick step. For the available strategies, see \ref TickStepStrategy. */ void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy) { mTickStepStrategy = strategy; } /*! Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with the requested number of ticks. Whether the readability has priority over meeting the requested \a count can be specified with \ref setTickStepStrategy. */ void QCPAxisTicker::setTickCount(int count) { if (count > 0) mTickCount = count; else qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count; } /*! Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a concept and doesn't need to be inside the currently visible axis range. By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be {-4, 1, 6, 11, 16,...}. */ void QCPAxisTicker::setTickOrigin(double origin) { mTickOrigin = origin; } /*! This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks), tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks). The ticks are generated for the specified \a range. The generated labels typically follow the specified \a locale, \a formatChar and number \a precision, however this might be different (or even irrelevant) for certain QCPAxisTicker subclasses. The output parameter \a ticks is filled with the generated tick positions in axis coordinates. The output parameters \a subTicks and \a tickLabels are optional (set them to \c nullptr if not needed) and are respectively filled with sub tick coordinates, and tick label strings belonging to \a ticks by index. */ void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector &ticks, QVector *subTicks, QVector *tickLabels) { // generate (major) ticks: double tickStep = getTickStep(range); ticks = createTickVector(tickStep, range); trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more) // generate sub ticks between major ticks: if (subTicks) { if (!ticks.isEmpty()) { *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks); trimTicks(range, *subTicks, false); } else *subTicks = QVector(); } // finally trim also outliers (no further clipping happens in axis drawing): trimTicks(range, ticks, false); // generate labels for visible ticks if requested: if (tickLabels) *tickLabels = createLabelVector(ticks, locale, formatChar, precision); } /*! \internal Takes the entire currently visible axis range and returns a sensible tick step in order to provide readable tick labels as well as a reasonable number of tick counts (see \ref setTickCount, \ref setTickStepStrategy). If a QCPAxisTicker subclass only wants a different tick step behaviour than the default implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper function. */ double QCPAxisTicker::getTickStep(const QCPRange &range) { double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers return cleanMantissa(exactStep); } /*! \internal Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns an appropriate number of sub ticks for that specific tick step. Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections. */ int QCPAxisTicker::getSubTickCount(double tickStep) { int result = 1; // default to 1, if no proper value can be found // separate integer and fractional part of mantissa: double epsilon = 0.01; double intPartf; int intPart; double fracPart = modf(getMantissa(tickStep), &intPartf); intPart = int(intPartf); // handle cases with (almost) integer mantissa: if (fracPart < epsilon || 1.0-fracPart < epsilon) { if (1.0-fracPart < epsilon) ++intPart; switch (intPart) { case 1: result = 4; break; // 1.0 -> 0.2 substep case 2: result = 3; break; // 2.0 -> 0.5 substep case 3: result = 2; break; // 3.0 -> 1.0 substep case 4: result = 3; break; // 4.0 -> 1.0 substep case 5: result = 4; break; // 5.0 -> 1.0 substep case 6: result = 2; break; // 6.0 -> 2.0 substep case 7: result = 6; break; // 7.0 -> 1.0 substep case 8: result = 3; break; // 8.0 -> 2.0 substep case 9: result = 2; break; // 9.0 -> 3.0 substep } } else { // handle cases with significantly fractional mantissa: if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa { switch (intPart) { case 1: result = 2; break; // 1.5 -> 0.5 substep case 2: result = 4; break; // 2.5 -> 0.5 substep case 3: result = 4; break; // 3.5 -> 0.7 substep case 4: result = 2; break; // 4.5 -> 1.5 substep case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on) case 6: result = 4; break; // 6.5 -> 1.3 substep case 7: result = 2; break; // 7.5 -> 2.5 substep case 8: result = 4; break; // 8.5 -> 1.7 substep case 9: result = 4; break; // 9.5 -> 1.9 substep } } // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default } return result; } /*! \internal This method returns the tick label string as it should be printed under the \a tick coordinate. If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a precision. If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will be formatted accordingly using multiplication symbol and superscript during rendering of the label automatically. */ QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) { return locale.toString(tick, formatChar.toLatin1(), precision); } /*! \internal Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a subTickCount sub ticks between each tick pair given in \a ticks. If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to base its result on \a subTickCount or \a ticks. */ QVector QCPAxisTicker::createSubTickVector(int subTickCount, const QVector &ticks) { QVector result; if (subTickCount <= 0 || ticks.size() < 2) return result; result.reserve((ticks.size()-1)*subTickCount); for (int i=1; i QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range) { QVector result; // Generate tick positions according to tickStep: qint64 firstStep = qint64(floor((range.lower-mTickOrigin)/tickStep)); // do not use qFloor here, or we'll lose 64 bit precision qint64 lastStep = qint64(ceil((range.upper-mTickOrigin)/tickStep)); // do not use qCeil here, or we'll lose 64 bit precision int tickcount = int(lastStep-firstStep+1); if (tickcount < 0) tickcount = 0; result.resize(tickcount); for (int i=0; i QCPAxisTicker::createLabelVector(const QVector &ticks, const QLocale &locale, QChar formatChar, int precision) { QVector result; result.reserve(ticks.size()); foreach (double tickCoord, ticks) result.append(getTickLabel(tickCoord, locale, formatChar, precision)); return result; } /*! \internal Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present. The passed \a ticks must be sorted in ascending order. */ void QCPAxisTicker::trimTicks(const QCPRange &range, QVector &ticks, bool keepOneOutlier) const { bool lowFound = false; bool highFound = false; int lowIndex = 0; int highIndex = -1; for (int i=0; i < ticks.size(); ++i) { if (ticks.at(i) >= range.lower) { lowFound = true; lowIndex = i; break; } } for (int i=ticks.size()-1; i >= 0; --i) { if (ticks.at(i) <= range.upper) { highFound = true; highIndex = i; break; } } if (highFound && lowFound) { int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0)); int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex); if (trimFront > 0 || trimBack > 0) ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack); } else // all ticks are either all below or all above the range ticks.clear(); } /*! \internal Returns the coordinate contained in \a candidates which is closest to the provided \a target. This method assumes \a candidates is not empty and sorted in ascending order. */ double QCPAxisTicker::pickClosest(double target, const QVector &candidates) const { if (candidates.size() == 1) return candidates.first(); QVector::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target); if (it == candidates.constEnd()) return *(it-1); else if (it == candidates.constBegin()) return *it; else return target-*(it-1) < *it-target ? *(it-1) : *it; } /*! \internal Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also returns the magnitude of \a input as a power of 10. For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100. */ double QCPAxisTicker::getMantissa(double input, double *magnitude) const { const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0))); if (magnitude) *magnitude = mag; return input/mag; } /*! \internal Returns a number that is close to \a input but has a clean, easier human readable mantissa. How strongly the mantissa is altered, and thus how strong the result deviates from the original \a input, depends on the current tick step strategy (see \ref setTickStepStrategy). */ double QCPAxisTicker::cleanMantissa(double input) const { double magnitude; const double mantissa = getMantissa(input, &magnitude); switch (mTickStepStrategy) { case tssReadability: { return pickClosest(mantissa, QVector() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude; } case tssMeetTickCount: { // this gives effectively a mantissa of 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 10.0 if (mantissa <= 5.0) return int(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5 else return int(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2 } } return input; } /* end of 'src/axis/axisticker.cpp' */ /* including file 'src/axis/axistickerdatetime.cpp' */ /* modified 2021-03-29T02:30:44, size 18829 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisTickerDateTime //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisTickerDateTime \brief Specialized axis ticker for calendar dates and times as axis ticks \image html axisticker-datetime.png This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00 UTC). This is also used for example by QDateTime in the toTime_t()/setTime_t() methods with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime by using QDateTime::fromMSecsSinceEpoch()/1000.0. The static methods \ref dateTimeToKey and \ref keyToDateTime conveniently perform this conversion achieving a precision of one millisecond on all Qt versions. The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat. If a different time spec or time zone shall be used for the tick label appearance, see \ref setDateTimeSpec or \ref setTimeZone, respectively. This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day ticks. For example, if the axis range spans a few years such that there is one tick per year, ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years, will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in the image above: even though the number of days varies month by month, this ticker generates ticks on the same day of each month. If you would like to change the date/time that is used as a (mathematical) starting date for the ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at 9:45 of every year. The ticker can be created and assigned to an axis like this: \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and milliseconds, and are not interested in the intricacies of real calendar dates with months and (leap) years, have a look at QCPAxisTickerTime instead. */ /*! Constructs the ticker and sets reasonable default values. Axis tickers are commonly created managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerDateTime::QCPAxisTickerDateTime() : mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")), mDateTimeSpec(Qt::LocalTime), mDateStrategy(dsNone) { setTickCount(4); } /*! Sets the format in which dates and times are displayed as tick labels. For details about the \a format string, see the documentation of QDateTime::toString(). Typical expressions are
\c dThe day as a number without a leading zero (1 to 31)
\c ddThe day as a number with a leading zero (01 to 31)
\c dddThe abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses the system locale to localize the name, i.e. QLocale::system().
\c ddddThe long localized day name (e.g. 'Monday' to 'Sunday'). Uses the system locale to localize the name, i.e. QLocale::system().
\c MThe month as a number without a leading zero (1 to 12)
\c MMThe month as a number with a leading zero (01 to 12)
\c MMMThe abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses the system locale to localize the name, i.e. QLocale::system().
\c MMMMThe long localized month name (e.g. 'January' to 'December'). Uses the system locale to localize the name, i.e. QLocale::system().
\c yyThe year as a two digit number (00 to 99)
\c yyyyThe year as a four digit number. If the year is negative, a minus sign is prepended, making five characters.
\c hThe hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
\c hhThe hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
\c HThe hour without a leading zero (0 to 23, even with AM/PM display)
\c HHThe hour with a leading zero (00 to 23, even with AM/PM display)
\c mThe minute without a leading zero (0 to 59)
\c mmThe minute with a leading zero (00 to 59)
\c sThe whole second, without any leading zero (0 to 59)
\c ssThe whole second, with a leading zero where applicable (00 to 59)
\c zThe fractional part of the second, to go after a decimal point, without trailing zeroes (0 to 999). Thus "s.z" reports the seconds to full available (millisecond) precision without trailing zeroes.
\c zzzThe fractional part of the second, to millisecond precision, including trailing zeroes where applicable (000 to 999).
\c AP or \c AUse AM/PM display. A/AP will be replaced by an upper-case version of either QLocale::amText() or QLocale::pmText().
\c ap or \c aUse am/pm display. a/ap will be replaced by a lower-case version of either QLocale::amText() or QLocale::pmText().
\c tThe timezone (for example "CEST")
Newlines can be inserted with \c "\n", literal strings (even when containing above expressions) by encapsulating them using single-quotes. A literal single quote can be generated by using two consecutive single quotes in the format. \see setDateTimeSpec, setTimeZone */ void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format) { mDateTimeFormat = format; } /*! Sets the time spec that is used for creating the tick labels from corresponding dates/times. The default value of QDateTime objects (and also QCPAxisTickerDateTime) is Qt::LocalTime. However, if the displayed tick labels shall be given in UTC, set \a spec to Qt::UTC. Tick labels corresponding to other time zones can be achieved with \ref setTimeZone (which sets \a spec to \c Qt::TimeZone internally). Note that if \a spec is afterwards set to not be \c Qt::TimeZone again, the \ref setTimeZone setting will be ignored accordingly. \see setDateTimeFormat, setTimeZone */ void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec) { mDateTimeSpec = spec; } # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) /*! Sets the time zone that is used for creating the tick labels from corresponding dates/times. The time spec (\ref setDateTimeSpec) is set to \c Qt::TimeZone. \see setDateTimeFormat, setTimeZone */ void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone) { mTimeZone = zone; mDateTimeSpec = Qt::TimeZone; } #endif /*! Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970, 00:00 UTC). For the date time ticker it might be more intuitive to use the overload which directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin). This is useful to define the month/day/time recurring at greater tick interval steps. For example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick per year, the ticks will end up on 15. July at 9:45 of every year. */ void QCPAxisTickerDateTime::setTickOrigin(double origin) { QCPAxisTicker::setTickOrigin(origin); } /*! Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin. This is useful to define the month/day/time recurring at greater tick interval steps. For example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick per year, the ticks will end up on 15. July at 9:45 of every year. */ void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin) { setTickOrigin(dateTimeToKey(origin)); } /*! \internal Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly, monthly, bi-monthly, etc. Note that this tick step isn't used exactly when generating the tick vector in \ref createTickVector, but only as a guiding value requiring some correction for each individual tick interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day in the month to the last day in the previous month from tick to tick, due to the non-uniform length of months. The same problem arises with leap years. \seebaseclassmethod */ double QCPAxisTickerDateTime::getTickStep(const QCPRange &range) { double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers mDateStrategy = dsNone; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds { result = cleanMantissa(result); } else if (result < 86400*30.4375*12) // below a year { result = pickClosest(result, QVector() << 1 << 2.5 << 5 << 10 << 15 << 30 << 60 << 2.5*60 << 5*60 << 10*60 << 15*60 << 30*60 << 60*60 // second, minute, hour range << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range << 86400*2 << 86400*5 << 86400*7 << 86400*14 << 86400*30.4375 << 86400*30.4375*2 << 86400*30.4375*3 << 86400*30.4375*6 << 86400*30.4375*12); // day, week, month range (avg. days per month includes leap years) if (result > 86400*30.4375-1) // month tick intervals or larger mDateStrategy = dsUniformDayInMonth; else if (result > 3600*24-1) // day tick intervals or larger mDateStrategy = dsUniformTimeInDay; } else // more than a year, go back to normal clean mantissa algorithm but in units of years { const double secondsPerYear = 86400*30.4375*12; // average including leap years result = cleanMantissa(result/secondsPerYear)*secondsPerYear; mDateStrategy = dsUniformDayInMonth; } return result; } /*! \internal Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly, monthly, bi-monthly, etc. \seebaseclassmethod */ int QCPAxisTickerDateTime::getSubTickCount(double tickStep) { int result = QCPAxisTicker::getSubTickCount(tickStep); switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep) { case 5*60: result = 4; break; case 10*60: result = 1; break; case 15*60: result = 2; break; case 30*60: result = 1; break; case 60*60: result = 3; break; case 3600*2: result = 3; break; case 3600*3: result = 2; break; case 3600*6: result = 1; break; case 3600*12: result = 3; break; case 3600*24: result = 3; break; case 86400*2: result = 1; break; case 86400*5: result = 4; break; case 86400*7: result = 6; break; case 86400*14: result = 1; break; case int(86400*30.4375+0.5): result = 3; break; case int(86400*30.4375*2+0.5): result = 1; break; case int(86400*30.4375*3+0.5): result = 2; break; case int(86400*30.4375*6+0.5): result = 5; break; case int(86400*30.4375*12+0.5): result = 3; break; } return result; } /*! \internal Generates a date/time tick label for tick coordinate \a tick, based on the currently set format (\ref setDateTimeFormat), time spec (\ref setDateTimeSpec), and possibly time zone (\ref setTimeZone). \seebaseclassmethod */ QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) { Q_UNUSED(precision) Q_UNUSED(formatChar) # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) if (mDateTimeSpec == Qt::TimeZone) return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat); else return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat); # else return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat); # endif } /*! \internal Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month. \seebaseclassmethod */ QVector QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range) { QVector result = QCPAxisTicker::createTickVector(tickStep, range); if (!result.isEmpty()) { if (mDateStrategy == dsUniformTimeInDay) { QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible QDateTime tickDateTime; for (int i=0; i 15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day tickDateTime = tickDateTime.addMonths(-1); tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay)); result[i] = dateTimeToKey(tickDateTime); } } } return result; } /*! A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a QDateTime object. This can be used to turn axis coordinates to actual QDateTimes. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6) \see dateTimeToKey */ QDateTime QCPAxisTickerDateTime::keyToDateTime(double key) { # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000); # else return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0)); # endif } /*! \overload A convenience method which turns a QDateTime object into a double value that corresponds to seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by QCPAxisTickerDateTime. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6) \see keyToDateTime */ double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime &dateTime) { # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) return dateTime.toTime_t()+dateTime.time().msec()/1000.0; # else return dateTime.toMSecsSinceEpoch()/1000.0; # endif } /*! \overload A convenience method which turns a QDate object into a double value that corresponds to seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by QCPAxisTickerDateTime. The returned value will be the start of the passed day of \a date, interpreted in the given \a timeSpec. \see keyToDateTime */ double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec) { # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) return QDateTime(date, QTime(0, 0), timeSpec).toTime_t(); # elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0) return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0; # else return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0; # endif } /* end of 'src/axis/axistickerdatetime.cpp' */ /* including file 'src/axis/axistickertime.cpp' */ /* modified 2021-03-29T02:30:44, size 11745 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisTickerTime //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisTickerTime \brief Specialized axis ticker for time spans in units of milliseconds to days \image html axisticker-time.png This QCPAxisTicker subclass generates ticks that corresponds to time intervals. The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date and time. The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the largest available unit in the format specified with \ref setTimeFormat, any time spans above will be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis zero will carry a leading minus sign. The ticker can be created and assigned to an axis like this: \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation Here is an example of a time axis providing time information in days, hours and minutes. Due to the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker decided to use tick steps of 12 hours: \image html axisticker-time2.png The format string for this example is \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2 \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime instead. */ /*! Constructs the ticker and sets reasonable default values. Axis tickers are commonly created managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerTime::QCPAxisTickerTime() : mTimeFormat(QLatin1String("%h:%m:%s")), mSmallestUnit(tuSeconds), mBiggestUnit(tuHours) { setTickCount(4); mFieldWidth[tuMilliseconds] = 3; mFieldWidth[tuSeconds] = 2; mFieldWidth[tuMinutes] = 2; mFieldWidth[tuHours] = 2; mFieldWidth[tuDays] = 1; mFormatPattern[tuMilliseconds] = QLatin1String("%z"); mFormatPattern[tuSeconds] = QLatin1String("%s"); mFormatPattern[tuMinutes] = QLatin1String("%m"); mFormatPattern[tuHours] = QLatin1String("%h"); mFormatPattern[tuDays] = QLatin1String("%d"); } /*! Sets the format that will be used to display time in the tick labels. The available patterns are: - %%z for milliseconds - %%s for seconds - %%m for minutes - %%h for hours - %%d for days The field width (zero padding) can be controlled for each unit with \ref setFieldWidth. The largest unit that appears in \a format will carry all the remaining time of a certain tick coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the largest unit it might become larger than 59 in order to consume larger time values. If on the other hand %%h is available, the minutes will wrap around to zero after 59 and the time will carry to the hour digit. */ void QCPAxisTickerTime::setTimeFormat(const QString &format) { mTimeFormat = format; // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59) mSmallestUnit = tuMilliseconds; mBiggestUnit = tuMilliseconds; bool hasSmallest = false; for (int i = tuMilliseconds; i <= tuDays; ++i) { TimeUnit unit = static_cast(i); if (mTimeFormat.contains(mFormatPattern.value(unit))) { if (!hasSmallest) { mSmallestUnit = unit; hasSmallest = true; } mBiggestUnit = unit; } } } /*! Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick label. If the number for the specific unit is shorter than \a width, it will be padded with an according number of zeros to the left in order to reach the field width. \see setTimeFormat */ void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width) { mFieldWidth[unit] = qMax(width, 1); } /*! \internal Returns the tick step appropriate for time displays, depending on the provided \a range and the smallest available time unit in the current format (\ref setTimeFormat). For example if the unit of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes) that require sub-minute precision to be displayed correctly. \seebaseclassmethod */ double QCPAxisTickerTime::getTickStep(const QCPRange &range) { double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds { if (mSmallestUnit == tuMilliseconds) result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond else // have no milliseconds available in format, so stick with 1 second tickstep result = 1.0; } else if (result < 3600*24) // below a day { // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run QVector availableSteps; // seconds range: if (mSmallestUnit <= tuSeconds) availableSteps << 1; if (mSmallestUnit == tuMilliseconds) availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it else if (mSmallestUnit == tuSeconds) availableSteps << 2; if (mSmallestUnit <= tuSeconds) availableSteps << 5 << 10 << 15 << 30; // minutes range: if (mSmallestUnit <= tuMinutes) availableSteps << 1*60; if (mSmallestUnit <= tuSeconds) availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it else if (mSmallestUnit == tuMinutes) availableSteps << 2*60; if (mSmallestUnit <= tuMinutes) availableSteps << 5*60 << 10*60 << 15*60 << 30*60; // hours range: if (mSmallestUnit <= tuHours) availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600; // pick available step that is most appropriate to approximate ideal step: result = pickClosest(result, availableSteps); } else // more than a day, go back to normal clean mantissa algorithm but in units of days { const double secondsPerDay = 3600*24; result = cleanMantissa(result/secondsPerDay)*secondsPerDay; } return result; } /*! \internal Returns the sub tick count appropriate for the provided \a tickStep and time displays. \seebaseclassmethod */ int QCPAxisTickerTime::getSubTickCount(double tickStep) { int result = QCPAxisTicker::getSubTickCount(tickStep); switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep) { case 5*60: result = 4; break; case 10*60: result = 1; break; case 15*60: result = 2; break; case 30*60: result = 1; break; case 60*60: result = 3; break; case 3600*2: result = 3; break; case 3600*3: result = 2; break; case 3600*6: result = 1; break; case 3600*12: result = 3; break; case 3600*24: result = 3; break; } return result; } /*! \internal Returns the tick label corresponding to the provided \a tick and the configured format and field widths (\ref setTimeFormat, \ref setFieldWidth). \seebaseclassmethod */ QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) { Q_UNUSED(precision) Q_UNUSED(formatChar) Q_UNUSED(locale) bool negative = tick < 0; if (negative) tick *= -1; double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59) double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time restValues[tuMilliseconds] = tick*1000; values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000; values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60; values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60; values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24; // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time) QString result = mTimeFormat; for (int i = mSmallestUnit; i <= mBiggestUnit; ++i) { TimeUnit iUnit = static_cast(i); replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit])); } if (negative) result.prepend(QLatin1Char('-')); return result; } /*! \internal Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified \a value, using the field width as specified with \ref setFieldWidth for the \a unit. */ void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const { QString valueStr = QString::number(value); while (valueStr.size() < mFieldWidth.value(unit)) valueStr.prepend(QLatin1Char('0')); text.replace(mFormatPattern.value(unit), valueStr); } /* end of 'src/axis/axistickertime.cpp' */ /* including file 'src/axis/axistickerfixed.cpp' */ /* modified 2021-03-29T02:30:44, size 5575 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisTickerFixed //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisTickerFixed \brief Specialized axis ticker with a fixed tick step \image html axisticker-fixed.png This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It is also possible to allow integer multiples and integer powers of the specified tick step with \ref setScaleStrategy. A typical application of this ticker is to make an axis only display integers, by setting the tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples. Another case is when a certain number has a special meaning and axis ticks should only appear at multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi because despite the name it is not limited to only pi symbols/values. The ticker can be created and assigned to an axis like this: \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation */ /*! Constructs the ticker and sets reasonable default values. Axis tickers are commonly created managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerFixed::QCPAxisTickerFixed() : mTickStep(1.0), mScaleStrategy(ssNone) { } /*! Sets the fixed tick interval to \a step. The axis ticker will only use this tick step when generating axis ticks. This might cause a very high tick density and overlapping labels if the axis range is zoomed out. Using \ref setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref setTickCount). */ void QCPAxisTickerFixed::setTickStep(double step) { if (step > 0) mTickStep = step; else qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step; } /*! Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether modifications may be applied to it before calculating the finally used tick step, such as permitting multiples or powers. See \ref ScaleStrategy for details. The default strategy is \ref ssNone, which means the tick step is absolutely fixed. */ void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy) { mScaleStrategy = strategy; } /*! \internal Determines the actually used tick step from the specified tick step and scale strategy (\ref setTickStep, \ref setScaleStrategy). This method either returns the specified tick step exactly, or, if the scale strategy is not \ref ssNone, a modification of it to allow varying the number of ticks in the current axis range. \seebaseclassmethod */ double QCPAxisTickerFixed::getTickStep(const QCPRange &range) { switch (mScaleStrategy) { case ssNone: { return mTickStep; } case ssMultiples: { double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers if (exactStep < mTickStep) return mTickStep; else return qint64(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep; } case ssPowers: { double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers return qPow(mTickStep, int(qLn(exactStep)/qLn(mTickStep)+0.5)); } } return mTickStep; } /* end of 'src/axis/axistickerfixed.cpp' */ /* including file 'src/axis/axistickertext.cpp' */ /* modified 2021-03-29T02:30:44, size 8742 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisTickerText //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisTickerText \brief Specialized axis ticker which allows arbitrary labels at specified coordinates \image html axisticker-text.png This QCPAxisTicker subclass generates ticks which can be directly specified by the user as coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks and modify the tick/label data there. This is useful for cases where the axis represents categories rather than numerical values. If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on the axis range), it is a sign that you should probably create an own ticker by subclassing QCPAxisTicker, instead of using this one. The ticker can be created and assigned to an axis like this: \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation */ /* start of documentation of inline functions */ /*! \fn QMap &QCPAxisTickerText::ticks() Returns a non-const reference to the internal map which stores the tick coordinates and their labels. You can access the map directly in order to add, remove or manipulate ticks, as an alternative to using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick. */ /* end of documentation of inline functions */ /*! Constructs the ticker and sets reasonable default values. Axis tickers are commonly created managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerText::QCPAxisTickerText() : mSubTickCount(0) { } /*! \overload Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis coordinate, and the map value is the string that will appear as tick label. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks getter. \see addTicks, addTick, clear */ void QCPAxisTickerText::setTicks(const QMap &ticks) { mTicks = ticks; } /*! \overload Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis coordinates, and the entries of \a labels are the respective strings that will appear as tick labels. \see addTicks, addTick, clear */ void QCPAxisTickerText::setTicks(const QVector &positions, const QVector &labels) { clear(); addTicks(positions, labels); } /*! Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this method. */ void QCPAxisTickerText::setSubTickCount(int subTicks) { if (subTicks >= 0) mSubTickCount = subTicks; else qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks; } /*! Clears all ticks. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks getter. \see setTicks, addTicks, addTick */ void QCPAxisTickerText::clear() { mTicks.clear(); } /*! Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a label. \see addTicks, setTicks, clear */ void QCPAxisTickerText::addTick(double position, const QString &label) { mTicks.insert(position, label); } /*! \overload Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to the axis coordinate, and the map value is the string that will appear as tick label. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks getter. \see addTick, setTicks, clear */ void QCPAxisTickerText::addTicks(const QMap &ticks) { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) mTicks.unite(ticks); #else mTicks.insert(ticks); #endif } /*! \overload Adds the provided ticks to the ones already existing. The entries of \a positions correspond to the axis coordinates, and the entries of \a labels are the respective strings that will appear as tick labels. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks getter. \see addTick, setTicks, clear */ void QCPAxisTickerText::addTicks(const QVector &positions, const QVector &labels) { if (positions.size() != labels.size()) qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size(); int n = qMin(positions.size(), labels.size()); for (int i=0; i QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range) { Q_UNUSED(tickStep) QVector result; if (mTicks.isEmpty()) return result; QMap::const_iterator start = mTicks.lowerBound(range.lower); QMap::const_iterator end = mTicks.upperBound(range.upper); // this method should try to give one tick outside of range so proper subticks can be generated: if (start != mTicks.constBegin()) --start; if (end != mTicks.constEnd()) ++end; for (QMap::const_iterator it = start; it != end; ++it) result.append(it.key()); return result; } /* end of 'src/axis/axistickertext.cpp' */ /* including file 'src/axis/axistickerpi.cpp' */ /* modified 2021-03-29T02:30:44, size 11177 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisTickerPi //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisTickerPi \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi \image html axisticker-pi.png This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic constant with a numerical value specified with \ref setPiValue and an appearance in the tick labels specified with \ref setPiSymbol. Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the tick label can be configured with \ref setFractionStyle. The ticker can be created and assigned to an axis like this: \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation */ /*! Constructs the ticker and sets reasonable default values. Axis tickers are commonly created managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerPi::QCPAxisTickerPi() : mPiSymbol(QLatin1String(" ")+QChar(0x03C0)), mPiValue(M_PI), mPeriodicity(0), mFractionStyle(fsUnicodeFractions), mPiTickStep(0) { setTickCount(4); } /*! Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick label. If a space shall appear between the number and the symbol, make sure the space is contained in \a symbol. */ void QCPAxisTickerPi::setPiSymbol(QString symbol) { mPiSymbol = symbol; } /*! Sets the numerical value that the symbolic constant has. This will be used to place the appropriate fractions of the symbol at the respective axis coordinates. */ void QCPAxisTickerPi::setPiValue(double pi) { mPiValue = pi; } /*! Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the symbolic constant. To disable periodicity, set \a multiplesOfPi to zero. For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two. */ void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi) { mPeriodicity = qAbs(multiplesOfPi); } /*! Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick labels. See \ref FractionStyle for the various options. */ void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style) { mFractionStyle = style; } /*! \internal Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence the numerical/fractional part preceding the symbolic constant is made to have a readable mantissa. \seebaseclassmethod */ double QCPAxisTickerPi::getTickStep(const QCPRange &range) { mPiTickStep = range.size()/mPiValue/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers mPiTickStep = cleanMantissa(mPiTickStep); return mPiTickStep*mPiValue; } /*! \internal Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant reasonably, and not the total tick coordinate. \seebaseclassmethod */ int QCPAxisTickerPi::getSubTickCount(double tickStep) { return QCPAxisTicker::getSubTickCount(tickStep/mPiValue); } /*! \internal Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The formatting of the fraction is done according to the specified \ref setFractionStyle. The appended symbol is specified with \ref setPiSymbol. \seebaseclassmethod */ QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) { double tickInPis = tick/mPiValue; if (mPeriodicity > 0) tickInPis = fmod(tickInPis, mPeriodicity); if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50) { // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above int denominator = 1000; int numerator = qRound(tickInPis*denominator); simplifyFraction(numerator, denominator); if (qAbs(numerator) == 1 && denominator == 1) return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed(); else if (numerator == 0) return QLatin1String("0"); else return fractionToString(numerator, denominator) + mPiSymbol; } else { if (qFuzzyIsNull(tickInPis)) return QLatin1String("0"); else if (qFuzzyCompare(qAbs(tickInPis), 1.0)) return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed(); else return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol; } } /*! \internal Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure the fraction is in irreducible form, i.e. numerator and denominator don't share any common factors which could be cancelled. */ void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const { if (numerator == 0 || denominator == 0) return; int num = numerator; int denom = denominator; while (denom != 0) // euclidean gcd algorithm { int oldDenom = denom; denom = num % denom; num = oldDenom; } // num is now gcd of numerator and denominator numerator /= num; denominator /= num; } /*! \internal Takes the fraction given by \a numerator and \a denominator and returns a string representation. The result depends on the configured fraction style (\ref setFractionStyle). This method is used to format the numerical/fractional part when generating tick labels. It simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out any integer parts of the fraction (e.g. "10/4" becomes "2 1/2"). */ QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const { if (denominator == 0) { qDebug() << Q_FUNC_INFO << "called with zero denominator"; return QString(); } if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function { qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal"; return QString::number(numerator/double(denominator)); // failsafe } int sign = numerator*denominator < 0 ? -1 : 1; numerator = qAbs(numerator); denominator = qAbs(denominator); if (denominator == 1) { return QString::number(sign*numerator); } else { int integerPart = numerator/denominator; int remainder = numerator%denominator; if (remainder == 0) { return QString::number(sign*integerPart); } else { if (mFractionStyle == fsAsciiFractions) { return QString(QLatin1String("%1%2%3/%4")) .arg(sign == -1 ? QLatin1String("-") : QLatin1String("")) .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(QLatin1String(""))) .arg(remainder) .arg(denominator); } else if (mFractionStyle == fsUnicodeFractions) { return QString(QLatin1String("%1%2%3")) .arg(sign == -1 ? QLatin1String("-") : QLatin1String("")) .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String("")) .arg(unicodeFraction(remainder, denominator)); } } } return QString(); } /*! \internal Returns the unicode string representation of the fraction given by \a numerator and \a denominator. This is the representation used in \ref fractionToString when the fraction style (\ref setFractionStyle) is \ref fsUnicodeFractions. This method doesn't use the single-character common fractions but builds each fraction from a superscript unicode number, the unicode fraction character, and a subscript unicode number. */ QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const { return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator); } /*! \internal Returns the unicode string representing \a number as superscript. This is used to build unicode fractions in \ref unicodeFraction. */ QString QCPAxisTickerPi::unicodeSuperscript(int number) const { if (number == 0) return QString(QChar(0x2070)); QString result; while (number > 0) { const int digit = number%10; switch (digit) { case 1: { result.prepend(QChar(0x00B9)); break; } case 2: { result.prepend(QChar(0x00B2)); break; } case 3: { result.prepend(QChar(0x00B3)); break; } default: { result.prepend(QChar(0x2070+digit)); break; } } number /= 10; } return result; } /*! \internal Returns the unicode string representing \a number as subscript. This is used to build unicode fractions in \ref unicodeFraction. */ QString QCPAxisTickerPi::unicodeSubscript(int number) const { if (number == 0) return QString(QChar(0x2080)); QString result; while (number > 0) { result.prepend(QChar(0x2080+number%10)); number /= 10; } return result; } /* end of 'src/axis/axistickerpi.cpp' */ /* including file 'src/axis/axistickerlog.cpp' */ /* modified 2021-03-29T02:30:44, size 7890 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisTickerLog //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisTickerLog \brief Specialized axis ticker suited for logarithmic axes \image html axisticker-log.png This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase). Especially in the case of a log base equal to 10 (the default), it might be desirable to have tick labels in the form of powers of ten without mantissa display. To achieve this, set the number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal powers, so a format string of "eb". This will result in the following axis tick labels: \image html axisticker-log-powers.png The ticker can be created and assigned to an axis like this: \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step, corresponding to one multiplication by the log base. If the user zooms in further than that, no new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this situation, this ticker falls back to regular tick generation if the axis range would be covered by too few logarithmically placed ticks. */ /*! Constructs the ticker and sets reasonable default values. Axis tickers are commonly created managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerLog::QCPAxisTickerLog() : mLogBase(10.0), mSubTickCount(8), // generates 10 intervals mLogBaseLnInv(1.0/qLn(mLogBase)) { } /*! Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer powers of \a base. */ void QCPAxisTickerLog::setLogBase(double base) { if (base > 0) { mLogBase = base; mLogBaseLnInv = 1.0/qLn(mLogBase); } else qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base; } /*! Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced linearly to provide a better visual guide, so the sub tick density increases toward the higher tick. Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks, namely at 20, 30, 40, 50, 60, 70, 80 and 90. */ void QCPAxisTickerLog::setSubTickCount(int subTicks) { if (subTicks >= 0) mSubTickCount = subTicks; else qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks; } /*! \internal Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no automatic sub tick count calculation necessary. \seebaseclassmethod */ int QCPAxisTickerLog::getSubTickCount(double tickStep) { Q_UNUSED(tickStep) return mSubTickCount; } /*! \internal Creates ticks with a spacing given by the logarithm base and an increasing integer power in the provided \a range. The step in which the power increases tick by tick is chosen in order to keep the total number of ticks as close as possible to the tick count (\ref setTickCount). The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when zoomed in very far such that not enough logarithmically placed ticks would be visible, this function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep. \seebaseclassmethod */ QVector QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range) { QVector result; if (range.lower > 0 && range.upper > 0) // positive range { const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv; if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation return QCPAxisTicker::createTickVector(tickStep, range); const double exactPowerStep = baseTickCount/double(mTickCount+1e-10); const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1)); double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase))); result.append(currentTick); while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentTick *= newLogBase; result.append(currentTick); } } else if (range.lower < 0 && range.upper < 0) // negative range { const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv; if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation return QCPAxisTicker::createTickVector(tickStep, range); const double exactPowerStep = baseTickCount/double(mTickCount+1e-10); const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1)); double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase))); result.append(currentTick); while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentTick /= newLogBase; result.append(currentTick); } } else // invalid range for logarithmic scale, because lower and upper have different sign { qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper; } return result; } /* end of 'src/axis/axistickerlog.cpp' */ /* including file 'src/axis/axis.cpp' */ /* modified 2021-03-29T02:30:44, size 99883 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGrid \brief Responsible for drawing the grid of a QCPAxis. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. The axis and grid drawing was split into two classes to allow them to be placed on different layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid in the background and the axes in the foreground, and any plottables/items in between. This described situation is the default setup, see the QCPLayer documentation. */ /*! Creates a QCPGrid instance and sets default values. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. */ QCPGrid::QCPGrid(QCPAxis *parentAxis) : QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), mSubGridVisible{}, mAntialiasedSubGrid{}, mAntialiasedZeroLine{}, mParentAxis(parentAxis) { // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called setParent(parentAxis); setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); setSubGridVisible(false); setAntialiased(false); setAntialiasedSubGrid(false); setAntialiasedZeroLine(false); } /*! Sets whether grid lines at sub tick marks are drawn. \see setSubGridPen */ void QCPGrid::setSubGridVisible(bool visible) { mSubGridVisible = visible; } /*! Sets whether sub grid lines are drawn antialiased. */ void QCPGrid::setAntialiasedSubGrid(bool enabled) { mAntialiasedSubGrid = enabled; } /*! Sets whether zero lines are drawn antialiased. */ void QCPGrid::setAntialiasedZeroLine(bool enabled) { mAntialiasedZeroLine = enabled; } /*! Sets the pen with which (major) grid lines are drawn. */ void QCPGrid::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen with which sub grid lines are drawn. */ void QCPGrid::setSubGridPen(const QPen &pen) { mSubGridPen = pen; } /*! Sets the pen with which zero lines are drawn. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. */ void QCPGrid::setZeroLinePen(const QPen &pen) { mZeroLinePen = pen; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPGrid::draw(QCPPainter *painter) { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } if (mParentAxis->subTicks() && mSubGridVisible) drawSubGridLines(painter); drawGridLines(painter); } /*! \internal Draws the main grid lines and possibly a zero line with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } const int tickCount = mParentAxis->mTickVector.size(); double t; // helper variable, result of coordinate-to-pixel transforms if (mParentAxis->orientation() == Qt::Horizontal) { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero for (int i=0; imTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=0; icoordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero for (int i=0; imTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=0; icoordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } /*! \internal Draws the sub grid lines with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawSubGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); double t; // helper variable, result of coordinate-to-pixel transforms painter->setPen(mSubGridPen); if (mParentAxis->orientation() == Qt::Horizontal) { foreach (double tickCoord, mParentAxis->mSubTickVector) { t = mParentAxis->coordToPixel(tickCoord); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { foreach (double tickCoord, mParentAxis->mSubTickVector) { t = mParentAxis->coordToPixel(tickCoord); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxis //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxis \brief Manages a single axis inside a QCustomPlot. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and QCustomPlot::yAxis2 (right). Axes are always part of an axis rect, see QCPAxisRect. \image html AxisNamesOverview.png
Naming convention of axis parts
\n \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line on the left represents the QCustomPlot widget border.
Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the documentation of QCPAxisTicker. */ /* start of documentation of inline functions */ /*! \fn Qt::Orientation QCPAxis::orientation() const Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced from the axis type (left, top, right or bottom). \see orientation(AxisType type), pixelOrientation */ /*! \fn QCPGrid *QCPAxis::grid() const Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the grid is displayed. */ /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) Returns the orientation of the specified axis type \see orientation(), pixelOrientation */ /*! \fn int QCPAxis::pixelOrientation() const Returns which direction points towards higher coordinate values/keys, in pixel space. This method returns either 1 or -1. If it returns 1, then going in the positive direction along the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates. On the other hand, if this method returns -1, going to smaller pixel values corresponds to going from lower to higher axis coordinates. For example, this is useful to easily shift axis coordinates by a certain amount given in pixels, without having to care about reversed or vertically aligned axes: \code double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation()); \endcode \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey. */ /*! \fn QSharedPointer QCPAxis::ticker() const Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is responsible for generating the tick positions and tick labels of this axis. You can access the \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count (\ref QCPAxisTicker::setTickCount). You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see the documentation there. A new axis ticker can be set with \ref setTicker. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis ticker simply by passing the same shared pointer to multiple axes. \see setTicker */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange) This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following slot would limit the x axis to ranges between 0 and 10: \code customPlot->xAxis->setRange(newRange.bounded(0, 10)) \endcode */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ /* end of documentation of signals */ /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : QCPLayerable(parent->parentPlot(), QString(), parent), // axis base: mAxisType(type), mAxisRect(parent), mPadding(5), mOrientation(orientation(type)), mSelectableParts(spAxis | spTickLabels | spAxisLabel), mSelectedParts(spNone), mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedBasePen(QPen(Qt::blue, 2)), // axis label: mLabel(), mLabelFont(mParentPlot->font()), mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), mLabelColor(Qt::black), mSelectedLabelColor(Qt::blue), // tick labels: mTickLabels(true), mTickLabelFont(mParentPlot->font()), mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), mTickLabelColor(Qt::black), mSelectedTickLabelColor(Qt::blue), mNumberPrecision(6), mNumberFormatChar('g'), mNumberBeautifulPowers(true), // ticks and subticks: mTicks(true), mSubTicks(true), mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedTickPen(QPen(Qt::blue, 2)), mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedSubTickPen(QPen(Qt::blue, 2)), // scale and range: mRange(0, 5), mRangeReversed(false), mScaleType(stLinear), // internal members: mGrid(new QCPGrid(this)), mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), mTicker(new QCPAxisTicker), mCachedMarginValid(false), mCachedMargin(0), mDragging(false) { setParent(parent); mGrid->setVisible(false); setAntialiased(false); setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again if (type == atTop) { setTickLabelPadding(3); setLabelPadding(6); } else if (type == atRight) { setTickLabelPadding(7); setLabelPadding(12); } else if (type == atBottom) { setTickLabelPadding(3); setLabelPadding(3); } else if (type == atLeft) { setTickLabelPadding(5); setLabelPadding(10); } } QCPAxis::~QCPAxis() { delete mAxisPainter; delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order } /* No documentation as it is a property getter */ int QCPAxis::tickLabelPadding() const { return mAxisPainter->tickLabelPadding; } /* No documentation as it is a property getter */ double QCPAxis::tickLabelRotation() const { return mAxisPainter->tickLabelRotation; } /* No documentation as it is a property getter */ QCPAxis::LabelSide QCPAxis::tickLabelSide() const { return mAxisPainter->tickLabelSide; } /* No documentation as it is a property getter */ QString QCPAxis::numberFormat() const { QString result; result.append(mNumberFormatChar); if (mNumberBeautifulPowers) { result.append(QLatin1Char('b')); if (mAxisPainter->numberMultiplyCross) result.append(QLatin1Char('c')); } return result; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthIn() const { return mAxisPainter->tickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthOut() const { return mAxisPainter->tickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthIn() const { return mAxisPainter->subTickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthOut() const { return mAxisPainter->subTickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::labelPadding() const { return mAxisPainter->labelPadding; } /* No documentation as it is a property getter */ int QCPAxis::offset() const { return mAxisPainter->offset; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::lowerEnding() const { return mAxisPainter->lowerEnding; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::upperEnding() const { return mAxisPainter->upperEnding; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the axis ticker to an instance of \ref QCPAxisTickerLog : \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. \ref setNumberPrecision */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { if (mScaleType != type) { mScaleType = type; if (mScaleType == stLogarithmic) setRange(mRange.sanitizedForLogScale()); mCachedMarginValid = false; emit scaleTypeChanged(mScaleType); } } /*! Sets the range of the axis. This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. To invert the direction of an axis, use \ref setRangeReversed. */ void QCPAxis::setRange(const QCPRange &range) { if (range.lower == mRange.lower && range.upper == mRange.upper) return; if (!QCPRange::validRange(range)) return; QCPRange oldRange = mRange; if (mScaleType == stLogarithmic) { mRange = range.sanitizedForLogScale(); } else { mRange = range.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPAxis::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part, independent of the \ref setSelectableParts setting. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPAxis::setSelectedParts(const SelectableParts &selected) { if (mSelectedParts != selected) { mSelectedParts = selected; emit selectionChanged(mSelectedParts); } } /*! \overload Sets the lower and upper bound of the axis range. To invert the direction of an axis, use \ref setRangeReversed. There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPAxis::setRange(double lower, double upper) { if (lower == mRange.lower && upper == mRange.upper) return; if (!QCPRange::validRange(lower, upper)) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! \overload Sets the range of the axis. The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, or center of the range to be aligned with \a position. Any other values of \a alignment will default to Qt::AlignCenter. */ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) { if (alignment == Qt::AlignLeft) setRange(position, position+size); else if (alignment == Qt::AlignRight) setRange(position-size, position); else // alignment == Qt::AlignCenter setRange(position-size/2.0, position+size/2.0); } /*! Sets the lower bound of the axis range. The upper bound is not changed. \see setRange */ void QCPAxis::setRangeLower(double lower) { if (mRange.lower == lower) return; QCPRange oldRange = mRange; mRange.lower = lower; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets the upper bound of the axis range. The lower bound is not changed. \see setRange */ void QCPAxis::setRangeUpper(double upper) { if (mRange.upper == upper) return; QCPRange oldRange = mRange; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the direction of increasing values is inverted. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part of the \ref setRange interface will still reference the mathematically smaller number than the \a upper part. */ void QCPAxis::setRangeReversed(bool reversed) { mRangeReversed = reversed; } /*! The axis ticker is responsible for generating the tick positions and tick labels. See the documentation of QCPAxisTicker for details on how to work with axis tickers. You can change the tick positioning/labeling behaviour of this axis by setting a different QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis ticker, access it via \ref ticker. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis ticker simply by passing the same shared pointer to multiple axes. \see ticker */ void QCPAxis::setTicker(QSharedPointer ticker) { if (ticker) mTicker = ticker; else qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker"; // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector } /*! Sets whether tick marks are displayed. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve that, see \ref setTickLabels. \see setSubTicks */ void QCPAxis::setTicks(bool show) { if (mTicks != show) { mTicks = show; mCachedMarginValid = false; } } /*! Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. */ void QCPAxis::setTickLabels(bool show) { if (mTickLabels != show) { mTickLabels = show; mCachedMarginValid = false; if (!mTickLabels) mTickVectorLabels.clear(); } } /*! Sets the distance between the axis base line (including any outward ticks) and the tick labels. \see setLabelPadding, setPadding */ void QCPAxis::setTickLabelPadding(int padding) { if (mAxisPainter->tickLabelPadding != padding) { mAxisPainter->tickLabelPadding = padding; mCachedMarginValid = false; } } /*! Sets the font of the tick labels. \see setTickLabels, setTickLabelColor */ void QCPAxis::setTickLabelFont(const QFont &font) { if (font != mTickLabelFont) { mTickLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the tick labels. \see setTickLabels, setTickLabelFont */ void QCPAxis::setTickLabelColor(const QColor &color) { mTickLabelColor = color; } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPAxis::setTickLabelRotation(double degrees) { if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) { mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); mCachedMarginValid = false; } } /*! Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels appear on the inside are additionally clipped to the axis rect. */ void QCPAxis::setTickLabelSide(LabelSide side) { mAxisPainter->tickLabelSide = side; mCachedMarginValid = false; } /*! Sets the number format for the numbers in tick labels. This \a formatCode is an extended version of the format code used e.g. by QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" section in the detailed description of the QString class. \a formatCode is a string of one, two or three characters. The first character is identical to the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, whichever is shorter. For the 'e', 'E', and 'f' formats, the precision set by \ref setNumberPrecision represents the number of digits after the decimal point. For the 'g' and 'G' formats, the precision represents the maximum number of significant digits, trailing zeroes are omitted. The second and third characters are optional and specific to QCustomPlot:\n If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. Examples for \a formatCode: \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, normal scientific format is used \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with beautifully typeset decimal powers and a dot as multiplication sign \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as multiplication sign \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal powers. Format code will be reduced to 'f'. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format code will not be changed. */ void QCPAxis::setNumberFormat(const QString &formatCode) { if (formatCode.isEmpty()) { qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; return; } mCachedMarginValid = false; // interpret first char as number format char: QString allowedFormatChars(QLatin1String("eEfgG")); if (allowedFormatChars.contains(formatCode.at(0))) { mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } if (formatCode.length() < 2) { mNumberBeautifulPowers = false; mAxisPainter->numberMultiplyCross = false; return; } // interpret second char as indicator for beautiful decimal powers: if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { mNumberBeautifulPowers = true; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; return; } if (formatCode.length() < 3) { mAxisPainter->numberMultiplyCross = false; return; } // interpret third char as indicator for dot or cross multiplication symbol: if (formatCode.at(2) == QLatin1Char('c')) { mAxisPainter->numberMultiplyCross = true; } else if (formatCode.at(2) == QLatin1Char('d')) { mAxisPainter->numberMultiplyCross = false; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; return; } } /*! Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) for details. The effect of precisions are most notably for number Formats starting with 'e', see \ref setNumberFormat */ void QCPAxis::setNumberPrecision(int precision) { if (mNumberPrecision != precision) { mNumberPrecision = precision; mCachedMarginValid = false; } } /*! Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPAxis::setTickLength(int inside, int outside) { setTickLengthIn(inside); setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthIn(int inside) { if (mAxisPainter->tickLengthIn != inside) { mAxisPainter->tickLengthIn = inside; } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthOut(int outside) { if (mAxisPainter->tickLengthOut != outside) { mAxisPainter->tickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets whether sub tick marks are displayed. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks) \see setTicks */ void QCPAxis::setSubTicks(bool show) { if (mSubTicks != show) { mSubTicks = show; mCachedMarginValid = false; } } /*! Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPAxis::setSubTickLength(int inside, int outside) { setSubTickLengthIn(inside); setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthIn(int inside) { if (mAxisPainter->subTickLengthIn != inside) { mAxisPainter->subTickLengthIn = inside; } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthOut(int outside) { if (mAxisPainter->subTickLengthOut != outside) { mAxisPainter->subTickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the pen, the axis base line is drawn with. \see setTickPen, setSubTickPen */ void QCPAxis::setBasePen(const QPen &pen) { mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. \see setTickLength, setBasePen */ void QCPAxis::setTickPen(const QPen &pen) { mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. \see setSubTickCount, setSubTickLength, setBasePen */ void QCPAxis::setSubTickPen(const QPen &pen) { mSubTickPen = pen; } /*! Sets the font of the axis label. \see setLabelColor */ void QCPAxis::setLabelFont(const QFont &font) { if (mLabelFont != font) { mLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the axis label. \see setLabelFont */ void QCPAxis::setLabelColor(const QColor &color) { mLabelColor = color; } /*! Sets the text of the axis label that will be shown below/above or next to the axis, depending on its orientation. To disable axis labels, pass an empty string as \a str. */ void QCPAxis::setLabel(const QString &str) { if (mLabel != str) { mLabel = str; mCachedMarginValid = false; } } /*! Sets the distance between the tick labels and the axis label. \see setTickLabelPadding, setPadding */ void QCPAxis::setLabelPadding(int padding) { if (mAxisPainter->labelPadding != padding) { mAxisPainter->labelPadding = padding; mCachedMarginValid = false; } } /*! Sets the padding of the axis. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, that is left blank. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. \see setLabelPadding, setTickLabelPadding */ void QCPAxis::setPadding(int padding) { if (mPadding != padding) { mPadding = padding; mCachedMarginValid = false; } } /*! Sets the offset the axis has to its axis rect side. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, only the offset of the inner most axis has meaning (even if it is set to be invisible). The offset of the other, outer axes is controlled automatically, to place them at appropriate positions. */ void QCPAxis::setOffset(int offset) { mAxisPainter->offset = offset; } /*! Sets the font that is used for tick labels when they are selected. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelFont(const QFont &font) { if (font != mSelectedTickLabelFont) { mSelectedTickLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } } /*! Sets the font that is used for the axis label when it is selected. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelFont(const QFont &font) { mSelectedLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor(const QColor &color) { if (color != mSelectedTickLabelColor) { mSelectedTickLabelColor = color; } } /*! Sets the color that is used for the axis label when it is selected. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor(const QColor &color) { mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen(const QPen &pen) { mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen(const QPen &pen) { mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen(const QPen &pen) { mSelectedSubTickPen = pen; } /*! Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setUpperEnding */ void QCPAxis::setLowerEnding(const QCPLineEnding &ending) { mAxisPainter->lowerEnding = ending; } /*! Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the right ending, for vertical axes the top ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setLowerEnding */ void QCPAxis::setUpperEnding(const QCPLineEnding &ending) { mAxisPainter->upperEnding = ending; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPAxis::moveRange(double diff) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { mRange.lower += diff; mRange.upper += diff; } else // mScaleType == stLogarithmic { mRange.lower *= diff; mRange.upper *= diff; } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis by \a factor around the center of the current axis range. For example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around the center will have moved symmetrically closer). If you wish to scale around a different coordinate than the current axis range center, use the overload \ref scaleRange(double factor, double center). */ void QCPAxis::scaleRange(double factor) { scaleRange(factor, range().center()); } /*! \overload Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates around 1.0 will have moved symmetrically closer to 1.0). \see scaleRange(double factor) */ void QCPAxis::scaleRange(double factor, double center) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { QCPRange newRange; newRange.lower = (mRange.lower-center)*factor + center; newRange.upper = (mRange.upper-center)*factor + center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLinScale(); } else // mScaleType == stLogarithmic { if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range { QCPRange newRange; newRange.lower = qPow(mRange.lower/center, factor)*center; newRange.upper = qPow(mRange.upper/center, factor)*center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLogScale(); } else qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will be done around the center of the current axis range. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the axis rect has. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent will follow. */ void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) { int otherPixelSize, ownPixelSize; if (otherAxis->orientation() == Qt::Horizontal) otherPixelSize = otherAxis->axisRect()->width(); else otherPixelSize = otherAxis->axisRect()->height(); if (orientation() == Qt::Horizontal) ownPixelSize = axisRect()->width(); else ownPixelSize = axisRect()->height(); double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize); setRange(range().center(), newRangeSize, Qt::AlignCenter); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPAxis::rescale(bool onlyVisiblePlottables) { QCPRange newRange; bool haveRange = false; foreach (QCPAbstractPlottable *plottable, plottables()) { if (!plottable->realVisibility() && onlyVisiblePlottables) continue; QCPRange plottableRange; bool currentFoundRange; QCP::SignDomain signDomain = QCP::sdBoth; if (mScaleType == stLogarithmic) signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); if (plottable->keyAxis() == this) plottableRange = plottable->getKeyRange(currentFoundRange, signDomain); else plottableRange = plottable->getValueRange(currentFoundRange, signDomain); if (currentFoundRange) { if (!haveRange) newRange = plottableRange; else newRange.expand(plottableRange); haveRange = true; } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mScaleType == stLinear) { newRange.lower = center-mRange.size()/2.0; newRange.upper = center+mRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mRange.upper/mRange.lower); newRange.upper = center*qSqrt(mRange.upper/mRange.lower); } } setRange(newRange); } } /*! Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. */ double QCPAxis::pixelToCoord(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.lower; else return -(value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/double(mAxisRect->width()))*mRange.lower; else return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/double(mAxisRect->width()))*mRange.upper; } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return (mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.lower; else return -(mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/double(mAxisRect->height()))*mRange.lower; else return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/double(mAxisRect->height()))*mRange.upper; } } } /*! Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. */ double QCPAxis::coordToPixel(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); else return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); } else // mScaleType == stLogarithmic { if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; else { if (!mRangeReversed) return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); else return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); } } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); else return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); } else // mScaleType == stLogarithmic { if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; else { if (!mRangeReversed) return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height(); else return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height(); } } } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. If the axis is not visible (\ref setVisible), this function always returns \ref spNone. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const { if (!mVisible) return spNone; if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; else return spNone; } /* inherits documentation from base class */ double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; SelectablePart part = getPartAt(pos); if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) return -1; if (details) details->setValue(part); return mParentPlot->selectionTolerance()*0.99; } /*! Returns a list of all the plottables that have this axis as key or value axis. If you are only interested in plottables of type QCPGraph, see \ref graphs. \see graphs, items */ QList QCPAxis::plottables() const { QList result; if (!mParentPlot) return result; foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables) { if (plottable->keyAxis() == this || plottable->valueAxis() == this) result.append(plottable); } return result; } /*! Returns a list of all the graphs that have this axis as key or value axis. \see plottables, items */ QList QCPAxis::graphs() const { QList result; if (!mParentPlot) return result; foreach (QCPGraph *graph, mParentPlot->mGraphs) { if (graph->keyAxis() == this || graph->valueAxis() == this) result.append(graph); } return result; } /*! Returns a list of all the items that are associated with this axis. An item is considered associated with an axis if at least one of its positions uses the axis as key or value axis. \see plottables, graphs */ QList QCPAxis::items() const { QList result; if (!mParentPlot) return result; foreach (QCPAbstractItem *item, mParentPlot->mItems) { foreach (QCPItemPosition *position, item->positions()) { if (position->keyAxis() == this || position->valueAxis() == this) { result.append(item); break; } } } return result; } /*! Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.) */ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) { switch (side) { case QCP::msLeft: return atLeft; case QCP::msRight: return atRight; case QCP::msTop: return atTop; case QCP::msBottom: return atBottom; default: break; } qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast(side); return atLeft; } /*! Returns the axis type that describes the opposite axis of an axis with the specified \a type. */ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) { switch (type) { case atLeft: return atRight; case atRight: return atLeft; case atBottom: return atTop; case atTop: return atBottom; } qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; } /* inherits documentation from base class */ void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) SelectablePart part = details.value(); if (mSelectableParts.testFlag(part)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^part : part); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPAxis::deselectEvent(bool *selectionStateChanged) { SelectableParts selBefore = mSelectedParts; setSelectedParts(mSelectedParts & ~mSelectableParts); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } /*! \internal This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref QCPAxisRect::setRangeDragAxes) \seebaseclassmethod \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. */ void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details) { Q_UNUSED(details) if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) || !mAxisRect->rangeDrag().testFlag(orientation()) || !mAxisRect->rangeDragAxes(orientation()).contains(this)) { event->ignore(); return; } if (event->buttons() & Qt::LeftButton) { mDragging = true; // initialize antialiasing backup in case we start dragging: if (mParentPlot->noAntialiasingOnDrag()) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) mDragStartRange = mRange; } } /*! \internal This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. \seebaseclassmethod \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. \see QCPAxis::mousePressEvent */ void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { if (mDragging) { const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); if (mScaleType == QCPAxis::stLinear) { const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff); } else if (mScaleType == QCPAxis::stLogarithmic) { const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff); } if (mParentPlot->noAntialiasingOnDrag()) mParentPlot->setNotAntialiasedElements(QCP::aeAll); mParentPlot->replot(QCustomPlot::rpQueuedReplot); } } /*! \internal This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. \seebaseclassmethod \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. \see QCPAxis::mousePressEvent */ void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(event) Q_UNUSED(startPos) mDragging = false; if (mParentPlot->noAntialiasingOnDrag()) { mParentPlot->setAntialiasedElements(mAADragBackup); mParentPlot->setNotAntialiasedElements(mNotAADragBackup); } } /*! \internal This mouse event reimplementation provides the functionality to let the user zoom individual axes exclusively, by performing the wheel event on top of the axis. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref QCPAxisRect::setRangeZoomAxes) \seebaseclassmethod \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent. */ void QCPAxis::wheelEvent(QWheelEvent *event) { // Mouse range zooming interaction: if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) || !mAxisRect->rangeZoom().testFlag(orientation()) || !mAxisRect->rangeZoomAxes(orientation()).contains(this)) { event->ignore(); return; } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) const double delta = event->delta(); #else const double delta = event->angleDelta().y(); #endif #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) const QPointF pos = event->pos(); #else const QPointF pos = event->position(); #endif const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps); scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y())); mParentPlot->replot(); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \seebaseclassmethod \see setAntialiased */ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. \seebaseclassmethod */ void QCPAxis::draw(QCPPainter *painter) { QVector subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(mTickVector.size()); tickLabels.reserve(mTickVector.size()); subTickPositions.reserve(mSubTickVector.size()); if (mTicks) { for (int i=0; itype = mAxisType; mAxisPainter->basePen = getBasePen(); mAxisPainter->labelFont = getLabelFont(); mAxisPainter->labelColor = getLabelColor(); mAxisPainter->label = mLabel; mAxisPainter->substituteExponent = mNumberBeautifulPowers; mAxisPainter->tickPen = getTickPen(); mAxisPainter->subTickPen = getSubTickPen(); mAxisPainter->tickLabelFont = getTickLabelFont(); mAxisPainter->tickLabelColor = getTickLabelColor(); mAxisPainter->axisRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; mAxisPainter->reversedEndings = mRangeReversed; mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; mAxisPainter->subTickPositions = subTickPositions; mAxisPainter->draw(painter); } /*! \internal Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling QCPAxisTicker::generate on the currently installed ticker. If a change in the label text/count is detected, the cached axis margin is invalidated to make sure the next margin calculation recalculates the label sizes and returns an up-to-date value. */ void QCPAxis::setupTickVectors() { if (!mParentPlot) return; if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; QVector oldLabels = mTickVectorLabels; mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr); mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too } /*! \internal Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPAxis::getBasePen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPAxis::getTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPAxis::getSubTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPAxis::getTickLabelFont() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPAxis::getLabelFont() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPAxis::getTickLabelColor() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPAxis::getLabelColor() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal Returns the appropriate outward margin for this axis. It is needed if \ref QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom margin and so forth. For the calculation, this function goes through similar steps as \ref draw, so changing one function likely requires the modification of the other one as well. The margin consists of the outward tick length, tick label padding, tick label size, label padding, label size, and padding. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. unchanged are very fast. */ int QCPAxis::calculateMargin() { if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis return 0; if (mCachedMarginValid) return mCachedMargin; // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels int margin = 0; QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(mTickVector.size()); tickLabels.reserve(mTickVector.size()); if (mTicks) { for (int i=0; itype = mAxisType; mAxisPainter->labelFont = getLabelFont(); mAxisPainter->label = mLabel; mAxisPainter->tickLabelFont = mTickLabelFont; mAxisPainter->axisRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; margin += mAxisPainter->size(); margin += mPadding; mCachedMargin = margin; mCachedMarginValid = true; return margin; } /* inherits documentation from base class */ QCP::Interaction QCPAxis::selectionCategory() const { return QCP::iSelectAxes; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisPainterPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisPainterPrivate \internal \brief (Private) This is a private class and not part of the public QCustomPlot interface. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and axis label. It also buffers the labels to reduce replot times. The parameters are configured by directly accessing the public member variables. */ /*! Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every redraw, to utilize the caching mechanisms. */ QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : type(QCPAxis::atLeft), basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), lowerEnding(QCPLineEnding::esNone), upperEnding(QCPLineEnding::esNone), labelPadding(0), tickLabelPadding(0), tickLabelRotation(0), tickLabelSide(QCPAxis::lsOutside), substituteExponent(true), numberMultiplyCross(false), tickLengthIn(5), tickLengthOut(0), subTickLengthIn(2), subTickLengthOut(0), tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), offset(0), abbreviateDecimalPowers(false), reversedEndings(false), mParentPlot(parentPlot), mLabelCache(16) // cache at most 16 (tick) labels { } QCPAxisPainterPrivate::~QCPAxisPainterPrivate() { } /*! \internal Draws the axis with the specified \a painter. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw(QCPPainter *painter) { QByteArray newHash = generateLabelParameterHash(); if (newHash != mLabelParameterHash) { mLabelCache.clear(); mLabelParameterHash = newHash; } QPoint origin; switch (type) { case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; } double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) switch (type) { case QCPAxis::atTop: yCor = -1; break; case QCPAxis::atRight: xCor = 1; break; default: break; } int margin = 0; // draw baseline: QLineF baseLine; painter->setPen(basePen); if (QCPAxis::orientation(type) == Qt::Horizontal) baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); else baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); if (reversedEndings) baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later painter->drawLine(baseLine); // draw ticks: if (!tickPositions.isEmpty()) { painter->setPen(tickPen); int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) if (QCPAxis::orientation(type) == Qt::Horizontal) { foreach (double tickPos, tickPositions) painter->drawLine(QLineF(tickPos+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPos+xCor, origin.y()+tickLengthIn*tickDir+yCor)); } else { foreach (double tickPos, tickPositions) painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPos+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPos+yCor)); } } // draw subticks: if (!subTickPositions.isEmpty()) { painter->setPen(subTickPen); // direction of ticks ("inward" is right for left axis and left for right axis) int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; if (QCPAxis::orientation(type) == Qt::Horizontal) { foreach (double subTickPos, subTickPositions) painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); } else { foreach (double subTickPos, subTickPositions) painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor)); } } margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // draw axis base endings: bool antialiasingBackup = painter->antialiasing(); painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't painter->setBrush(QBrush(basePen.color())); QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy()); if (lowerEnding.style() != QCPLineEnding::esNone) lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); if (upperEnding.style() != QCPLineEnding::esNone) upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); painter->setAntialiasing(antialiasingBackup); // tick labels: QRect oldClipRect; if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect { oldClipRect = painter->clipRegion().boundingRect(); painter->setClipRect(axisRect); } QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label if (!tickLabels.isEmpty()) { if (tickLabelSide == QCPAxis::lsOutside) margin += tickLabelPadding; painter->setFont(tickLabelFont); painter->setPen(QPen(tickLabelColor)); const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); int distanceToAxis = margin; if (tickLabelSide == QCPAxis::lsInside) distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); for (int i=0; isetClipRect(oldClipRect); // axis label: QRect labelBounds; if (!label.isEmpty()) { margin += labelPadding; painter->setFont(labelFont); painter->setPen(QPen(labelColor)); labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); if (type == QCPAxis::atLeft) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); painter->rotate(-90); painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atRight) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); painter->rotate(90); painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atTop) painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); else if (type == QCPAxis::atBottom) painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); } // set selection boxes: int selectionTolerance = 0; if (mParentPlot) selectionTolerance = mParentPlot->selectionTolerance(); else qDebug() << Q_FUNC_INFO << "mParentPlot is null"; int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); int selAxisInSize = selectionTolerance; int selTickLabelSize; int selTickLabelOffset; if (tickLabelSide == QCPAxis::lsOutside) { selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; } else { selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); } int selLabelSize = labelBounds.height(); int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; if (type == QCPAxis::atLeft) { mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); } else if (type == QCPAxis::atRight) { mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); } else if (type == QCPAxis::atTop) { mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); } else if (type == QCPAxis::atBottom) { mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); } mAxisSelectionBox = mAxisSelectionBox.normalized(); mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); mLabelSelectionBox = mLabelSelectionBox.normalized(); // draw hitboxes for debug purposes: //painter->setBrush(Qt::NoBrush); //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() { int result = 0; QByteArray newHash = generateLabelParameterHash(); if (newHash != mLabelParameterHash) { mLabelCache.clear(); mLabelParameterHash = newHash; } // get length of tick marks pointing outwards: if (!tickPositions.isEmpty()) result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // calculate size of tick labels: if (tickLabelSide == QCPAxis::lsOutside) { QSize tickLabelsSize(0, 0); if (!tickLabels.isEmpty()) { foreach (const QString &tickLabel, tickLabels) getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize); result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width(); result += tickLabelPadding; } } // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees): if (!label.isEmpty()) { QFontMetrics fontMetrics(labelFont); QRect bounds; bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label); result += bounds.height() + labelPadding; } return result; } /*! \internal Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This method is called automatically in \ref draw, if any parameters have changed that invalidate the cached labels, such as font, color, etc. */ void QCPAxisPainterPrivate::clearCache() { mLabelCache.clear(); } /*! \internal Returns a hash that allows uniquely identifying whether the label parameters have changed such that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the return value of this method hasn't changed since the last redraw, the respective label parameters haven't changed and cached labels may be used. */ QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const { QByteArray result; result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio())); result.append(QByteArray::number(tickLabelRotation)); result.append(QByteArray::number(int(tickLabelSide))); result.append(QByteArray::number(int(substituteExponent))); result.append(QByteArray::number(int(numberMultiplyCross))); result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16)); result.append(tickLabelFont.toString().toLatin1()); return result; } /*! \internal Draws a single tick label with the provided \a painter, utilizing the internal label cache to significantly speed up drawing of labels that were drawn in previous calls. The tick label is always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate), at which the label should be drawn. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently holds. The label is drawn with the font and pen that are currently set on the \a painter. To draw superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref getTickLabelData). */ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize) { // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! if (text.isEmpty()) return; QSize finalSize; QPointF labelAnchor; switch (type) { case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break; case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break; case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break; case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break; } if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled { CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache if (!cachedLabel) // no cached label existed, create it { cachedLabel = new CachedLabel; TickLabelData labelData = getTickLabelData(painter->font(), text); cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft(); if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio())) { cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio()); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED # ifdef QCP_DEVICEPIXELRATIO_FLOAT cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); # else cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); # endif #endif } else cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); cachedLabel->pixmap.fill(Qt::transparent); QCPPainter cachePainter(&cachedLabel->pixmap); cachePainter.setPen(painter->pen()); drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); } // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left(); else labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); } if (!labelClippedByBorder) { painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); } mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created } else // label caching disabled, draw text directly on surface: { TickLabelData labelData = getTickLabelData(painter->font(), text); QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); else labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); } if (!labelClippedByBorder) { drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); finalSize = labelData.rotatedTotalBounds.size(); } } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } /*! \internal This is a \ref placeTickLabel helper function. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when QCP::phCacheLabels plotting hint is not set. */ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const { // backup painter settings that we're about to change: QTransform oldTransform = painter->transform(); QFont oldFont = painter->font(); // transform painter to position/rotation: painter->translate(x, y); if (!qFuzzyIsNull(tickLabelRotation)) painter->rotate(tickLabelRotation); // draw text: if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used { painter->setFont(labelData.baseFont); painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); if (!labelData.suffixPart.isEmpty()) painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart); painter->setFont(labelData.expFont); painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); } else { painter->setFont(labelData.baseFont); painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); } // reset painter settings to what it was before: painter->setTransform(oldTransform); painter->setFont(oldFont); } /*! \internal This is a \ref placeTickLabel helper function. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const { TickLabelData result; // determine whether beautiful decimal powers should be used bool useBeautifulPowers = false; int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart if (substituteExponent) { ePos = text.indexOf(QLatin1Char('e')); if (ePos > 0 && text.at(ePos-1).isDigit()) { eLast = ePos; while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit())) ++eLast; if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power useBeautifulPowers = true; } } // calculate text bounding rects and do string preparation for beautiful decimal powers: result.baseFont = font; if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding if (useBeautifulPowers) { // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: result.basePart = text.left(ePos); result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: if (abbreviateDecimalPowers && result.basePart == QLatin1String("1")) result.basePart = QLatin1String("10"); else result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10"); result.expPart = text.mid(ePos+1, eLast-ePos); // clip "+" and leading zeros off expPart: while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e' result.expPart.remove(1, 1); if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) result.expPart.remove(0, 1); // prepare smaller font for exponent: result.expFont = font; if (result.expFont.pointSize() > 0) result.expFont.setPointSize(int(result.expFont.pointSize()*0.75)); else result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75)); // calculate bounding rects of base part(s), exponent part and total one: result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); if (!result.suffixPart.isEmpty()) result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart); result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA } else // useBeautifulPowers == false { result.basePart = text; result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); } result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler // calculate possibly different bounding rect after rotation: result.rotatedTotalBounds = result.totalBounds; if (!qFuzzyIsNull(tickLabelRotation)) { QTransform transform; transform.rotate(tickLabelRotation); result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); } return result; } /*! \internal This is a \ref placeTickLabel helper function. Calculates the offset at which the top left corner of the specified tick label shall be drawn. The offset is relative to a point right next to the tick the label belongs to. This function is thus responsible for e.g. centering tick labels under ticks and positioning them appropriately when they are rotated. */ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const { /* calculate label offset from base point at tick (non-trivial, for best visual appearance): short explanation for bottom axis: The anchor, i.e. the point in the label that is placed horizontally under the corresponding tick is always on the label side that is closer to the axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text will be centered under the tick (i.e. displaced horizontally by half its height). At the same time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick labels. */ bool doRotation = !qFuzzyIsNull(tickLabelRotation); bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. double radians = tickLabelRotation/180.0*M_PI; double x = 0; double y = 0; if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width(); y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = -labelData.totalBounds.width(); y = -labelData.totalBounds.height()/2.0; } } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height(); y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = 0; y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = 0; y = -labelData.totalBounds.height()/2.0; } } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); } else { x = -qSin(-radians)*labelData.totalBounds.height()/2.0; y = -qCos(-radians)*labelData.totalBounds.height(); } } else { x = -labelData.totalBounds.width()/2.0; y = -labelData.totalBounds.height(); } } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height()/2.0; y = 0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; y = +qSin(-radians)*labelData.totalBounds.width(); } } else { x = -labelData.totalBounds.width()/2.0; y = 0; } } return {x, y}; } /*! \internal Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a smaller width/height. */ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { // note: this function must return the same tick label sizes as the placeTickLabel function. QSize finalSize; if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label { const CachedLabel *cachedLabel = mLabelCache.object(text); finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); } else // label caching disabled or no label with this text cached: { TickLabelData labelData = getTickLabelData(font, text); finalSize = labelData.rotatedTotalBounds.size(); } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } /* end of 'src/axis/axis.cpp' */ /* including file 'src/scatterstyle.cpp' */ /* modified 2021-03-29T02:30:44, size 17466 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPScatterStyle //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPScatterStyle \brief Represents the visual appearance of scatter points This class holds information about shape, color and size of scatter points. In plottables like QCPGraph it is used to store how scatter points shall be drawn. For example, \ref QCPGraph::setScatterStyle takes a QCPScatterStyle instance. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can be controlled with \ref setSize. \section QCPScatterStyle-defining Specifying a scatter style You can set all these configurations either by calling the respective functions on an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1 Or you can use one of the various constructors that take different parameter combinations, making it easy to specify a scatter style in a single call, like so: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2 \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref isPenDefined will return false. It leads to scatter points that inherit the pen from the plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes it very convenient to set up typical scatter settings: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size) constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref ScatterShape, where actually a QCPScatterStyle is expected. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref setCustomPath function or call the constructor that takes a painter path. The scatter shape will automatically be set to \ref ssCustom. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap. Note that \ref setSize does not influence the appearance of the pixmap. */ /* start documentation of inline functions */ /*! \fn bool QCPScatterStyle::isNone() const Returns whether the scatter shape is \ref ssNone. \see setShape */ /*! \fn bool QCPScatterStyle::isPenDefined() const Returns whether a pen has been defined for this scatter style. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is undefined, the pen of the respective plottable will be used for drawing scatters. If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call \ref undefinePen. \see setPen */ /* end documentation of inline functions */ /*! Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle() : mSize(6), mShape(ssNone), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : mSize(size), mShape(shape), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, and size to \a size. No brush is defined, i.e. the scatter point will not be filled. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(Qt::NoBrush), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, the brush color to \a fill (with a solid pattern), and size to \a size. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(QBrush(fill)), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the brush to \a brush, and size to \a size. \warning In some cases it might be tempting to directly use a pen style like Qt::NoPen as \a pen and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n doesn't necessarily lead C++ to use this constructor in some cases, but might mistake Qt::NoPen for a QColor and use the \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) constructor instead (which will lead to an unexpected look of the scatter points). To prevent this, be more explicit with the parameter types. For example, use QBrush(Qt::blue) instead of just Qt::blue, to clearly point out to the compiler that this constructor is wanted. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(shape), mPen(pen), mBrush(brush), mPenDefined(pen.style() != Qt::NoPen) { } /*! Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape is set to \ref ssPixmap. */ QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : mSize(5), mShape(ssPixmap), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPixmap(pixmap), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The scatter shape is set to \ref ssCustom. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly different meaning than for built-in scatter points: The custom path will be drawn scaled by a factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its original size by default. To for example double the size of the path, set \a size to 12. */ QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(ssCustom), mPen(pen), mBrush(brush), mCustomPath(customPath), mPenDefined(pen.style() != Qt::NoPen) { } /*! Copies the specified \a properties from the \a other scatter style to this scatter style. */ void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties) { if (properties.testFlag(spPen)) { setPen(other.pen()); if (!other.isPenDefined()) undefinePen(); } if (properties.testFlag(spBrush)) setBrush(other.brush()); if (properties.testFlag(spSize)) setSize(other.size()); if (properties.testFlag(spShape)) { setShape(other.shape()); if (other.shape() == ssPixmap) setPixmap(other.pixmap()); else if (other.shape() == ssCustom) setCustomPath(other.customPath()); } } /*! Sets the size (pixel diameter) of the drawn scatter points to \a size. \see setShape */ void QCPScatterStyle::setSize(double size) { mSize = size; } /*! Sets the shape to \a shape. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref ssPixmap and \ref ssCustom, respectively. \see setSize */ void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape) { mShape = shape; } /*! Sets the pen that will be used to draw scatter points to \a pen. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after a call to this function, even if \a pen is Qt::NoPen. If you have defined a pen previously by calling this function and now wish to undefine the pen, call \ref undefinePen. \see setBrush */ void QCPScatterStyle::setPen(const QPen &pen) { mPenDefined = true; mPen = pen; } /*! Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does. \see setPen */ void QCPScatterStyle::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the pixmap that will be drawn as scatter point to \a pixmap. Note that \ref setSize does not influence the appearance of the pixmap. The scatter shape is automatically set to \ref ssPixmap. */ void QCPScatterStyle::setPixmap(const QPixmap &pixmap) { setShape(ssPixmap); mPixmap = pixmap; } /*! Sets the custom shape that will be drawn as scatter point to \a customPath. The scatter shape is automatically set to \ref ssCustom. */ void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) { setShape(ssCustom); mCustomPath = customPath; } /*! Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen implies). A call to \ref setPen will define a pen. */ void QCPScatterStyle::undefinePen() { mPenDefined = false; } /*! Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead. This function is used by plottables (or any class that wants to draw scatters) just before a number of scatters with this style shall be drawn with the \a painter. \see drawShape */ void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const { painter->setPen(mPenDefined ? mPen : defaultPen); painter->setBrush(mBrush); } /*! Draws the scatter shape with \a painter at position \a pos. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be called before scatter points are drawn with \ref drawShape. \see applyTo */ void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const { drawShape(painter, pos.x(), pos.y()); } /*! \overload Draws the scatter shape with \a painter at position \a x and \a y. */ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const { double w = mSize/2.0; switch (mShape) { case ssNone: break; case ssDot: { painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); break; } case ssCross: { painter->drawLine(QLineF(x-w, y-w, x+w, y+w)); painter->drawLine(QLineF(x-w, y+w, x+w, y-w)); break; } case ssPlus: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); break; } case ssCircle: { painter->drawEllipse(QPointF(x , y), w, w); break; } case ssDisc: { QBrush b = painter->brush(); painter->setBrush(painter->pen().color()); painter->drawEllipse(QPointF(x , y), w, w); painter->setBrush(b); break; } case ssSquare: { painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssDiamond: { QPointF lineArray[4] = {QPointF(x-w, y), QPointF( x, y-w), QPointF(x+w, y), QPointF( x, y+w)}; painter->drawPolygon(lineArray, 4); break; } case ssStar: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707)); painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707)); break; } case ssTriangle: { QPointF lineArray[3] = {QPointF(x-w, y+0.755*w), QPointF(x+w, y+0.755*w), QPointF( x, y-0.977*w)}; painter->drawPolygon(lineArray, 3); break; } case ssTriangleInverted: { QPointF lineArray[3] = {QPointF(x-w, y-0.755*w), QPointF(x+w, y-0.755*w), QPointF( x, y+0.977*w)}; painter->drawPolygon(lineArray, 3); break; } case ssCrossSquare: { painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95)); painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w)); break; } case ssPlusSquare: { painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); break; } case ssCrossCircle: { painter->drawEllipse(QPointF(x, y), w, w); painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670)); painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707)); break; } case ssPlusCircle: { painter->drawEllipse(QPointF(x, y), w, w); painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); break; } case ssPeace: { painter->drawEllipse(QPointF(x, y), w, w); painter->drawLine(QLineF(x, y-w, x, y+w)); painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707)); painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707)); break; } case ssPixmap: { const double widthHalf = mPixmap.width()*0.5; const double heightHalf = mPixmap.height()*0.5; #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0) const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); #else const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); #endif if (clipRect.contains(x, y)) painter->drawPixmap(qRound(x-widthHalf), qRound(y-heightHalf), mPixmap); break; } case ssCustom: { QTransform oldTransform = painter->transform(); painter->translate(x, y); painter->scale(mSize/6.0, mSize/6.0); painter->drawPath(mCustomPath); painter->setTransform(oldTransform); break; } } } /* end of 'src/scatterstyle.cpp' */ /* including file 'src/plottable.cpp' */ /* modified 2021-03-29T02:30:44, size 38818 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPSelectionDecorator //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPSelectionDecorator \brief Controls how a plottable's data selection is drawn Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data. The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref QCPScatterStyle is itself composed of different properties such as color shape and size, the decorator allows specifying exactly which of those properties shall be used for the selected data point, via \ref setUsedScatterProperties. A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance of selected segments. Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is especially useful since plottables take ownership of the passed selection decorator, and thus the same decorator instance can not be passed to multiple plottables. Selection decorators can also themselves perform drawing operations by reimplementing \ref drawDecoration, which is called by the plottable's draw method. The base class \ref QCPSelectionDecorator does not make use of this however. For example, \ref QCPSelectionDecoratorBracket draws brackets around selected data segments. */ /*! Creates a new QCPSelectionDecorator instance with default values */ QCPSelectionDecorator::QCPSelectionDecorator() : mPen(QColor(80, 80, 255), 2.5), mBrush(Qt::NoBrush), mUsedScatterProperties(QCPScatterStyle::spNone), mPlottable(nullptr) { } QCPSelectionDecorator::~QCPSelectionDecorator() { } /*! Sets the pen that will be used by the parent plottable to draw selected data segments. */ void QCPSelectionDecorator::setPen(const QPen &pen) { mPen = pen; } /*! Sets the brush that will be used by the parent plottable to draw selected data segments. */ void QCPSelectionDecorator::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the scatter style that will be used by the parent plottable to draw scatters in selected data segments. \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the plottable. The used properties can also be changed via \ref setUsedScatterProperties. */ void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties) { mScatterStyle = scatterStyle; setUsedScatterProperties(usedProperties); } /*! Use this method to define which properties of the scatter style (set via \ref setScatterStyle) will be used for selected data segments. All properties of the scatter style that are not specified in \a properties will remain as specified in the plottable's original scatter style. \see QCPScatterStyle::ScatterProperty */ void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties) { mUsedScatterProperties = properties; } /*! Sets the pen of \a painter to the pen of this selection decorator. \see applyBrush, getFinalScatterStyle */ void QCPSelectionDecorator::applyPen(QCPPainter *painter) const { painter->setPen(mPen); } /*! Sets the brush of \a painter to the brush of this selection decorator. \see applyPen, getFinalScatterStyle */ void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const { painter->setBrush(mBrush); } /*! Returns the scatter style that the parent plottable shall use for selected scatter points. The plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle. \see applyPen, applyBrush, setScatterStyle */ QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const { QCPScatterStyle result(unselectedStyle); result.setFromOther(mScatterStyle, mUsedScatterProperties); // if style shall inherit pen from plottable (has no own pen defined), give it the selected // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the // plottable: if (!result.isPenDefined()) result.setPen(mPen); return result; } /*! Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to this selection decorator. */ void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other) { setPen(other->pen()); setBrush(other->brush()); setScatterStyle(other->scatterStyle(), other->usedScatterProperties()); } /*! This method is called by all plottables' draw methods to allow custom selection decorations to be drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data selection for which the decoration shall be drawn. The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so this method does nothing. */ void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection) { Q_UNUSED(painter) Q_UNUSED(selection) } /*! \internal This method is called as soon as a selection decorator is associated with a plottable, by a call to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access data points via the \ref QCPAbstractPlottable::interface1D interface). If the selection decorator was already added to a different plottable before, this method aborts the registration and returns false. */ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable) { if (!mPlottable) { mPlottable = plottable; return true; } else { qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast(mPlottable); return false; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractPlottable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractPlottable \brief The abstract base class for all data representing objects in a plot. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new ways of displaying data (see "Creating own plottables" below). Plottables that display one-dimensional data (i.e. data points have a single key dimension and one or multiple values at each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details there. All further specifics are in the subclasses, for example: \li A normal graph with possibly a line and/or scatter points \ref QCPGraph (typically created with \ref QCustomPlot::addGraph) \li A parametric curve: \ref QCPCurve \li A bar chart: \ref QCPBars \li A statistical box plot: \ref QCPStatisticalBox \li A color encoded two-dimensional map: \ref QCPColorMap \li An OHLC/Candlestick chart: \ref QCPFinancial \section plottables-subclassing Creating own plottables Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more) data dimensions. If you want to display data with only one logical key dimension, you should rather derive from \ref QCPAbstractPlottable1D. If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must implement: \li \ref selectTest \li \ref draw \li \ref drawLegendIcon \li \ref getKeyRange \li \ref getValueRange See the documentation of those functions for what they need to do. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot coordinates to pixel coordinates. This function is quite convenient, because it takes the orientation of the key and value axes into account for you (x and y are swapped when the key axis is vertical and the value axis horizontal). If you are worried about performance (i.e. you need to translate many points in a loop like QCPGraph), you can directly use \ref QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis yourself. Here are some important members you inherit from QCPAbstractPlottable:
QCustomPlot *\b mParentPlot A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.
QString \b mName The name of the plottable.
QPen \b mPen The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)
QBrush \b mBrush The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)
QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension. Make sure to check whether the pointer is \c nullptr before using it. If one of the axes is null, don't draw the plottable.
\ref QCPSelectionDecorator \b mSelectionDecorator The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated. When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments. Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.
\ref QCP::SelectionType \b mSelectable In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done by QCPAbstractPlottable automatically.
\ref QCPDataSelection \b mSelection Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).
*/ /* start of documentation of inline functions */ /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const Provides access to the selection decorator of this plottable. The selection decorator controls how selected data ranges are drawn (e.g. their pen color and fill), see \ref QCPSelectionDecorator for details. If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref setSelectionDecorator. */ /*! \fn bool QCPAbstractPlottable::selected() const Returns true if there are any data points of the plottable currently selected. Use \ref selection to retrieve the current \ref QCPDataSelection. */ /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on this plottable. \see selected, setSelection, setSelectable */ /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D() If this plottable is a one-dimensional plottable, i.e. it implements the \ref QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case of a \ref QCPColorMap) returns zero. You can use this method to gain read access to data coordinates while holding a pointer to the abstract base class only. */ /* end of documentation of inline functions */ /* start of documentation of pure virtual functions */ /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 \internal called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation of this plottable inside \a rect, next to the plottable name. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't appear outside the legend icon border. */ /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0 Returns the coordinate range that all data in this plottable span in the key axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero (e.g. when there is only one data point). In this case \a foundRange would return true, but the returned range is not a valid range in terms of \ref QCPRange::validRange. \see rescaleAxes, getValueRange */ /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0 Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). If \a inKeyRange has both lower and upper bound set to zero (is equal to QCPRange()), all data points are considered, without any restriction on the keys. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero (e.g. when there is only one data point). In this case \a foundRange would return true, but the returned range is not a valid range in terms of \ref QCPRange::validRange. \see rescaleAxes, getKeyRange */ /* end of documentation of pure virtual functions */ /* start of documentation of signals */ /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) This signal is emitted when the selection state of this plottable has changed, either by user interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether there are any points selected or not. \see selectionChanged(const QCPDataSelection &selection) */ /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection) This signal is emitted when the selection state of this plottable has changed, either by user interaction or by a direct call to \ref setSelection. The parameter \a selection holds the currently selected data ranges. \see selectionChanged(bool selected) */ /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable); This signal is emitted when the selectability of this plottable has changed. \see setSelectable */ /* end of documentation of signals */ /*! Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and have perpendicular orientations. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, it can't be directly instantiated. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. */ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), mName(), mAntialiasedFill(true), mAntialiasedScatters(true), mPen(Qt::black), mBrush(Qt::NoBrush), mKeyAxis(keyAxis), mValueAxis(valueAxis), mSelectable(QCP::stWhole), mSelectionDecorator(nullptr) { if (keyAxis->parentPlot() != valueAxis->parentPlot()) qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; if (keyAxis->orientation() == valueAxis->orientation()) qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; mParentPlot->registerPlottable(this); setSelectionDecorator(new QCPSelectionDecorator); } QCPAbstractPlottable::~QCPAbstractPlottable() { if (mSelectionDecorator) { delete mSelectionDecorator; mSelectionDecorator = nullptr; } } /*! The name is the textual representation of this plottable as it is displayed in the legend (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. */ void QCPAbstractPlottable::setName(const QString &name) { mName = name; } /*! Sets whether fills of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedFill(bool enabled) { mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) { mAntialiasedScatters = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPAbstractPlottable::setPen(const QPen &pen) { mPen = pen; } /*! The brush is used to draw basic fills of the plottable representation in the plot. The Fill can be a color, gradient or texture, see the usage of QBrush. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. \see setPen */ void QCPAbstractPlottable::setBrush(const QBrush &brush) { mBrush = brush; } /*! The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setValueAxis */ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) { mKeyAxis = axis; } /*! The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's key axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setKeyAxis */ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) { mValueAxis = axis; } /*! Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref selectionDecorator). The entire selection mechanism for plottables is handled automatically when \ref QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when you wish to change the selection state programmatically. Using \ref setSelectable you can further specify for each plottable whether and to which granularity it is selectable. If \a selection is not compatible with the current \ref QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted accordingly (see \ref QCPDataSelection::enforceType). emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractPlottable::setSelection(QCPDataSelection selection) { selection.enforceType(mSelectable); if (mSelection != selection) { mSelection = selection; emit selectionChanged(selected()); emit selectionChanged(mSelection); } } /*! Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to customize the visual representation of selected data ranges further than by using the default QCPSelectionDecorator. The plottable takes ownership of the \a decorator. The currently set decorator can be accessed via \ref selectionDecorator. */ void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator) { if (decorator) { if (decorator->registerWithPlottable(this)) { delete mSelectionDecorator; // delete old decorator if necessary mSelectionDecorator = decorator; } } else if (mSelectionDecorator) // just clear decorator { delete mSelectionDecorator; mSelectionDecorator = nullptr; } } /*! Sets whether and to which granularity this plottable can be selected. A selection can happen by clicking on the QCustomPlot surface (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by calling \ref setSelection. \see setSelection, QCP::SelectionType */ void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable) { if (mSelectable != selectable) { mSelectable = selectable; QCPDataSelection oldSelection = mSelection; mSelection.enforceType(mSelectable); emit selectableChanged(mSelectable); if (mSelection != oldSelection) { emit selectionChanged(selected()); emit selectionChanged(mSelection); } } } /*! Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y. \see pixelsToCoords, QCPAxis::coordToPixel */ void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { x = keyAxis->coordToPixel(key); y = valueAxis->coordToPixel(value); } else { y = keyAxis->coordToPixel(key); x = valueAxis->coordToPixel(value); } } /*! \overload Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF. */ const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } if (keyAxis->orientation() == Qt::Horizontal) return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value)); else return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); } /*! Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value. \see coordsToPixels, QCPAxis::coordToPixel */ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { key = keyAxis->pixelToCoord(x); value = valueAxis->pixelToCoord(y); } else { key = keyAxis->pixelToCoord(y); value = valueAxis->pixelToCoord(x); } } /*! \overload Returns the pixel input \a pixelPos as plot coordinates \a key and \a value. */ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); } /*! Rescales the key and value axes associated with this plottable to contain all displayed data, so the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie outside of that domain. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has \a onlyEnlarge set to false (the default), and all subsequent set to true. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const { rescaleKeyAxis(onlyEnlarge); rescaleValueAxis(onlyEnlarge); } /*! Rescales the key axis of the plottable so the whole plottable is visible. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } QCP::SignDomain signDomain = QCP::sdBoth; if (keyAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); bool foundRange; QCPRange newRange = getKeyRange(foundRange, signDomain); if (foundRange) { if (onlyEnlarge) newRange.expand(keyAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (keyAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-keyAxis->range().size()/2.0; newRange.upper = center+keyAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); } } keyAxis->setRange(newRange); } } /*! Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is set to true, only the data points which are in the currently visible key axis range are considered. Returns true if the axis was actually scaled. This might not be the case if this plottable has an invalid range, e.g. because it has no data points. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QCP::SignDomain signDomain = QCP::sdBoth; if (valueAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); if (foundRange) { if (onlyEnlarge) newRange.expand(valueAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (valueAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-valueAxis->range().size()/2.0; newRange.upper = center+valueAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); } } valueAxis->setRange(newRange); } } /*! \overload Adds this plottable to the specified \a legend. Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in the legend. If the plottable needs a more specialized representation in the legend, you can create a corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead of calling this method. \see removeFromLegend, QCPLegend::addItem */ bool QCPAbstractPlottable::addToLegend(QCPLegend *legend) { if (!legend) { qDebug() << Q_FUNC_INFO << "passed legend is null"; return false; } if (legend->parentPlot() != mParentPlot) { qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; return false; } if (!legend->hasItemWithPlottable(this)) { legend->addItem(new QCPPlottableLegendItem(legend, this)); return true; } else return false; } /*! \overload Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend). \see removeFromLegend */ bool QCPAbstractPlottable::addToLegend() { if (!mParentPlot || !mParentPlot->legend) return false; else return addToLegend(mParentPlot->legend); } /*! \overload Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem that is associated with this plottable is removed. Returns true on success, i.e. if the legend exists and a legend item associated with this plottable was found and removed. \see addToLegend, QCPLegend::removeItem */ bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const { if (!legend) { qDebug() << Q_FUNC_INFO << "passed legend is null"; return false; } if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this)) return legend->removeItem(lip); else return false; } /*! \overload Removes the plottable from the legend of the parent QCustomPlot. \see addToLegend */ bool QCPAbstractPlottable::removeFromLegend() const { if (!mParentPlot || !mParentPlot->legend) return false; else return removeFromLegend(mParentPlot->legend); } /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { if (mKeyAxis && mValueAxis) return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); else return {}; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractPlottable::selectionCategory() const { return QCP::iSelectPlottables; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \seebaseclassmethod \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable fills. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable scatter points. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } /* inherits documentation from base class */ void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) if (mSelectable != QCP::stNone) { QCPDataSelection newSelection = details.value(); QCPDataSelection selectionBefore = mSelection; if (additive) { if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit { if (selected()) setSelection(QCPDataSelection()); else setSelection(newSelection); } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments { if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection setSelection(mSelection-newSelection); else setSelection(mSelection+newSelection); } } else setSelection(newSelection); if (selectionStateChanged) *selectionStateChanged = mSelection != selectionBefore; } } /* inherits documentation from base class */ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) { if (mSelectable != QCP::stNone) { QCPDataSelection selectionBefore = mSelection; setSelection(QCPDataSelection()); if (selectionStateChanged) *selectionStateChanged = mSelection != selectionBefore; } } /* end of 'src/plottable.cpp' */ /* including file 'src/item.cpp' */ /* modified 2021-03-29T02:30:44, size 49486 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemAnchor //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemAnchor \brief An anchor of an item to which positions can be attached to. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't control anything on its item, but provides a way to tie other items via their positions to the anchor. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the QCPItemRect. This way the start of the line will now always follow the respective anchor location on the rect item. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an anchor to other positions. To learn how to provide anchors in your own item subclasses, see the subclassing section of the QCPAbstractItem documentation. */ /* start documentation of inline functions */ /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with gcc compiler). */ /* end documentation of inline functions */ /*! Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) : mName(name), mParentPlot(parentPlot), mParentItem(parentItem), mAnchorId(anchorId) { } QCPItemAnchor::~QCPItemAnchor() { // unregister as parent at children: foreach (QCPItemPosition *child, mChildrenX.values()) { if (child->parentAnchorX() == this) child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX } foreach (QCPItemPosition *child, mChildrenY.values()) { if (child->parentAnchorY() == this) child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY } } /*! Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPosition() const { if (mParentItem) { if (mAnchorId > -1) { return mParentItem->anchorPixelPosition(mAnchorId); } else { qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; return {}; } } else { qDebug() << Q_FUNC_INFO << "no parent item set"; return {}; } } /*! \internal Adds \a pos to the childX list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildX(QCPItemPosition *pos) { if (!mChildrenX.contains(pos)) mChildrenX.insert(pos); else qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); } /*! \internal Removes \a pos from the childX list of this anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) { if (!mChildrenX.remove(pos)) qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); } /*! \internal Adds \a pos to the childY list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildY(QCPItemPosition *pos) { if (!mChildrenY.contains(pos)) mChildrenY.insert(pos); else qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); } /*! \internal Removes \a pos from the childY list of this anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) { if (!mChildrenY.remove(pos)) qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPosition //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPosition \brief Manages the position of an item. Every item has at least one public QCPItemPosition member pointer which provides ways to position the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: \a topLeft and \a bottomRight. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as plot coordinates of certain axes (\ref QCPItemPosition::setAxes), as fractions of the axis rect (\ref QCPItemPosition::setAxisRect), etc. For more advanced plots it is also possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref setTypeY). This way an item could be positioned for example at a fixed pixel distance from the top in the Y direction, while following a plot coordinate in the X direction. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords) are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line always be centered under the text label, no matter where the text is moved to. For more advanced plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B in Y. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other positions. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified pixel values. */ /* start documentation of inline functions */ /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const Returns the current position type. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the type of the X coordinate. In that case rather use \a typeX() and \a typeY(). \see setType */ /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const Returns the current parent anchor. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), this method returns the parent anchor of the Y coordinate. In that case rather use \a parentAnchorX() and \a parentAnchorY(). \see setParentAnchor */ /* end documentation of inline functions */ /*! Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) : QCPItemAnchor(parentPlot, parentItem, name), mPositionTypeX(ptAbsolute), mPositionTypeY(ptAbsolute), mKey(0), mValue(0), mParentAnchorX(nullptr), mParentAnchorY(nullptr) { } QCPItemPosition::~QCPItemPosition() { // unregister as parent at children: // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then // the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition foreach (QCPItemPosition *child, mChildrenX.values()) { if (child->parentAnchorX() == this) child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX } foreach (QCPItemPosition *child, mChildrenY.values()) { if (child->parentAnchorY() == this) child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY } // unregister as child in parent: if (mParentAnchorX) mParentAnchorX->removeChildX(this); if (mParentAnchorY) mParentAnchorY->removeChildY(this); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPItemPosition::axisRect() const { return mAxisRect.data(); } /*! Sets the type of the position. The type defines how the coordinates passed to \ref setCoords should be handled and how the QCPItemPosition should behave in the plot. The possible values for \a type can be separated in two main categories: \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. By default, the QCustomPlot's x- and yAxis are used. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref ptAxisRectRatio. They differ only in the way the absolute position is described, see the documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position has no parent anchor (\ref setParentAnchor). If the type is changed, the apparent pixel position on the plot is preserved. This means the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. This method sets the type for both X and Y directions. It is also possible to set different types for X and Y, see \ref setTypeX, \ref setTypeY. */ void QCPItemPosition::setType(QCPItemPosition::PositionType type) { setTypeX(type); setTypeY(type); } /*! This method sets the position type of the X coordinate to \a type. For a detailed description of what a position type is, see the documentation of \ref setType. \see setType, setTypeY */ void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type) { if (mPositionTypeX != type) { // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning. bool retainPixelPosition = true; if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) retainPixelPosition = false; if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) retainPixelPosition = false; QPointF pixel; if (retainPixelPosition) pixel = pixelPosition(); mPositionTypeX = type; if (retainPixelPosition) setPixelPosition(pixel); } } /*! This method sets the position type of the Y coordinate to \a type. For a detailed description of what a position type is, see the documentation of \ref setType. \see setType, setTypeX */ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) { if (mPositionTypeY != type) { // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning. bool retainPixelPosition = true; if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) retainPixelPosition = false; if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) retainPixelPosition = false; QPointF pixel; if (retainPixelPosition) pixel = pixelPosition(); mPositionTypeY = type; if (retainPixelPosition) setPixelPosition(pixel); } } /*! Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position will be exactly on top of the parent anchor. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is set to \ref ptAbsolute, to keep the position in a valid state. This method sets the parent anchor for both X and Y directions. It is also possible to set different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. */ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); return successX && successY; } /*! This method sets the parent anchor of the X coordinate to \a parentAnchor. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. \see setParentAnchor, setParentAnchorY */ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { // make sure self is not assigned as parent: if (parentAnchor == this) { qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; } // make sure no recursive parent-child-relationships are created: QCPItemAnchor *currentParent = parentAnchor; while (currentParent) { if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { // is a QCPItemPosition, might have further parent, so keep iterating if (currentParentPos == this) { qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); return false; } currentParent = currentParentPos->parentAnchorX(); } else { // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the // same, to prevent a position being child of an anchor which itself depends on the position, // because they're both on the same item: if (currentParent->mParentItem == mParentItem) { qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); return false; } break; } } // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) setTypeX(ptAbsolute); // save pixel position: QPointF pixelP; if (keepPixelPosition) pixelP = pixelPosition(); // unregister at current parent anchor: if (mParentAnchorX) mParentAnchorX->removeChildX(this); // register at new parent anchor: if (parentAnchor) parentAnchor->addChildX(this); mParentAnchorX = parentAnchor; // restore pixel position under new parent: if (keepPixelPosition) setPixelPosition(pixelP); else setCoords(0, coords().y()); return true; } /*! This method sets the parent anchor of the Y coordinate to \a parentAnchor. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. \see setParentAnchor, setParentAnchorX */ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { // make sure self is not assigned as parent: if (parentAnchor == this) { qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; } // make sure no recursive parent-child-relationships are created: QCPItemAnchor *currentParent = parentAnchor; while (currentParent) { if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { // is a QCPItemPosition, might have further parent, so keep iterating if (currentParentPos == this) { qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); return false; } currentParent = currentParentPos->parentAnchorY(); } else { // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the // same, to prevent a position being child of an anchor which itself depends on the position, // because they're both on the same item: if (currentParent->mParentItem == mParentItem) { qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); return false; } break; } } // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) setTypeY(ptAbsolute); // save pixel position: QPointF pixelP; if (keepPixelPosition) pixelP = pixelPosition(); // unregister at current parent anchor: if (mParentAnchorY) mParentAnchorY->removeChildY(this); // register at new parent anchor: if (parentAnchor) parentAnchor->addChildY(this); mParentAnchorY = parentAnchor; // restore pixel position under new parent: if (keepPixelPosition) setPixelPosition(pixelP); else setCoords(coords().x(), 0); return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType, \ref setTypeX, \ref setTypeY). For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the plot coordinate system defined by the axes set by \ref setAxes. By default those are the QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available coordinate types and their meaning. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a value must also be provided in the different coordinate systems. Here, the X type refers to \a key, and the Y type refers to \a value. \see setPixelPosition */ void QCPItemPosition::setCoords(double key, double value) { mKey = key; mValue = value; } /*! \overload Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the meaning of \a value of the \ref setCoords(double key, double value) method. */ void QCPItemPosition::setCoords(const QPointF &pos) { setCoords(pos.x(), pos.y()); } /*! Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor). \see setPixelPosition */ QPointF QCPItemPosition::pixelPosition() const { QPointF result; // determine X: switch (mPositionTypeX) { case ptAbsolute: { result.rx() = mKey; if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPosition().x(); break; } case ptViewportRatio: { result.rx() = mKey*mParentPlot->viewport().width(); if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPosition().x(); else result.rx() += mParentPlot->viewport().left(); break; } case ptAxisRectRatio: { if (mAxisRect) { result.rx() = mKey*mAxisRect.data()->width(); if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPosition().x(); else result.rx() += mAxisRect.data()->left(); } else qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) result.rx() = mKeyAxis.data()->coordToPixel(mKey); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) result.rx() = mValueAxis.data()->coordToPixel(mValue); else qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; break; } } // determine Y: switch (mPositionTypeY) { case ptAbsolute: { result.ry() = mValue; if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPosition().y(); break; } case ptViewportRatio: { result.ry() = mValue*mParentPlot->viewport().height(); if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPosition().y(); else result.ry() += mParentPlot->viewport().top(); break; } case ptAxisRectRatio: { if (mAxisRect) { result.ry() = mValue*mAxisRect.data()->height(); if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPosition().y(); else result.ry() += mAxisRect.data()->top(); } else qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) result.ry() = mKeyAxis.data()->coordToPixel(mKey); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) result.ry() = mValueAxis.data()->coordToPixel(mValue); else qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; break; } } return result; } /*! When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and yAxis of the QCustomPlot. */ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) { mKeyAxis = keyAxis; mValueAxis = valueAxis; } /*! When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of the QCustomPlot. */ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) { mAxisRect = axisRect; } /*! Sets the apparent pixel position. This works no matter what type (\ref setType) this QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed appropriately, to make the position finally appear at the specified pixel values. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is identical to that of \ref setCoords. \see pixelPosition, setCoords */ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) { double x = pixelPosition.x(); double y = pixelPosition.y(); switch (mPositionTypeX) { case ptAbsolute: { if (mParentAnchorX) x -= mParentAnchorX->pixelPosition().x(); break; } case ptViewportRatio: { if (mParentAnchorX) x -= mParentAnchorX->pixelPosition().x(); else x -= mParentPlot->viewport().left(); x /= double(mParentPlot->viewport().width()); break; } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchorX) x -= mParentAnchorX->pixelPosition().x(); else x -= mAxisRect.data()->left(); x /= double(mAxisRect.data()->width()); } else qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) x = mKeyAxis.data()->pixelToCoord(x); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) y = mValueAxis.data()->pixelToCoord(x); else qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; break; } } switch (mPositionTypeY) { case ptAbsolute: { if (mParentAnchorY) y -= mParentAnchorY->pixelPosition().y(); break; } case ptViewportRatio: { if (mParentAnchorY) y -= mParentAnchorY->pixelPosition().y(); else y -= mParentPlot->viewport().top(); y /= double(mParentPlot->viewport().height()); break; } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchorY) y -= mParentAnchorY->pixelPosition().y(); else y -= mAxisRect.data()->top(); y /= double(mAxisRect.data()->height()); } else qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) x = mKeyAxis.data()->pixelToCoord(y); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) y = mValueAxis.data()->pixelToCoord(y); else qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; break; } } setCoords(x, y); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractItem \brief The abstract base class for all items in a plot. In QCustomPlot, items are supplemental graphical elements that are neither plottables (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each specific item has at least one QCPItemPosition member which controls the positioning. Some items are defined by more than one coordinate and thus have two or more QCPItemPosition members (For example, QCPItemRect has \a topLeft and \a bottomRight). This abstract base class defines a very basic interface like visibility and clipping. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new items. The built-in items are:
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemStraightLineA straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.
QCPItemCurveA curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).
QCPItemRectA rectangle
QCPItemEllipseAn ellipse
QCPItemPixmapAn arbitrary pixmap
QCPItemTextA text label
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
\section items-clipping Clipping Items are by default clipped to the main axis rect (they are only visible inside the axis rect). To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect "setClipToAxisRect(false)". On the other hand if you want the item to be clipped to a different axis rect, specify it via \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and in principle is independent of the coordinate axes the item might be tied to via its position members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping also contains the axes used for the item positions. \section items-using Using items First you instantiate the item you want to use and add it to the plot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1 by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just set the plot coordinates where the line should start/end: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2 If we don't want the line to be positioned in plot coordinates but a different coordinate system, e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3 Then we can set the coordinates, this time in pixels: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4 and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5 For more advanced plots, it is even possible to set different types and parent anchors per X/Y coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. \section items-subclassing Creating own items To create an own item, you implement a subclass of QCPAbstractItem. These are the pure virtual functions, you must implement: \li \ref selectTest \li \ref draw See the documentation of those functions for what they need to do. \subsection items-positioning Allowing the item to be positioned As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add a public member of type QCPItemPosition like so: \code QCPItemPosition * const myPosition;\endcode the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition instance it points to, can be modified, of course). The initialization of this pointer is made easy with the \ref createPosition function. Just assign the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a string which is the name of the position, typically this is identical to the variable name. For example, the constructor of QCPItemExample could look like this: \code QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), myPosition(createPosition("myPosition")) { // other constructor code } \endcode \subsection items-drawing The draw function To give your item a visual representation, reimplement the \ref draw function and use the passed QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the position member(s) via \ref QCPItemPosition::pixelPosition. To optimize performance you should calculate a bounding rect first (don't forget to take the pen width into account), check whether it intersects the \ref clipRect, and only draw the item at all if this is the case. \subsection items-selection The selectTest function Your implementation of the \ref selectTest function may use the helpers \ref QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the selection test becomes significantly simpler for most items. See the documentation of \ref selectTest for what the function parameters mean and what the function should return. \subsection anchors Providing anchors Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public member, e.g. \code QCPItemAnchor * const bottom;\endcode and create it in the constructor with the \ref createAnchor function, assigning it a name and an anchor id (an integer enumerating all anchors on the item, you may create an own enum for this). Since anchors can be placed anywhere, relative to the item's position(s), your item needs to provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int anchorId) function. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel position when anything attached to the anchor needs to know the coordinates. */ /* start of documentation of inline functions */ /*! \fn QList QCPAbstractItem::positions() const Returns all positions of the item in a list. \see anchors, position */ /*! \fn QList QCPAbstractItem::anchors() const Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always also an anchor, the list will also contain the positions of this item. \see positions, anchor */ /* end of documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 \internal Draws this item with the provided \a painter. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this function is called. The clipRect depends on the clipping settings defined by \ref setClipToAxisRect and \ref setClipAxisRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPAbstractItem::selectionChanged(bool selected) This signal is emitted when the selection state of this item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end documentation of signals */ /*! Base class constructor which initializes base class members. */ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), mClipToAxisRect(false), mSelectable(true), mSelected(false) { parentPlot->registerItem(this); QList rects = parentPlot->axisRects(); if (!rects.isEmpty()) { setClipToAxisRect(true); setClipAxisRect(rects.first()); } } QCPAbstractItem::~QCPAbstractItem() { // don't delete mPositions because every position is also an anchor and thus in mAnchors qDeleteAll(mAnchors); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPAbstractItem::clipAxisRect() const { return mClipAxisRect.data(); } /*! Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. \see setClipAxisRect */ void QCPAbstractItem::setClipToAxisRect(bool clip) { mClipToAxisRect = clip; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref setClipToAxisRect is set to true. \see setClipToAxisRect */ void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) { mClipAxisRect = rect; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected. \see QCustomPlot::setInteractions, setSelected */ void QCPAbstractItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this item is selected or not. When selected, it might use a different visual appearance (e.g. pen and brush), this depends on the specific item though. The entire selection mechanism for items is handled automatically when \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this function when you wish to change the selection state manually. This function can change the selection state even when \ref setSelectable was set to false. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /*! Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by that name, returns \c nullptr. This function provides an alternative way to access item positions. Normally, you access positions direcly by their member pointers (which typically have the same variable name as \a name). \see positions, anchor */ QCPItemPosition *QCPAbstractItem::position(const QString &name) const { foreach (QCPItemPosition *position, mPositions) { if (position->name() == name) return position; } qDebug() << Q_FUNC_INFO << "position with name not found:" << name; return nullptr; } /*! Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by that name, returns \c nullptr. This function provides an alternative way to access item anchors. Normally, you access anchors direcly by their member pointers (which typically have the same variable name as \a name). \see anchors, position */ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const { foreach (QCPItemAnchor *anchor, mAnchors) { if (anchor->name() == name) return anchor; } qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; return nullptr; } /*! Returns whether this item has an anchor with the specified \a name. Note that you can check for positions with this function, too. This is because every position is also an anchor (QCPItemPosition inherits from QCPItemAnchor). \see anchor, position */ bool QCPAbstractItem::hasAnchor(const QString &name) const { foreach (QCPItemAnchor *anchor, mAnchors) { if (anchor->name() == name) return true; } return false; } /*! \internal Returns the rect the visual representation of this item is clipped to. This depends on the current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect. If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned. \see draw */ QRect QCPAbstractItem::clipRect() const { if (mClipToAxisRect && mClipAxisRect) return mClipAxisRect.data()->rect(); else return mParentPlot->viewport(); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing item lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); } /*! \internal A convenience function which returns the selectTest value for a specified \a rect and a specified click position \a pos. \a filledRect defines whether a click inside the rect should also be considered a hit or whether only the rect border is sensitive to hits. This function may be used to help with the implementation of the \ref selectTest function for specific items. For example, if your item consists of four rects, call this function four times, once for each rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four returned values. */ double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const { double result = -1; // distance to border: const QList lines = QList() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); const QCPVector2D posVec(pos); double minDistSqr = (std::numeric_limits::max)(); foreach (const QLineF &line, lines) { double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2()); if (distSqr < minDistSqr) minDistSqr = distSqr; } result = qSqrt(minDistSqr); // filled rect, allow click inside to count as hit: if (filledRect && result > mParentPlot->selectionTolerance()*0.99) { if (rect.contains(pos)) result = mParentPlot->selectionTolerance()*0.99; } return result; } /*! \internal Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in item subclasses if they want to provide anchors (QCPItemAnchor). For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor ids and returns the respective pixel points of the specified anchor. \see createAnchor */ QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const { qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; return {}; } /*! \internal Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the position member (This is needed to provide the name-based \ref position access to positions). Don't delete positions created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each position member. Don't create QCPItemPositions with \b new yourself, because they won't be registered with the item properly. \see createAnchor */ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); mPositions.append(newPosition); mAnchors.append(newPosition); // every position is also an anchor newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); newPosition->setType(QCPItemPosition::ptPlotCoords); if (mParentPlot->axisRect()) newPosition->setAxisRect(mParentPlot->axisRect()); newPosition->setCoords(0, 0); return newPosition; } /*! \internal Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the anchor member (This is needed to provide the name based \ref anchor access to anchors). The \a anchorId must be a number identifying the created anchor. It is recommended to create an enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns the correct pixel coordinates for the passed anchor id. Don't delete anchors created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they won't be registered with the item properly. \see createPosition */ QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); mAnchors.append(newAnchor); return newAnchor; } /* inherits documentation from base class */ void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractItem::selectionCategory() const { return QCP::iSelectItems; } /* end of 'src/item.cpp' */ /* including file 'src/core.cpp' */ /* modified 2021-03-29T02:30:44, size 127198 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCustomPlot //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCustomPlot \brief The central class of the library. This is the QWidget which displays the plot and interacts with the user. For tutorials on how to use QCustomPlot, see the website\n http://www.qcustomplot.com/ */ /* start of documentation of inline functions */ /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used to handle and draw selection rect interactions (see \ref setSelectionRectMode). \see setSelectionRect */ /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse double click event. */ /*! \fn void QCustomPlot::mousePress(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse press event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. */ /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse move event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, because the dragging starting point was saved the moment the mouse was pressed. Thus it only has a meaning for the range drag axes that were set at that moment. If you want to change the drag axes, consider doing this in the \ref mousePress signal instead. */ /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse release event. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or \ref QCPAbstractPlottable::setSelectable. */ /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse wheel event. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. */ /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) This signal is emitted when a plottable is clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. The parameter \a dataIndex indicates the data point that was closest to the click position. \see plottableDoubleClick */ /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) This signal is emitted when a plottable is double clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. The parameter \a dataIndex indicates the data point that was closest to the click position. \see plottableClick */ /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemDoubleClick */ /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is double clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemClick */ /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisDoubleClick */ /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is double clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisClick */ /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space between two items. \see legendDoubleClick */ /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is double clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space between two items. \see legendClick */ /*! \fn void QCustomPlot::selectionChangedByUser() This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by clicking. It is not emitted when the selection state of an object has changed programmatically by a direct call to setSelected()/setSelection() on an object or by calling \ref deselectAll. In addition to this signal, selectable objects also provide individual signals, for example \ref QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals are emitted even if the selection state is changed programmatically. See the documentation of \ref setInteractions for details about the selection mechanism. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends */ /*! \fn void QCustomPlot::beforeReplot() This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, afterReplot, afterLayout */ /*! \fn void QCustomPlot::afterLayout() This signal is emitted immediately after the layout step has been completed, which occurs right before drawing the plot. This is typically during a call to \ref replot, and in such cases this signal is emitted in between the signals \ref beforeReplot and \ref afterReplot. Unlike those signals however, this signal is also emitted during off-screen painting, such as when calling \ref toPixmap or \ref savePdf. The layout step queries all layouts and layout elements in the plot for their proposed size and arranges the objects accordingly as preparation for the subsequent drawing step. Through this signal, you have the opportunity to update certain things in your plot that depend crucially on the exact dimensions/positioning of layout elements such as axes and axis rects. \warning However, changing any parameters of this QCustomPlot instance which would normally affect the layouting (e.g. axis range order of magnitudes, tick label sizes, etc.) will not issue a second run of the layout step. It will propagate directly to the draw step and may cause graphical inconsistencies such as overlapping objects, if sizes or positions have changed. \see updateLayout, beforeReplot, afterReplot */ /*! \fn void QCustomPlot::afterReplot() This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, beforeReplot, afterLayout */ /* end of documentation of signals */ /* start of documentation of public members */ /*! \var QCPAxis *QCustomPlot::xAxis A pointer to the primary x Axis (bottom) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become \c nullptr. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is added after the main legend was removed before. */ /*! \var QCPAxis *QCustomPlot::yAxis A pointer to the primary y Axis (left) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become \c nullptr. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is added after the main legend was removed before. */ /*! \var QCPAxis *QCustomPlot::xAxis2 A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become \c nullptr. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is added after the main legend was removed before. */ /*! \var QCPAxis *QCustomPlot::yAxis2 A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become \c nullptr. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is added after the main legend was removed before. */ /*! \var QCPLegend *QCustomPlot::legend A pointer to the default legend of the main axis rect. The legend is invisible by default. Use QCPLegend::setVisible to change this. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple legends to the plot, use the layout system interface to access the new legend. For example, legends can be placed inside an axis rect's \ref QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointer becomes \c nullptr. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is added after the main legend was removed before. */ /* end of documentation of public members */ /*! Constructs a QCustomPlot and sets reasonable default values. */ QCustomPlot::QCustomPlot(QWidget *parent) : QWidget(parent), xAxis(nullptr), yAxis(nullptr), xAxis2(nullptr), yAxis2(nullptr), legend(nullptr), mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below mPlotLayout(nullptr), mAutoAddPlottableToLegend(true), mAntialiasedElements(QCP::aeNone), mNotAntialiasedElements(QCP::aeNone), mInteractions(QCP::iNone), mSelectionTolerance(8), mNoAntialiasingOnDrag(false), mBackgroundBrush(Qt::white, Qt::SolidPattern), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mCurrentLayer(nullptr), mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh), mMultiSelectModifier(Qt::ControlModifier), mSelectionRectMode(QCP::srmNone), mSelectionRect(nullptr), mOpenGl(false), mMouseHasMoved(false), mMouseEventLayerable(nullptr), mMouseSignalLayerable(nullptr), mReplotting(false), mReplotQueued(false), mReplotTime(0), mReplotTimeAverage(0), mOpenGlMultisamples(16), mOpenGlAntialiasedElementsBackup(QCP::aeNone), mOpenGlCacheLabelsBackup(true) { setAttribute(Qt::WA_NoMousePropagation); setAttribute(Qt::WA_OpaquePaintEvent); setFocusPolicy(Qt::ClickFocus); setMouseTracking(true); QLocale currentLocale = locale(); currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); setLocale(currentLocale); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED # ifdef QCP_DEVICEPIXELRATIO_FLOAT setBufferDevicePixelRatio(QWidget::devicePixelRatioF()); # else setBufferDevicePixelRatio(QWidget::devicePixelRatio()); # endif #endif mOpenGlAntialiasedElementsBackup = mAntialiasedElements; mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels); // create initial layers: mLayers.append(new QCPLayer(this, QLatin1String("background"))); mLayers.append(new QCPLayer(this, QLatin1String("grid"))); mLayers.append(new QCPLayer(this, QLatin1String("main"))); mLayers.append(new QCPLayer(this, QLatin1String("axes"))); mLayers.append(new QCPLayer(this, QLatin1String("legend"))); mLayers.append(new QCPLayer(this, QLatin1String("overlay"))); updateLayerIndices(); setCurrentLayer(QLatin1String("main")); layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered); // create initial layout, axis rect and legend: mPlotLayout = new QCPLayoutGrid; mPlotLayout->initializeParentPlot(this); mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry mPlotLayout->setLayer(QLatin1String("main")); QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); mPlotLayout->addElement(0, 0, defaultAxisRect); xAxis = defaultAxisRect->axis(QCPAxis::atBottom); yAxis = defaultAxisRect->axis(QCPAxis::atLeft); xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); legend = new QCPLegend; legend->setVisible(false); defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); defaultAxisRect->setLayer(QLatin1String("background")); xAxis->setLayer(QLatin1String("axes")); yAxis->setLayer(QLatin1String("axes")); xAxis2->setLayer(QLatin1String("axes")); yAxis2->setLayer(QLatin1String("axes")); xAxis->grid()->setLayer(QLatin1String("grid")); yAxis->grid()->setLayer(QLatin1String("grid")); xAxis2->grid()->setLayer(QLatin1String("grid")); yAxis2->grid()->setLayer(QLatin1String("grid")); legend->setLayer(QLatin1String("legend")); // create selection rect instance: mSelectionRect = new QCPSelectionRect(this); mSelectionRect->setLayer(QLatin1String("overlay")); setViewport(rect()); // needs to be called after mPlotLayout has been created replot(rpQueuedReplot); } QCustomPlot::~QCustomPlot() { clearPlottables(); clearItems(); if (mPlotLayout) { delete mPlotLayout; mPlotLayout = nullptr; } mCurrentLayer = nullptr; qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed mLayers.clear(); } /*! Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is removed from there. \see setNotAntialiasedElements */ void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) { mAntialiasedElements = antialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. See \ref setAntialiasedElements for details. \see setNotAntialiasedElement */ void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) { if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements &= ~antialiasedElement; else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements |= antialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets which elements are forcibly drawn not antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is removed from there. \see setAntialiasedElements */ void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) { mNotAntialiasedElements = notAntialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. See \ref setNotAntialiasedElements for details. \see setAntialiasedElement */ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) { if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements &= ~notAntialiasedElement; else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements |= notAntialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the plottable to the legend (QCustomPlot::legend). \see addGraph, QCPLegend::addItem */ void QCustomPlot::setAutoAddPlottableToLegend(bool on) { mAutoAddPlottableToLegend = on; } /*! Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction enums. There are the following types of interactions: Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. For details how to control which axes the user may drag/zoom and in what orientations, see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, \ref QCPAxisRect::setRangeZoomAxes. Plottable data selection is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable and its data can further be restricted with the \ref QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the special page about the \ref dataselection "data selection mechanism". To retrieve a list of all currently selected plottables, call \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience function \ref selectedGraphs. Item selection is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of all currently selected items, call \ref selectedItems. Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may select the legend itself or individual items by clicking on them. What parts exactly are selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To find out which child items are selected, call \ref QCPLegend::selectedItems. All other selectable elements The selection of all other selectable objects (e.g. QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the user may select those objects by clicking on them. To find out which are currently selected, you need to check their selected state explicitly. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is emitted. Each selectable object additionally emits an individual selectionChanged signal whenever their selection state has changed, i.e. not only by user interaction. To allow multiple objects to be selected by holding the selection modifier (\ref setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. \note In addition to the selection mechanism presented here, QCustomPlot always emits corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and \ref plottableDoubleClick for example. \see setInteraction, setSelectionTolerance */ void QCustomPlot::setInteractions(const QCP::Interactions &interactions) { mInteractions = interactions; } /*! Sets the single \a interaction of this QCustomPlot to \a enabled. For details about the interaction system, see \ref setInteractions. \see setInteractions */ void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) { if (!enabled && mInteractions.testFlag(interaction)) mInteractions &= ~interaction; else if (enabled && !mInteractions.testFlag(interaction)) mInteractions |= interaction; } /*! Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or not. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a potential selection when the minimum distance between the click position and the graph line is smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks directly inside the area and ignore this selection tolerance. In other words, it only has meaning for parts of objects that are too thin to exactly hit with a click and thus need such a tolerance. \see setInteractions, QCPLayerable::selectTest */ void QCustomPlot::setSelectionTolerance(int pixels) { mSelectionTolerance = pixels; } /*! Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves performance during dragging. Thus it creates a more responsive user experience. As soon as the user stops dragging, the last replot is done with normal antialiasing, to restore high image quality. \see setAntialiasedElements, setNotAntialiasedElements */ void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) { mNoAntialiasingOnDrag = enabled; } /*! Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. \see setPlottingHint */ void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) { mPlottingHints = hints; } /*! Sets the specified plotting \a hint to \a enabled. \see setPlottingHints */ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) { QCP::PlottingHints newHints = mPlottingHints; if (!enabled) newHints &= ~hint; else newHints |= hint; if (newHints != mPlottingHints) setPlottingHints(newHints); } /*! Sets the keyboard modifier that will be recognized as multi-select-modifier. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects (or data points) by clicking on them one after the other while holding down \a modifier. By default the multi-select-modifier is set to Qt::ControlModifier. \see setInteractions */ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) { mMultiSelectModifier = modifier; } /*! Sets how QCustomPlot processes mouse click-and-drag interactions by the user. If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref selectionRect) becomes activated and allows e.g. rect zooming and data point selection. If you wish to provide your user both with axis range dragging and data selection/range zooming, use this method to switch between the modes just before the interaction is processed, e.g. in reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether the user is holding a certain keyboard modifier, and then decide which \a mode shall be set. If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes will keep the selection rect active. Upon completion of the interaction, the behaviour is as defined by the currently set \a mode, not the mode that was set when the interaction started. \see setInteractions, setSelectionRect, QCPSelectionRect */ void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode) { if (mSelectionRect) { if (mode == QCP::srmNone) mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect // disconnect old connections: if (mSelectionRectMode == QCP::srmSelect) disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*))); else if (mSelectionRectMode == QCP::srmZoom) disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*))); // establish new ones: if (mode == QCP::srmSelect) connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*))); else if (mode == QCP::srmZoom) connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*))); } mSelectionRectMode = mode; } /*! Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of the passed \a selectionRect. It can be accessed later via \ref selectionRect. This method is useful if you wish to replace the default QCPSelectionRect instance with an instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect. \see setSelectionRectMode */ void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect) { delete mSelectionRect; mSelectionRect = selectionRect; if (mSelectionRect) { // establish connections with new selection rect: if (mSelectionRectMode == QCP::srmSelect) connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*))); else if (mSelectionRectMode == QCP::srmZoom) connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*))); } } /*! \warning This is still an experimental feature and its performance depends on the system that it runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering might cause context conflicts on some systems. This method allows to enable OpenGL plot rendering, for increased plotting performance of graphically demanding plots (thick lines, translucent fills, etc.). If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful, continue plotting with hardware acceleration. The parameter \a multisampling controls how many samples will be used per pixel, it essentially controls the antialiasing quality. If \a multisampling is set too high for the current graphics hardware, the maximum allowed value will be used. You can test whether switching to OpenGL rendering was successful by checking whether the according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails, rendering continues with the regular software rasterizer, and an according qDebug output is generated. If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching settings are restored to what they were before OpenGL was enabled, if they weren't altered in the meantime. \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL defined. This define must be set before including the QCustomPlot header both during compilation of the QCustomPlot library as well as when compiling your application. It is best to just include the line DEFINES += QCUSTOMPLOT_USE_OPENGL in the respective qmake project files. \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a newer OpenGL interface which is already in the "gui" module. */ void QCustomPlot::setOpenGl(bool enabled, int multisampling) { mOpenGlMultisamples = qMax(0, multisampling); #ifdef QCUSTOMPLOT_USE_OPENGL mOpenGl = enabled; if (mOpenGl) { if (setupOpenGl()) { // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL mOpenGlAntialiasedElementsBackup = mAntialiasedElements; mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels); // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches): setAntialiasedElements(QCP::aeAll); setPlottingHint(QCP::phCacheLabels, false); } else { qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration."; mOpenGl = false; } } else { // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime: if (mAntialiasedElements == QCP::aeAll) setAntialiasedElements(mOpenGlAntialiasedElementsBackup); if (!mPlottingHints.testFlag(QCP::phCacheLabels)) setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup); freeOpenGl(); } // recreate all paint buffers: mPaintBuffers.clear(); setupPaintBuffers(); #else Q_UNUSED(enabled) qDebug() << Q_FUNC_INFO << "QCustomPlot can't use OpenGL because QCUSTOMPLOT_USE_OPENGL was not defined during compilation (add 'DEFINES += QCUSTOMPLOT_USE_OPENGL' to your qmake .pro file)"; #endif } /*! Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the viewport manually. The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin calculation take the viewport to be the outer border of the plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger and contains also the axes themselves, their tick numbers, their labels, or even additional axis rects, color scales and other layout elements. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref savePdf, etc. by temporarily changing the viewport size. */ void QCustomPlot::setViewport(const QRect &rect) { mViewport = rect; if (mPlotLayout) mPlotLayout->setOuterRect(mViewport); } /*! Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance. Normally, this doesn't need to be set manually, because it is initialized with the regular \a QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal displays, 2 for High-DPI displays). Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and leaves the internal buffer device pixel ratio at 1.0. */ void QCustomPlot::setBufferDevicePixelRatio(double ratio) { if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED mBufferDevicePixelRatio = ratio; foreach (QSharedPointer buffer, mPaintBuffers) buffer->setDevicePixelRatio(mBufferDevicePixelRatio); // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here #else qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; mBufferDevicePixelRatio = 1.0; #endif } } /*! Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn below all other objects in the plot. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will first be filled with that brush, before drawing the background pixmap. This can be useful for background pixmaps with translucent areas. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! Sets the background brush of the viewport (see \ref setViewport). Before drawing everything else, the background is filled with \a brush. If a background pixmap was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport before the background pixmap is drawn. This can be useful for background pixmaps with translucent areas. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be useful for exporting to image formats which support transparency, e.g. \ref savePng. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the viewport, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is set to true, control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the viewport dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCustomPlot::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap is preserved. \see setBackground, setBackgroundScaled */ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the plottable with \a index. If the index is invalid, returns \c nullptr. There is an overloaded version of this function with no parameter which returns the last added plottable, see QCustomPlot::plottable() \see plottableCount */ QCPAbstractPlottable *QCustomPlot::plottable(int index) { if (index >= 0 && index < mPlottables.size()) { return mPlottables.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return nullptr; } } /*! \overload Returns the last plottable that was added to the plot. If there are no plottables in the plot, returns \c nullptr. \see plottableCount */ QCPAbstractPlottable *QCustomPlot::plottable() { if (!mPlottables.isEmpty()) { return mPlottables.last(); } else return nullptr; } /*! Removes the specified plottable from the plot and deletes it. If necessary, the corresponding legend item is also removed from the default legend (QCustomPlot::legend). Returns true on success. \see clearPlottables */ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) { if (!mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); return false; } // remove plottable from legend: plottable->removeFromLegend(); // special handling for QCPGraphs to maintain the simple graph interface: if (QCPGraph *graph = qobject_cast(plottable)) mGraphs.removeOne(graph); // remove plottable: delete plottable; mPlottables.removeOne(plottable); return true; } /*! \overload Removes and deletes the plottable by its \a index. */ bool QCustomPlot::removePlottable(int index) { if (index >= 0 && index < mPlottables.size()) return removePlottable(mPlottables[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all plottables from the plot and deletes them. Corresponding legend items are also removed from the default legend (QCustomPlot::legend). Returns the number of plottables removed. \see removePlottable */ int QCustomPlot::clearPlottables() { int c = mPlottables.size(); for (int i=c-1; i >= 0; --i) removePlottable(mPlottables[i]); return c; } /*! Returns the number of currently existing plottables in the plot \see plottable */ int QCustomPlot::plottableCount() const { return mPlottables.size(); } /*! Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection */ QList QCustomPlot::selectedPlottables() const { QList result; foreach (QCPAbstractPlottable *plottable, mPlottables) { if (plottable->selected()) result.append(plottable); } return result; } /*! Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the return type is the abstract base class of all plottables, QCPAbstractPlottable. For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the template method plottableAt() \see plottableAt(), itemAt, layoutElementAt */ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const { return plottableAt(pos, onlySelectable, dataIndex); } /*! Returns whether this QCustomPlot instance contains the \a plottable. */ bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const { return mPlottables.contains(plottable); } /*! Returns the graph with \a index. If the index is invalid, returns \c nullptr. There is an overloaded version of this function with no parameter which returns the last created graph, see QCustomPlot::graph() \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph(int index) const { if (index >= 0 && index < mGraphs.size()) { return mGraphs.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return nullptr; } } /*! \overload Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, returns \c nullptr. \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph() const { if (!mGraphs.isEmpty()) { return mGraphs.last(); } else return nullptr; } /*! Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a keyAxis and \a valueAxis must reside in this QCustomPlot. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically "y") for the graph. Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed. \see graph, graphCount, removeGraph, clearGraphs */ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) { if (!keyAxis) keyAxis = xAxis; if (!valueAxis) valueAxis = yAxis; if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; return nullptr; } if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; return nullptr; } QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size())); return newGraph; } /*! Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in the plot have a channel fill set towards the removed graph, the channel fill property of those graphs is reset to \c nullptr (no channel fill). Returns true on success. \see clearGraphs */ bool QCustomPlot::removeGraph(QCPGraph *graph) { return removePlottable(graph); } /*! \overload Removes and deletes the graph by its \a index. */ bool QCustomPlot::removeGraph(int index) { if (index >= 0 && index < mGraphs.size()) return removeGraph(mGraphs[index]); else return false; } /*! Removes all graphs from the plot and deletes them. Corresponding legend items are also removed from the default legend (QCustomPlot::legend). Returns the number of graphs removed. \see removeGraph */ int QCustomPlot::clearGraphs() { int c = mGraphs.size(); for (int i=c-1; i >= 0; --i) removeGraph(mGraphs[i]); return c; } /*! Returns the number of currently existing graphs in the plot \see graph, addGraph */ int QCustomPlot::graphCount() const { return mGraphs.size(); } /*! Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars, etc., use \ref selectedPlottables. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection */ QList QCustomPlot::selectedGraphs() const { QList result; foreach (QCPGraph *graph, mGraphs) { if (graph->selected()) result.append(graph); } return result; } /*! Returns the item with \a index. If the index is invalid, returns \c nullptr. There is an overloaded version of this function with no parameter which returns the last added item, see QCustomPlot::item() \see itemCount */ QCPAbstractItem *QCustomPlot::item(int index) const { if (index >= 0 && index < mItems.size()) { return mItems.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return nullptr; } } /*! \overload Returns the last item that was added to this plot. If there are no items in the plot, returns \c nullptr. \see itemCount */ QCPAbstractItem *QCustomPlot::item() const { if (!mItems.isEmpty()) { return mItems.last(); } else return nullptr; } /*! Removes the specified item from the plot and deletes it. Returns true on success. \see clearItems */ bool QCustomPlot::removeItem(QCPAbstractItem *item) { if (mItems.contains(item)) { delete item; mItems.removeOne(item); return true; } else { qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); return false; } } /*! \overload Removes and deletes the item by its \a index. */ bool QCustomPlot::removeItem(int index) { if (index >= 0 && index < mItems.size()) return removeItem(mItems[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all items from the plot and deletes them. Returns the number of items removed. \see removeItem */ int QCustomPlot::clearItems() { int c = mItems.size(); for (int i=c-1; i >= 0; --i) removeItem(mItems[i]); return c; } /*! Returns the number of currently existing items in the plot \see item */ int QCustomPlot::itemCount() const { return mItems.size(); } /*! Returns a list of the selected items. If no items are currently selected, the list is empty. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected */ QList QCustomPlot::selectedItems() const { QList result; foreach (QCPAbstractItem *item, mItems) { if (item->selected()) result.append(item); } return result; } /*! Returns the item at the pixel position \a pos. Since it can capture all items, the return type is the abstract base class of all items, QCPAbstractItem. For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the template method itemAt() \see itemAt(), plottableAt, layoutElementAt */ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { return itemAt(pos, onlySelectable); } /*! Returns whether this QCustomPlot contains the \a item. \see item */ bool QCustomPlot::hasItem(QCPAbstractItem *item) const { return mItems.contains(item); } /*! Returns the layer with the specified \a name. If there is no layer with the specified name, \c nullptr is returned. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(const QString &name) const { foreach (QCPLayer *layer, mLayers) { if (layer->name() == name) return layer; } return nullptr; } /*! \overload Returns the layer by \a index. If the index is invalid, \c nullptr is returned. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(int index) const { if (index >= 0 && index < mLayers.size()) { return mLayers.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return nullptr; } } /*! Returns the layer that is set as current layer (see \ref setCurrentLayer). */ QCPLayer *QCustomPlot::currentLayer() const { return mCurrentLayer; } /*! Sets the layer with the specified \a name to be the current layer. All layerables (\ref QCPLayerable), e.g. plottables and items, are created on the current layer. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer */ bool QCustomPlot::setCurrentLayer(const QString &name) { if (QCPLayer *newCurrentLayer = layer(name)) { return setCurrentLayer(newCurrentLayer); } else { qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; return false; } } /*! \overload Sets the provided \a layer to be the current layer. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. \see addLayer, moveLayer, removeLayer */ bool QCustomPlot::setCurrentLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } mCurrentLayer = layer; return true; } /*! Returns the number of currently existing layers in the plot \see layer, addLayer */ int QCustomPlot::layerCount() const { return mLayers.size(); } /*! Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a valid layer inside this QCustomPlot. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. \see layer, moveLayer, removeLayer */ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!otherLayer) otherLayer = mLayers.last(); if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); return false; } if (layer(name)) { qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; return false; } QCPLayer *newLayer = new QCPLayer(this, name); mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); updateLayerIndices(); setupPaintBuffers(); // associates new layer with the appropriate paint buffer return true; } /*! Removes the specified \a layer and returns true on success. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both cases, the total rendering order of all layerables in the QCustomPlot is preserved. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom layer) becomes the new current layer. It is not possible to remove the last layer of the plot. \see layer, addLayer, moveLayer */ bool QCustomPlot::removeLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } if (mLayers.size() < 2) { qDebug() << Q_FUNC_INFO << "can't remove last layer"; return false; } // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) int removedIndex = layer->index(); bool isFirstLayer = removedIndex==0; QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); QList children = layer->children(); if (isFirstLayer) // prepend in reverse order (such that relative order stays the same) std::reverse(children.begin(), children.end()); foreach (QCPLayerable *child, children) child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append // if removed layer is current layer, change current layer to layer below/above: if (layer == mCurrentLayer) setCurrentLayer(targetLayer); // invalidate the paint buffer that was responsible for this layer: if (QSharedPointer pb = layer->mPaintBuffer.toStrongRef()) pb->setInvalidated(); // remove layer: delete layer; mLayers.removeOne(layer); updateLayerIndices(); return true; } /*! Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or below is controlled with \a insertMode. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the QCustomPlot. \see layer, addLayer, moveLayer */ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); return false; } if (layer->index() > otherLayer->index()) mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); else if (layer->index() < otherLayer->index()) mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1)); // invalidate the paint buffers that are responsible for the layers: if (QSharedPointer pb = layer->mPaintBuffer.toStrongRef()) pb->setInvalidated(); if (QSharedPointer pb = otherLayer->mPaintBuffer.toStrongRef()) pb->setInvalidated(); updateLayerIndices(); return true; } /*! Returns the number of axis rects in the plot. All axis rects can be accessed via QCustomPlot::axisRect(). Initially, only one axis rect exists in the plot. \see axisRect, axisRects */ int QCustomPlot::axisRectCount() const { return axisRects().size(); } /*! Returns the axis rect with \a index. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were added, all of them may be accessed with this function in a linear fashion (even when they are nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding them. For example, if the axis rects are in the top level grid layout (accessible via \ref QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst "foColumnsFirst" wasn't changed. If you want to access axis rects by their row and column index, use the layout interface. For example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.) \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder */ QCPAxisRect *QCustomPlot::axisRect(int index) const { const QList rectList = axisRects(); if (index >= 0 && index < rectList.size()) { return rectList.at(index); } else { qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; return nullptr; } } /*! Returns all axis rects in the plot. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding them. For example, if the axis rects are in the top level grid layout (accessible via \ref QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst "foColumnsFirst" wasn't changed. \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder */ QList QCustomPlot::axisRects() const { QList result; QStack elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) { if (element) { elementStack.push(element); if (QCPAxisRect *ar = qobject_cast(element)) result.append(ar); } } } return result; } /*! Returns the layout element at pixel position \a pos. If there is no element at that position, returns \c nullptr. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on any of its parent elements is set to false, it will not be considered. \see itemAt, plottableAt */ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const { QCPLayoutElement *currentElement = mPlotLayout; bool searchSubElements = true; while (searchSubElements && currentElement) { searchSubElements = false; foreach (QCPLayoutElement *subElement, currentElement->elements(false)) { if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) { currentElement = subElement; searchSubElements = true; break; } } } return currentElement; } /*! Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores other layout elements even if they are visually in front of the axis rect (e.g. a \ref QCPLegend). If there is no axis rect at that position, returns \c nullptr. Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or on any of its parent elements is set to false, it will not be considered. \see layoutElementAt */ QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const { QCPAxisRect *result = nullptr; QCPLayoutElement *currentElement = mPlotLayout; bool searchSubElements = true; while (searchSubElements && currentElement) { searchSubElements = false; foreach (QCPLayoutElement *subElement, currentElement->elements(false)) { if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) { currentElement = subElement; searchSubElements = true; if (QCPAxisRect *ar = qobject_cast(currentElement)) result = ar; break; } } } return result; } /*! Returns the axes that currently have selected parts, i.e. whose selection state is not \ref QCPAxis::spNone. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ QList QCustomPlot::selectedAxes() const { QList result, allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) { if (axis->selectedParts() != QCPAxis::spNone) result.append(axis); } return result; } /*! Returns the legends that currently have selected parts, i.e. whose selection state is not \ref QCPLegend::spNone. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ QList QCustomPlot::selectedLegends() const { QList result; QStack elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) { if (subElement) { elementStack.push(subElement); if (QCPLegend *leg = qobject_cast(subElement)) { if (leg->selectedParts() != QCPLegend::spNone) result.append(leg); } } } } return result; } /*! Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. Since calling this function is not a user interaction, this does not emit the \ref selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the objects were previously selected. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends */ void QCustomPlot::deselectAll() { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) layerable->deselectEvent(nullptr); } } /*! Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is refreshed with the new buffer contents. This is the method that must be called to make changes to the plot, e.g. on the axis ranges or data points of graphs, visible. The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example if your application calls \ref replot very quickly in succession (e.g. multiple independent functions change some aspects of the plot and each wants to make sure the change gets replotted), it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref replot with this priority will only cause a single replot, avoiding redundant replots and improving performance. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the QCustomPlot widget and user interactions (object selection and range dragging/zooming). Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to replot only that specific layer via \ref QCPLayer::replot. See the documentation there for details. \see replotTime */ void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) { if (refreshPriority == QCustomPlot::rpQueuedReplot) { if (!mReplotQueued) { mReplotQueued = true; QTimer::singleShot(0, this, SLOT(replot())); } return; } if (mReplotting) // incase signals loop back to replot slot return; mReplotting = true; mReplotQueued = false; emit beforeReplot(); # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0) QTime replotTimer; replotTimer.start(); # else QElapsedTimer replotTimer; replotTimer.start(); # endif updateLayout(); // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers: setupPaintBuffers(); foreach (QCPLayer *layer, mLayers) layer->drawToPaintBuffer(); foreach (QSharedPointer buffer, mPaintBuffers) buffer->setInvalidated(false); if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh) repaint(); else update(); # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0) mReplotTime = replotTimer.elapsed(); # else mReplotTime = replotTimer.nsecsElapsed()*1e-6; # endif if (!qFuzzyIsNull(mReplotTimeAverage)) mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots else mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time emit afterReplot(); mReplotting = false; } /*! Returns the time in milliseconds that the last replot took. If \a average is set to true, an exponential moving average over the last couple of replots is returned. \see replot */ double QCustomPlot::replotTime(bool average) const { return average ? mReplotTimeAverage : mReplotTime; } /*! Rescales the axes such that all plottables (like graphs) in the plot are fully visible. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true (QCPLayerable::setVisible), will be used to rescale the axes. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale */ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) { QList allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) axis->rescale(onlyVisiblePlottables); } /*! Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale of texts and lines will be derived from the specified \a width and \a height. This means, the output will look like the normal on-screen output of a QCustomPlot widget with the corresponding pixel width and height. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter and QPen documentation. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. Returns true on success. \warning \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks). \li If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting PDF file. \note On Android systems, this method does nothing and issues an according qDebug warning message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set. \see savePng, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle) { bool success = false; #ifdef QT_NO_PRINTER Q_UNUSED(fileName) Q_UNUSED(exportPen) Q_UNUSED(width) Q_UNUSED(height) Q_UNUSED(pdfCreator) Q_UNUSED(pdfTitle) qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; #else int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } QPrinter printer(QPrinter::ScreenResolution); printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); printer.setColorMode(QPrinter::Color); printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) printer.setFullPage(true); printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); #else QPageLayout pageLayout; pageLayout.setMode(QPageLayout::FullPageMode); pageLayout.setOrientation(QPageLayout::Portrait); pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); printer.setPageLayout(pageLayout); #endif QCPPainter printpainter; if (printpainter.begin(&printer)) { printpainter.setMode(QCPPainter::pmVectorized); printpainter.setMode(QCPPainter::pmNoCaching); printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic); printpainter.setWindow(mViewport); if (mBackgroundBrush.style() != Qt::NoBrush && mBackgroundBrush.color() != Qt::white && mBackgroundBrush.color() != Qt::transparent && mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent printpainter.fillRect(viewport(), mBackgroundBrush); draw(&printpainter); printpainter.end(); success = true; } setViewport(oldViewport); #endif // QT_NO_PRINTER return success; } /*! Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the current width and height of the QCustomPlot widget is used instead. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. image compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. The \a resolution will be written to the image file header and has no direct consequence for the quality or the pixel size. However, if opening the image with a tool which respects the metadata, it will be able to scale the image to match either a given size in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected resolution unit internally. Returns true on success. If this function fails, most likely the PNG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. \see savePdf, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit) { return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit); } /*! Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the current width and height of the QCustomPlot widget is used instead. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. image compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. The \a resolution will be written to the image file header and has no direct consequence for the quality or the pixel size. However, if opening the image with a tool which respects the metadata, it will be able to scale the image to match either a given size in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected resolution unit internally. Returns true on success. If this function fails, most likely the JPEG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. \see savePdf, savePng, saveBmp, saveRastered */ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit) { return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit); } /*! Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the current width and height of the QCustomPlot widget is used instead. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. The \a resolution will be written to the image file header and has no direct consequence for the quality or the pixel size. However, if opening the image with a tool which respects the metadata, it will be able to scale the image to match either a given size in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected resolution unit internally. Returns true on success. If this function fails, most likely the BMP format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. \see savePdf, savePng, saveJpg, saveRastered */ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit) { return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit); } /*! \internal Returns a minimum size hint that corresponds to the minimum size of the top level layout (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. This is especially important, when placed in a QLayout where other components try to take in as much space as possible (e.g. QMdiArea). */ QSize QCustomPlot::minimumSizeHint() const { return mPlotLayout->minimumOuterSizeHint(); } /*! \internal Returns a size hint that is the same as \ref minimumSizeHint. */ QSize QCustomPlot::sizeHint() const { return mPlotLayout->minimumOuterSizeHint(); } /*! \internal Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but draws the internal buffer on the widget surface. */ void QCustomPlot::paintEvent(QPaintEvent *event) { Q_UNUSED(event) QCPPainter painter(this); if (painter.isActive()) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem #endif if (mBackgroundBrush.style() != Qt::NoBrush) painter.fillRect(mViewport, mBackgroundBrush); drawBackground(&painter); foreach (QSharedPointer buffer, mPaintBuffers) buffer->draw(&painter); } } /*! \internal Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect of mPlotLayout) is resized appropriately. Finally a \ref replot is performed. */ void QCustomPlot::resizeEvent(QResizeEvent *event) { Q_UNUSED(event) // resize and repaint the buffer: setViewport(rect()); replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow) } /*! \internal Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then determines the layerable under the cursor and forwards the event to it. Finally, emits the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref axisDoubleClick, etc.). \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) { emit mouseDoubleClick(event); mMouseHasMoved = false; mMousePressPos = event->pos(); // determine layerable under the cursor (this event is called instead of the second press event in a double-click): QList details; QList candidates = layerableListAt(mMousePressPos, false, &details); for (int i=0; iaccept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list candidates.at(i)->mouseDoubleClickEvent(event, details.at(i)); if (event->isAccepted()) { mMouseEventLayerable = candidates.at(i); mMouseEventLayerableDetails = details.at(i); break; } } // emit specialized object double click signals: if (!candidates.isEmpty()) { if (QCPAbstractPlottable *ap = qobject_cast(candidates.first())) { int dataIndex = 0; if (!details.first().value().isEmpty()) dataIndex = details.first().value().dataRange().begin(); emit plottableDoubleClick(ap, dataIndex, event); } else if (QCPAxis *ax = qobject_cast(candidates.first())) emit axisDoubleClick(ax, details.first().value(), event); else if (QCPAbstractItem *ai = qobject_cast(candidates.first())) emit itemDoubleClick(ai, event); else if (QCPLegend *lg = qobject_cast(candidates.first())) emit legendDoubleClick(lg, nullptr, event); else if (QCPAbstractLegendItem *li = qobject_cast(candidates.first())) emit legendDoubleClick(li->parentLegend(), li, event); } event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal Event handler for when a mouse button is pressed. Emits the mousePress signal. If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the selection rect. Otherwise determines the layerable under the cursor and forwards the event to it. \see mouseMoveEvent, mouseReleaseEvent */ void QCustomPlot::mousePressEvent(QMouseEvent *event) { emit mousePress(event); // save some state to tell in releaseEvent whether it was a click: mMouseHasMoved = false; mMousePressPos = event->pos(); if (mSelectionRect && mSelectionRectMode != QCP::srmNone) { if (mSelectionRectMode != QCP::srmZoom || qobject_cast(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect mSelectionRect->startSelection(event); } else { // no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor: QList details; QList candidates = layerableListAt(mMousePressPos, false, &details); if (!candidates.isEmpty()) { mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event) mMouseSignalLayerableDetails = details.first(); } // forward event to topmost candidate which accepts the event: for (int i=0; iaccept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list candidates.at(i)->mousePressEvent(event, details.at(i)); if (event->isAccepted()) { mMouseEventLayerable = candidates.at(i); mMouseEventLayerableDetails = details.at(i); break; } } } event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal Event handler for when the cursor is moved. Emits the \ref mouseMove signal. If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it in order to update the rect geometry. Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the layout element before), the mouseMoveEvent is forwarded to that element. \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseMoveEvent(QMouseEvent *event) { emit mouseMove(event); if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3) mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release if (mSelectionRect && mSelectionRect->isActive()) mSelectionRect->moveSelection(event); else if (mMouseEventLayerable) // call event of affected layerable: mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos); event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. If the mouse was moved less than a certain threshold in any direction since the \ref mousePressEvent, it is considered a click which causes the selection mechanism (if activated via \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.) If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable before), the \ref mouseReleaseEvent is forwarded to that element. \see mousePressEvent, mouseMoveEvent */ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) { emit mouseRelease(event); if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click { if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here mSelectionRect->cancel(); if (event->button() == Qt::LeftButton) processPointSelection(event); // emit specialized click signals of QCustomPlot instance: if (QCPAbstractPlottable *ap = qobject_cast(mMouseSignalLayerable)) { int dataIndex = 0; if (!mMouseSignalLayerableDetails.value().isEmpty()) dataIndex = mMouseSignalLayerableDetails.value().dataRange().begin(); emit plottableClick(ap, dataIndex, event); } else if (QCPAxis *ax = qobject_cast(mMouseSignalLayerable)) emit axisClick(ax, mMouseSignalLayerableDetails.value(), event); else if (QCPAbstractItem *ai = qobject_cast(mMouseSignalLayerable)) emit itemClick(ai, event); else if (QCPLegend *lg = qobject_cast(mMouseSignalLayerable)) emit legendClick(lg, nullptr, event); else if (QCPAbstractLegendItem *li = qobject_cast(mMouseSignalLayerable)) emit legendClick(li->parentLegend(), li, event); mMouseSignalLayerable = nullptr; } if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there { // finish selection rect, the appropriate action will be taken via signal-slot connection: mSelectionRect->endSelection(event); } else { // call event of affected layerable: if (mMouseEventLayerable) { mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos); mMouseEventLayerable = nullptr; } } if (noAntialiasingOnDrag()) replot(rpQueuedReplot); event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then determines the affected layerable and forwards the event to it. */ void QCustomPlot::wheelEvent(QWheelEvent *event) { emit mouseWheel(event); #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) const QPointF pos = event->pos(); #else const QPointF pos = event->position(); #endif // forward event to layerable under cursor: foreach (QCPLayerable *candidate, layerableListAt(pos, false)) { event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list candidate->wheelEvent(event); if (event->isAccepted()) break; } event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal This function draws the entire plot, including background pixmap, with the specified \a painter. It does not make use of the paint buffers like \ref replot, so this is the function typically used by saving/exporting methods such as \ref savePdf or \ref toPainter. Note that it does not fill the background with the background brush (as the user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this method. */ void QCustomPlot::draw(QCPPainter *painter) { updateLayout(); // draw viewport background pixmap: drawBackground(painter); // draw all layered objects (grid, axes, plottables, items, legend,...): foreach (QCPLayer *layer, mLayers) layer->draw(painter); /* Debug code to draw all layout element rects foreach (QCPLayoutElement *el, findChildren()) { painter->setBrush(Qt::NoBrush); painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->rect()); painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->outerRect()); } */ } /*! \internal Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref QCPLayoutElement::update on the main plot layout. Here, the layout elements calculate their positions and margins, and prepare for the following draw call. */ void QCustomPlot::updateLayout() { // run through layout phases: mPlotLayout->update(QCPLayoutElement::upPreparation); mPlotLayout->update(QCPLayoutElement::upMargins); mPlotLayout->update(QCPLayoutElement::upLayout); emit afterLayout(); } /*! \internal Draws the viewport background pixmap of the plot. If a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the viewport with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. Note that this function does not draw a fill with the background brush (\ref setBackground(const QBrush &brush)) beneath the pixmap. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::drawBackground(QCPPainter *painter) { // Note: background color is handled in individual replot/save functions // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mViewport.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); } } } /*! \internal Goes through the layers and makes sure this QCustomPlot instance holds the correct number of paint buffers and that they have the correct configuration (size, pixel ratio, etc.). Allocations, reallocations and deletions of paint buffers are performed as necessary. It also associates the paint buffers with the layers, so they draw themselves into the right buffer when \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for layers in \ref QCPLayer::lmBuffered mode. This method uses \ref createPaintBuffer to create new paint buffers. After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated (so an attempt to replot only a single buffered layer causes a full replot). This method is called in every \ref replot call, prior to actually drawing the layers (into their associated paint buffer). If the paint buffers don't need changing/reallocating, this method basically leaves them alone and thus finishes very fast. */ void QCustomPlot::setupPaintBuffers() { int bufferIndex = 0; if (mPaintBuffers.isEmpty()) mPaintBuffers.append(QSharedPointer(createPaintBuffer())); for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex) { QCPLayer *layer = mLayers.at(layerIndex); if (layer->mode() == QCPLayer::lmLogical) { layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef(); } else if (layer->mode() == QCPLayer::lmBuffered) { ++bufferIndex; if (bufferIndex >= mPaintBuffers.size()) mPaintBuffers.append(QSharedPointer(createPaintBuffer())); layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef(); if (layerIndex < mLayers.size()-1 && mLayers.at(layerIndex+1)->mode() == QCPLayer::lmLogical) // not last layer, and next one is logical, so prepare another buffer for next layerables { ++bufferIndex; if (bufferIndex >= mPaintBuffers.size()) mPaintBuffers.append(QSharedPointer(createPaintBuffer())); } } } // remove unneeded buffers: while (mPaintBuffers.size()-1 > bufferIndex) mPaintBuffers.removeLast(); // resize buffers to viewport size and clear contents: foreach (QSharedPointer buffer, mPaintBuffers) { buffer->setSize(viewport().size()); // won't do anything if already correct size buffer->clear(Qt::transparent); buffer->setInvalidated(); } } /*! \internal This method is used by \ref setupPaintBuffers when it needs to create new paint buffers. Depending on the current setting of \ref setOpenGl, and the current Qt version, different backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper size and device pixel ratio, and returned. */ QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer() { if (mOpenGl) { #if defined(QCP_OPENGL_FBO) return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice); #elif defined(QCP_OPENGL_PBUFFER) return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples); #else qDebug() << Q_FUNC_INFO << "OpenGL enabled even though no support for it compiled in, this shouldn't have happened. Falling back to pixmap paint buffer."; return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio); #endif } else return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio); } /*! This method returns whether any of the paint buffers held by this QCustomPlot instance are invalidated. If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example the layer order has changed, new layers were added or removed, layer modes were changed (\ref QCPLayer::setMode), or layerables were added or removed. \see QCPAbstractPaintBuffer::setInvalidated */ bool QCustomPlot::hasInvalidatedPaintBuffers() { foreach (QSharedPointer buffer, mPaintBuffers) { if (buffer->invalidated()) return true; } return false; } /*! \internal When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context, surface, paint device). Returns true on success. If this method is successful, all paint buffers should be deleted and then reallocated by calling \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots. \see freeOpenGl */ bool QCustomPlot::setupOpenGl() { #ifdef QCP_OPENGL_FBO freeOpenGl(); QSurfaceFormat proposedSurfaceFormat; proposedSurfaceFormat.setSamples(mOpenGlMultisamples); #ifdef QCP_OPENGL_OFFSCREENSURFACE QOffscreenSurface *surface = new QOffscreenSurface; #else QWindow *surface = new QWindow; surface->setSurfaceType(QSurface::OpenGLSurface); #endif surface->setFormat(proposedSurfaceFormat); surface->create(); mGlSurface = QSharedPointer(surface); mGlContext = QSharedPointer(new QOpenGLContext); mGlContext->setFormat(mGlSurface->format()); if (!mGlContext->create()) { qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context"; mGlContext.clear(); mGlSurface.clear(); return false; } if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device { qDebug() << Q_FUNC_INFO << "Failed to make opengl context current"; mGlContext.clear(); mGlSurface.clear(); return false; } if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()) { qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects"; mGlContext.clear(); mGlSurface.clear(); return false; } mGlPaintDevice = QSharedPointer(new QOpenGLPaintDevice); return true; #elif defined(QCP_OPENGL_PBUFFER) return QGLFormat::hasOpenGL(); #else return false; #endif } /*! \internal When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the context and frees resources). After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref QCPPaintBufferPixmap) is used for subsequent replots. \see setupOpenGl */ void QCustomPlot::freeOpenGl() { #ifdef QCP_OPENGL_FBO mGlPaintDevice.clear(); mGlContext.clear(); mGlSurface.clear(); #endif } /*! \internal This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. */ void QCustomPlot::axisRemoved(QCPAxis *axis) { if (xAxis == axis) xAxis = nullptr; if (xAxis2 == axis) xAxis2 = nullptr; if (yAxis == axis) yAxis = nullptr; if (yAxis2 == axis) yAxis2 = nullptr; // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers } /*! \internal This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so it may clear its QCustomPlot::legend member accordingly. */ void QCustomPlot::legendRemoved(QCPLegend *legend) { if (this->legend == legend) this->legend = nullptr; } /*! \internal This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref setSelectionRectMode is set to \ref QCP::srmSelect. First, it determines which axis rect was the origin of the selection rect judging by the starting point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be precise) associated with that axis rect and finds the data points that are in \a rect. It does this by querying their \ref QCPAbstractPlottable1D::selectTestRect method. Then, the actual selection is done by calling the plottables' \ref QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details parameter as QVariant(\ref QCPDataSelection). All plottables that weren't touched by \a rect receive a \ref QCPAbstractPlottable::deselectEvent. \see processRectZoom */ void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event) { typedef QPair SelectionCandidate; typedef QMultiMap SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size bool selectionStateChanged = false; if (mInteractions.testFlag(QCP::iSelectPlottables)) { SelectionCandidates potentialSelections; QRectF rectF(rect.normalized()); if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft())) { // determine plottables that were hit by the rect and thus are candidates for selection: foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables()) { if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D()) { QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true); if (!dataSel.isEmpty()) potentialSelections.insert(dataSel.dataPointCount(), SelectionCandidate(plottable, dataSel)); } } if (!mInteractions.testFlag(QCP::iMultiSelect)) { // only leave plottable with most selected points in map, since we will only select a single plottable: if (!potentialSelections.isEmpty()) { SelectionCandidates::iterator it = potentialSelections.begin(); while (it != std::prev(potentialSelections.end())) // erase all except last element it = potentialSelections.erase(it); } } bool additive = event->modifiers().testFlag(mMultiSelectModifier); // deselect all other layerables if not additive selection: if (!additive) { // emit deselection except to those plottables who will be selected afterwards: foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) { if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory())) { bool selChanged = false; layerable->deselectEvent(&selChanged); selectionStateChanged |= selChanged; } } } } // go through selections in reverse (largest selection first) and emit select events: SelectionCandidates::const_iterator it = potentialSelections.constEnd(); while (it != potentialSelections.constBegin()) { --it; if (mInteractions.testFlag(it.value().first->selectionCategory())) { bool selChanged = false; it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged); selectionStateChanged |= selChanged; } } } } if (selectionStateChanged) { emit selectionChangedByUser(); replot(rpQueuedReplot); } else if (mSelectionRect) mSelectionRect->layer()->replot(); } /*! \internal This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref setSelectionRectMode is set to \ref QCP::srmZoom. It determines which axis rect was the origin of the selection rect judging by the starting point of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the provided \a rect (see \ref QCPAxisRect::zoom). \see processRectSelection */ void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event) { Q_UNUSED(event) if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft())) { QList affectedAxes = QList() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical); affectedAxes.removeAll(static_cast(nullptr)); axisRect->zoom(QRectF(rect), affectedAxes); } replot(rpQueuedReplot); // always replot to make selection rect disappear } /*! \internal This method is called when a simple left mouse click was detected on the QCustomPlot surface. It first determines the layerable that was hit by the click, and then calls its \ref QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the multi-select modifier was pressed, see \ref setMultiSelectModifier). In this method the hit layerable is determined a second time using \ref layerableAt (after the one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the clicked layerable determined here. For example, if a non-selectable layerable is in front of a selectable layerable at the click position, the front layerable will receive mouse events but the selectable one in the back will receive the \ref QCPLayerable::selectEvent. \see processRectSelection, QCPLayerable::selectTest */ void QCustomPlot::processPointSelection(QMouseEvent *event) { QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); bool selectionStateChanged = false; bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); // deselect all other layerables if not additive selection: if (!additive) { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) { if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) { bool selChanged = false; layerable->deselectEvent(&selChanged); selectionStateChanged |= selChanged; } } } } if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) { // a layerable was actually clicked, call its selectEvent: bool selChanged = false; clickedLayerable->selectEvent(event, additive, details, &selChanged); selectionStateChanged |= selChanged; } if (selectionStateChanged) { emit selectionChangedByUser(); replot(rpQueuedReplot); } } /*! \internal Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of \a plottable is this QCustomPlot. This method is called automatically in the QCPAbstractPlottable base class constructor. */ bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable) { if (mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast(plottable); return false; } if (plottable->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(plottable); return false; } mPlottables.append(plottable); // possibly add plottable to legend: if (mAutoAddPlottableToLegend) plottable->addToLegend(); if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) plottable->setLayer(currentLayer()); return true; } /*! \internal In order to maintain the simplified graph interface of QCustomPlot, this method is called by the QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot. This graph specific registration happens in addition to the call to \ref registerPlottable by the QCPAbstractPlottable base class. */ bool QCustomPlot::registerGraph(QCPGraph *graph) { if (!graph) { qDebug() << Q_FUNC_INFO << "passed graph is zero"; return false; } if (mGraphs.contains(graph)) { qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot"; return false; } mGraphs.append(graph); return true; } /*! \internal Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a item is this QCustomPlot. This method is called automatically in the QCPAbstractItem base class constructor. */ bool QCustomPlot::registerItem(QCPAbstractItem *item) { if (mItems.contains(item)) { qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast(item); return false; } if (item->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast(item); return false; } mItems.append(item); if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor) item->setLayer(currentLayer()); return true; } /*! \internal Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called after every operation that changes the layer indices, like layer removal, layer creation, layer moving. */ void QCustomPlot::updateLayerIndices() const { for (int i=0; imIndex = i; } /*! \internal Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true, only those layerables that are selectable will be considered. (Layerable subclasses communicate their selectability via the QCPLayerable::selectTest method, by returning -1.) \a selectionDetails is an output parameter that contains selection specifics of the affected layerable. This is useful if the respective layerable shall be given a subsequent QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains information about which part of the layerable was hit, in multi-part layerables (e.g. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref QCPDataSelection instance with the single data point which is closest to \a pos. \see layerableListAt, layoutElementAt, axisRectAt */ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const { QList details; QList candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr); if (selectionDetails && !details.isEmpty()) *selectionDetails = details.first(); if (!candidates.isEmpty()) return candidates.first(); else return nullptr; } /*! \internal Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those layerables that are selectable will be considered. (Layerable subclasses communicate their selectability via the QCPLayerable::selectTest method, by returning -1.) The returned list is sorted by the layerable/drawing order such that the layerable that appears on top in the plot is at index 0 of the returned list. If you only need to know the top layerable, rather use \ref layerableAt. \a selectionDetails is an output parameter that contains selection specifics of the affected layerable. This is useful if the respective layerable shall be given a subsequent QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains information about which part of the layerable was hit, in multi-part layerables (e.g. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref QCPDataSelection instance with the single data point which is closest to \a pos. \see layerableAt, layoutElementAt, axisRectAt */ QList QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails) const { QList result; for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) { const QList layerables = mLayers.at(layerIndex)->children(); for (int i=layerables.size()-1; i>=0; --i) { if (!layerables.at(i)->realVisibility()) continue; QVariant details; double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : nullptr); if (dist >= 0 && dist < selectionTolerance()) { result.append(layerables.at(i)); if (selectionDetails) selectionDetails->append(details); } } } return result; } /*! Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution file with width 200.) If the \a format supports compression, \a quality may be between 0 and 100 to control it. Returns true on success. If this function fails, most likely the given \a format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). The \a resolution will be written to the image file header (if the file format supports this) and has no direct consequence for the quality or the pixel size. However, if opening the image with a tool which respects the metadata, it will be able to scale the image to match either a given size in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected resolution unit internally. \see saveBmp, saveJpg, savePng, savePdf */ bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit) { QImage buffer = toPixmap(width, height, scale).toImage(); int dotsPerMeter = 0; switch (resolutionUnit) { case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break; case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break; case QCP::ruDotsPerInch: dotsPerMeter = int(resolution/0.0254); break; } buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools if (!buffer.isNull()) return buffer.save(fileName, format, quality); else return false; } /*! Renders the plot to a pixmap and returns it. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution pixmap with width 200.) \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf */ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) { // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } int scaledWidth = qRound(scale*newWidth); int scaledHeight = qRound(scale*newHeight); QPixmap result(scaledWidth, scaledHeight); result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later QCPPainter painter; painter.begin(&result); if (painter.isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter.setMode(QCPPainter::pmNoCaching); if (!qFuzzyCompare(scale, 1.0)) { if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales painter.setMode(QCPPainter::pmNonCosmetic); painter.scale(scale, scale); } if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill painter.fillRect(mViewport, mBackgroundBrush); draw(&painter); setViewport(oldViewport); painter.end(); } else // might happen if pixmap has width or height zero { qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; return QPixmap(); } return result; } /*! Renders the plot using the passed \a painter. The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will appear scaled accordingly. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. \see toPixmap */ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) { // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } if (painter->isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter->setMode(QCPPainter::pmNoCaching); if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here painter->fillRect(mViewport, mBackgroundBrush); draw(painter); setViewport(oldViewport); } else qDebug() << Q_FUNC_INFO << "Passed painter is not active"; } /* end of 'src/core.cpp' */ /* including file 'src/colorgradient.cpp' */ /* modified 2021-03-29T02:30:44, size 25278 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorGradient //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorGradient \brief Defines a color gradient for use with e.g. \ref QCPColorMap This class describes a color gradient which can be used to encode data with color. For example, QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) with a \a position from 0 to 1. In between these defined color positions, the color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation. Alternatively, load one of the preset color gradients shown in the image below, with \ref loadPreset, or by directly specifying the preset in the constructor. Apart from red, green and blue components, the gradient also interpolates the alpha values of the configured color stops. This allows to display some portions of the data range as transparent in the plot. How NaN values are interpreted can be configured with \ref setNanHandling. \image html QCPColorGradient.png The constructor \ref QCPColorGradient(GradientPreset preset) allows directly converting a \ref GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset to all the \a setGradient methods, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the color gradient shall be applied periodically (wrapping around) to data values that lie outside the data range specified on the plottable instance can be controlled with \ref setPeriodic. */ /*! Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color stops with \ref setColorStopAt. The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient() : mLevelCount(350), mColorInterpolation(ciRGB), mNanHandling(nhNone), mNanColor(Qt::black), mPeriodic(false), mColorBufferInvalidated(true) { mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); } /*! Constructs a new QCPColorGradient initialized with the colors and color interpolation according to \a preset. The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient(GradientPreset preset) : mLevelCount(350), mColorInterpolation(ciRGB), mNanHandling(nhNone), mNanColor(Qt::black), mPeriodic(false), mColorBufferInvalidated(true) { mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); loadPreset(preset); } /* undocumented operator */ bool QCPColorGradient::operator==(const QCPColorGradient &other) const { return ((other.mLevelCount == this->mLevelCount) && (other.mColorInterpolation == this->mColorInterpolation) && (other.mNanHandling == this ->mNanHandling) && (other.mNanColor == this->mNanColor) && (other.mPeriodic == this->mPeriodic) && (other.mColorStops == this->mColorStops)); } /*! Sets the number of discretization levels of the color gradient to \a n. The default is 350 which is typically enough to create a smooth appearance. The minimum number of levels is 2. \image html QCPColorGradient-levelcount.png */ void QCPColorGradient::setLevelCount(int n) { if (n < 2) { qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; n = 2; } if (n != mLevelCount) { mLevelCount = n; mColorBufferInvalidated = true; } } /*! Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the colors are the values of the passed QMap \a colorStops. In between these color stops, the color is interpolated according to \ref setColorInterpolation. A more convenient way to create a custom gradient may be to clear all color stops with \ref clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with \ref setColorStopAt. \see clearColorStops */ void QCPColorGradient::setColorStops(const QMap &colorStops) { mColorStops = colorStops; mColorBufferInvalidated = true; } /*! Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between these color stops, the color is interpolated according to \ref setColorInterpolation. \see setColorStops, clearColorStops */ void QCPColorGradient::setColorStopAt(double position, const QColor &color) { mColorStops.insert(position, color); mColorBufferInvalidated = true; } /*! Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be interpolated linearly in RGB or in HSV color space. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, whereas in HSV space the intermediate color is yellow. */ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) { if (interpolation != mColorInterpolation) { mColorInterpolation = interpolation; mColorBufferInvalidated = true; } } /*! Sets how NaNs in the data are displayed in the plot. \see setNanColor */ void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling) { mNanHandling = handling; } /*! Sets the color that NaN data is represented by, if \ref setNanHandling is set to ref nhNanColor. \see setNanHandling */ void QCPColorGradient::setNanColor(const QColor &color) { mNanColor = color; } /*! Sets whether data points that are outside the configured data range (e.g. \ref QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether they all have the same color, corresponding to the respective gradient boundary color. \image html QCPColorGradient-periodic.png As shown in the image above, gradients that have the same start and end color are especially suitable for a periodic gradient mapping, since they produce smooth color transitions throughout the color map. A preset that has this property is \ref gpHues. In practice, using periodic color gradients makes sense when the data corresponds to a periodic dimension, such as an angle or a phase. If this is not the case, the color encoding might become ambiguous, because multiple different data values are shown as the same color. */ void QCPColorGradient::setPeriodic(bool enabled) { mPeriodic = enabled; } /*! \overload This method is used to quickly convert a \a data array to colors. The colors will be output in the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this function. The data range that shall be used for mapping the data value to the gradient is passed in \a range. \a logarithmic indicates whether the data values shall be mapped to colors logarithmically. if \a data actually contains 2D-data linearized via [row*columnCount + column], you can set \a dataIndexFactor to columnCount to convert a column instead of a row of the data array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data is addressed data[i*dataIndexFactor]. Use the overloaded method to additionally provide alpha map data. The QRgb values that are placed in \a scanLine have their r, g, and b components premultiplied with alpha (see QImage::Format_ARGB32_Premultiplied). */ void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic) { // If you change something here, make sure to also adapt color() and the other colorize() overload if (!data) { qDebug() << Q_FUNC_INFO << "null pointer given as data"; return; } if (!scanLine) { qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; return; } if (mColorBufferInvalidated) updateColorBuffer(); const bool skipNanCheck = mNanHandling == nhNone; const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower); for (int i=0; i::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) result.setColorStopAt(1.0-it.key(), it.value()); return result; } /*! \internal Returns true if the color gradient uses transparency, i.e. if any of the configured color stops has an alpha value below 255. */ bool QCPColorGradient::stopsUseAlpha() const { for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) { if (it.value().alpha() < 255) return true; } return false; } /*! \internal Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly convert positions to colors. This is where the interpolation between color stops is calculated. */ void QCPColorGradient::updateColorBuffer() { if (mColorBuffer.size() != mLevelCount) mColorBuffer.resize(mLevelCount); if (mColorStops.size() > 1) { double indexToPosFactor = 1.0/double(mLevelCount-1); const bool useAlpha = stopsUseAlpha(); for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop { if (useAlpha) { const QColor col = std::prev(it).value(); const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier), int(col.green()*alphaPremultiplier), int(col.blue()*alphaPremultiplier), col.alpha()); } else mColorBuffer[i] = std::prev(it).value().rgba(); } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop { if (useAlpha) { const QColor &col = it.value(); const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier), int(col.green()*alphaPremultiplier), int(col.blue()*alphaPremultiplier), col.alpha()); } else mColorBuffer[i] = it.value().rgba(); } else // position is in between stops (or on an intermediate stop), interpolate color { QMap::const_iterator high = it; QMap::const_iterator low = std::prev(it); double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 switch (mColorInterpolation) { case ciRGB: { if (useAlpha) { const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha()); const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ), int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ), int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ), alpha); } else { mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ), int( ((1-t)*low.value().green() + t*high.value().green()) ), int( ((1-t)*low.value().blue() + t*high.value().blue())) ); } break; } case ciHSV: { QColor lowHsv = low.value().toHsv(); QColor highHsv = high.value().toHsv(); double hue = 0; double hueDiff = highHsv.hueF()-lowHsv.hueF(); if (hueDiff > 0.5) hue = lowHsv.hueF() - t*(1.0-hueDiff); else if (hueDiff < -0.5) hue = lowHsv.hueF() + t*(1.0+hueDiff); else hue = lowHsv.hueF() + t*hueDiff; if (hue < 0) hue += 1.0; else if (hue >= 1.0) hue -= 1.0; if (useAlpha) { const QRgb rgb = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF(); mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)); } else { mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); } break; } } } } } else if (mColorStops.size() == 1) { const QRgb rgb = mColorStops.constBegin().value().rgb(); const double alpha = mColorStops.constBegin().value().alphaF(); mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha))); } else // mColorStops is empty, fill color buffer with black { mColorBuffer.fill(qRgb(0, 0, 0)); } mColorBufferInvalidated = false; } /* end of 'src/colorgradient.cpp' */ /* including file 'src/selectiondecorator-bracket.cpp' */ /* modified 2021-03-29T02:30:44, size 12308 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPSelectionDecoratorBracket //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPSelectionDecoratorBracket \brief A selection decorator which draws brackets around each selected data segment Additionally to the regular highlighting of selected segments via color, fill and scatter style, this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data segment of the plottable. The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref setBracketBrush. To introduce custom bracket styles, it is only necessary to sublcass \ref QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the base class. */ /*! Creates a new QCPSelectionDecoratorBracket instance with default values. */ QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() : mBracketPen(QPen(Qt::black)), mBracketBrush(Qt::NoBrush), mBracketWidth(5), mBracketHeight(50), mBracketStyle(bsSquareBracket), mTangentToData(false), mTangentAverage(2) { } QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket() { } /*! Sets the pen that will be used to draw the brackets at the beginning and end of each selected data segment. */ void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen) { mBracketPen = pen; } /*! Sets the brush that will be used to draw the brackets at the beginning and end of each selected data segment. */ void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush) { mBracketBrush = brush; } /*! Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of the data, or the tangent direction of the current data slope, if \ref setTangentToData is enabled. */ void QCPSelectionDecoratorBracket::setBracketWidth(int width) { mBracketWidth = width; } /*! Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis of the data, or the tangent direction of the current data slope, if \ref setTangentToData is enabled. */ void QCPSelectionDecoratorBracket::setBracketHeight(int height) { mBracketHeight = height; } /*! Sets the shape that the bracket/marker will have. \see setBracketWidth, setBracketHeight */ void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style) { mBracketStyle = style; } /*! Sets whether the brackets will be rotated such that they align with the slope of the data at the position that they appear in. For noisy data, it might be more visually appealing to average the slope over multiple data points. This can be configured via \ref setTangentAverage. */ void QCPSelectionDecoratorBracket::setTangentToData(bool enabled) { mTangentToData = enabled; } /*! Controls over how many data points the slope shall be averaged, when brackets shall be aligned with the data (if \ref setTangentToData is true). From the position of the bracket, \a pointCount points towards the selected data range will be taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to disabling \ref setTangentToData. */ void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount) { mTangentAverage = pointCount; if (mTangentAverage < 1) mTangentAverage = 1; } /*! Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening bracket, respectively). The passed \a painter already contains all transformations that are necessary to position and rotate the bracket appropriately. Painting operations can be performed as if drawing upright brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket. If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should reimplement. */ void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const { switch (mBracketStyle) { case bsSquareBracket: { painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5)); painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5)); painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5)); break; } case bsHalfEllipse: { painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction); break; } case bsEllipse: { painter->drawEllipse(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight)); break; } case bsPlus: { painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5)); painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0)); break; } default: { qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast(mBracketStyle); break; } } } /*! Draws the bracket decoration on the data points at the begin and end of each selected data segment given in \a seletion. It uses the method \ref drawBracket to actually draw the shapes. \seebaseclassmethod */ void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection) { if (!mPlottable || selection.isEmpty()) return; if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D()) { foreach (const QCPDataRange &dataRange, selection.dataRanges()) { // determine position and (if tangent mode is enabled) angle of brackets: int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1; int closeBracketDir = -openBracketDir; QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin()); QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1); double openBracketAngle = 0; double closeBracketAngle = 0; if (mTangentToData) { openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir); closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir); } // draw opening bracket: QTransform oldTransform = painter->transform(); painter->setPen(mBracketPen); painter->setBrush(mBracketBrush); painter->translate(openBracketPos); painter->rotate(openBracketAngle/M_PI*180.0); drawBracket(painter, openBracketDir); painter->setTransform(oldTransform); // draw closing bracket: painter->setPen(mBracketPen); painter->setBrush(mBracketBrush); painter->translate(closeBracketPos); painter->rotate(closeBracketAngle/M_PI*180.0); drawBracket(painter, closeBracketDir); painter->setTransform(oldTransform); } } } /*! \internal If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope. This method returns the angle in radians by which a bracket at the given \a dataIndex must be rotated. The parameter \a direction must be set to either -1 or 1, representing whether it is an opening or closing bracket. Since for slope calculation multiple data points are required, this defines the direction in which the algorithm walks, starting at \a dataIndex, to average those data points. (see \ref setTangentToData and \ref setTangentAverage) \a interface1d is the interface to the plottable's data which is used to query data coordinates. */ double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const { if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount()) return 0; direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1 // how many steps we can actually go from index in the given direction without exceeding data bounds: int averageCount; if (direction < 0) averageCount = qMin(mTangentAverage, dataIndex); else averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex); qDebug() << averageCount; // calculate point average of averageCount points: QVector points(averageCount); QPointF pointsAverage; int currentIndex = dataIndex; for (int i=0; ikeyAxis(); QCPAxis *valueAxis = mPlottable->valueAxis(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; } if (keyAxis->orientation() == Qt::Horizontal) return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))}; else return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))}; } /* end of 'src/selectiondecorator-bracket.cpp' */ /* including file 'src/layoutelements/layoutelement-axisrect.cpp' */ /* modified 2021-03-29T02:30:44, size 47193 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisRect \brief Holds multiple axes and arranges them in a rectangular shape. This class represents an axis rect, a rectangular area that is bounded on all sides with an arbitrary number of axes. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the layout system allows to have multiple axis rects, e.g. arranged in a grid layout (QCustomPlot::plotLayout). By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref addAxes. To remove an axis, use \ref removeAxis. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be placed on other layers, independently of the axis rect. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref insetLayout and can be used to have other layout elements (or even other layouts with multiple elements) hovering inside the axis rect. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed line on the far left indicates the viewport/widget border.
*/ /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. \see QCPLayoutInset */ /*! \fn int QCPAxisRect::left() const Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::right() const Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::top() const Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::bottom() const Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::width() const Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::height() const Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPAxisRect::size() const Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topLeft() const Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topRight() const Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomLeft() const Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomRight() const Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::center() const Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /* end documentation of inline functions */ /*! Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four sides, the top and right axes are set invisible initially. */ QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : QCPLayoutElement(parentPlot), mBackgroundBrush(Qt::NoBrush), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mInsetLayout(new QCPLayoutInset), mRangeDrag(Qt::Horizontal|Qt::Vertical), mRangeZoom(Qt::Horizontal|Qt::Vertical), mRangeZoomFactorHorz(0.85), mRangeZoomFactorVert(0.85), mDragging(false) { mInsetLayout->initializeParentPlot(mParentPlot); mInsetLayout->setParentLayerable(this); mInsetLayout->setParent(this); setMinimumSize(50, 50); setMinimumMargins(QMargins(15, 15, 15, 15)); mAxes.insert(QCPAxis::atLeft, QList()); mAxes.insert(QCPAxis::atRight, QList()); mAxes.insert(QCPAxis::atTop, QList()); mAxes.insert(QCPAxis::atBottom, QList()); if (setupDefaultAxes) { QCPAxis *xAxis = addAxis(QCPAxis::atBottom); QCPAxis *yAxis = addAxis(QCPAxis::atLeft); QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); setRangeDragAxes(xAxis, yAxis); setRangeZoomAxes(xAxis, yAxis); xAxis2->setVisible(false); yAxis2->setVisible(false); xAxis->grid()->setVisible(true); yAxis->grid()->setVisible(true); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); xAxis2->grid()->setZeroLinePen(Qt::NoPen); yAxis2->grid()->setZeroLinePen(Qt::NoPen); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); } } QCPAxisRect::~QCPAxisRect() { delete mInsetLayout; mInsetLayout = nullptr; foreach (QCPAxis *axis, axes()) removeAxis(axis); } /*! Returns the number of axes on the axis rect side specified with \a type. \see axis */ int QCPAxisRect::axisCount(QCPAxis::AxisType type) const { return mAxes.value(type).size(); } /*! Returns the axis with the given \a index on the axis rect side specified with \a type. \see axisCount, axes */ QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const { QList ax(mAxes.value(type)); if (index >= 0 && index < ax.size()) { return ax.at(index); } else { qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; return nullptr; } } /*! Returns all axes on the axis rect sides specified with \a types. \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. \see axis */ QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const { QList result; if (types.testFlag(QCPAxis::atLeft)) result << mAxes.value(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << mAxes.value(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << mAxes.value(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << mAxes.value(QCPAxis::atBottom); return result; } /*! \overload Returns all axes of this axis rect. */ QList QCPAxisRect::axes() const { QList result; QHashIterator > it(mAxes); while (it.hasNext()) { it.next(); result << it.value(); } return result; } /*! Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to remove an axis, use \ref removeAxis instead of deleting it manually. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership of the axis, so you may not delete it afterwards. Further, the \a axis must have been created with this axis rect as parent and with the same axis type as specified in \a type. If this is not the case, a debug output is generated, the axis is not added, and the method returns \c nullptr. This method can not be used to move \a axis between axis rects. The same \a axis instance must not be added multiple times to the same or different axis rects. If an axis rect side already contains one or more axes, the lower and upper endings of the new axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref QCPLineEnding::esHalfBar. \see addAxes, setupFullAxesBox */ QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis) { QCPAxis *newAxis = axis; if (!newAxis) { newAxis = new QCPAxis(this, type); } else // user provided existing axis instance, do some sanity checks { if (newAxis->axisType() != type) { qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; return nullptr; } if (newAxis->axisRect() != this) { qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; return nullptr; } if (axes().contains(newAxis)) { qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; return nullptr; } } if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset { bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); } mAxes[type].append(newAxis); // reset convenience axis pointers on parent QCustomPlot if they are unset: if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this) { switch (type) { case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; } case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; } case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; } case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; } } } return newAxis; } /*! Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. Returns a list of the added axes. \see addAxis, setupFullAxesBox */ QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) { QList result; if (types.testFlag(QCPAxis::atLeft)) result << addAxis(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << addAxis(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << addAxis(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << addAxis(QCPAxis::atBottom); return result; } /*! Removes the specified \a axis from the axis rect and deletes it. Returns true on success, i.e. if \a axis was a valid axis in this axis rect. \see addAxis */ bool QCPAxisRect::removeAxis(QCPAxis *axis) { // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: QHashIterator > it(mAxes); while (it.hasNext()) { it.next(); if (it.value().contains(axis)) { if (it.value().first() == axis && it.value().size() > 1) // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists) it.value()[1]->setOffset(axis->offset()); mAxes[it.key()].removeOne(axis); if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) parentPlot()->axisRemoved(axis); delete axis; return true; } } qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); return false; } /*! Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates. All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom specific axes, use the overloaded version of this method. \see QCustomPlot::setSelectionRectMode */ void QCPAxisRect::zoom(const QRectF &pixelRect) { zoom(pixelRect, axes()); } /*! \overload Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates. Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly. \see QCustomPlot::setSelectionRectMode */ void QCPAxisRect::zoom(const QRectF &pixelRect, const QList &affectedAxes) { foreach (QCPAxis *axis, affectedAxes) { if (!axis) { qDebug() << Q_FUNC_INFO << "a passed axis was zero"; continue; } QCPRange pixelRange; if (axis->orientation() == Qt::Horizontal) pixelRange = QCPRange(pixelRect.left(), pixelRect.right()); else pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom()); axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper)); } } /*! Convenience function to create an axis on each side that doesn't have any axes yet and set their visibility to true. Further, the top/right axes are assigned the following properties of the bottom/left axes: \li range (\ref QCPAxis::setRange) \li range reversed (\ref QCPAxis::setRangeReversed) \li scale type (\ref QCPAxis::setScaleType) \li tick visibility (\ref QCPAxis::setTicks) \li number format (\ref QCPAxis::setNumberFormat) \li number precision (\ref QCPAxis::setNumberPrecision) \li tick count of ticker (\ref QCPAxisTicker::setTickCount) \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin) Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes. */ void QCPAxisRect::setupFullAxesBox(bool connectRanges) { QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; if (axisCount(QCPAxis::atBottom) == 0) xAxis = addAxis(QCPAxis::atBottom); else xAxis = axis(QCPAxis::atBottom); if (axisCount(QCPAxis::atLeft) == 0) yAxis = addAxis(QCPAxis::atLeft); else yAxis = axis(QCPAxis::atLeft); if (axisCount(QCPAxis::atTop) == 0) xAxis2 = addAxis(QCPAxis::atTop); else xAxis2 = axis(QCPAxis::atTop); if (axisCount(QCPAxis::atRight) == 0) yAxis2 = addAxis(QCPAxis::atRight); else yAxis2 = axis(QCPAxis::atRight); xAxis->setVisible(true); yAxis->setVisible(true); xAxis2->setVisible(true); yAxis2->setVisible(true); xAxis2->setTickLabels(false); yAxis2->setTickLabels(false); xAxis2->setRange(xAxis->range()); xAxis2->setRangeReversed(xAxis->rangeReversed()); xAxis2->setScaleType(xAxis->scaleType()); xAxis2->setTicks(xAxis->ticks()); xAxis2->setNumberFormat(xAxis->numberFormat()); xAxis2->setNumberPrecision(xAxis->numberPrecision()); xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount()); xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin()); yAxis2->setRange(yAxis->range()); yAxis2->setRangeReversed(yAxis->rangeReversed()); yAxis2->setScaleType(yAxis->scaleType()); yAxis2->setTicks(yAxis->ticks()); yAxis2->setNumberFormat(yAxis->numberFormat()); yAxis2->setNumberPrecision(yAxis->numberPrecision()); yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount()); yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin()); if (connectRanges) { connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); } } /*! Returns a list of all the plottables that are associated with this axis rect. A plottable is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see graphs, items */ QList QCPAxisRect::plottables() const { // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries QList result; foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables) { if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this) result.append(plottable); } return result; } /*! Returns a list of all the graphs that are associated with this axis rect. A graph is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see plottables, items */ QList QCPAxisRect::graphs() const { // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries QList result; foreach (QCPGraph *graph, mParentPlot->mGraphs) { if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this) result.append(graph); } return result; } /*! Returns a list of all the items that are associated with this axis rect. An item is considered associated with an axis rect if any of its positions has key or value axis set to an axis that is in this axis rect, or if any of its positions has \ref QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref QCPAbstractItem::setClipAxisRect) is set to this axis rect. \see plottables, graphs */ QList QCPAxisRect::items() const { // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries // and miss those items that have this axis rect as clipAxisRect. QList result; foreach (QCPAbstractItem *item, mParentPlot->mItems) { if (item->clipAxisRect() == this) { result.append(item); continue; } foreach (QCPItemPosition *position, item->positions()) { if (position->axisRect() == this || position->keyAxis()->axisRect() == this || position->valueAxis()->axisRect() == this) { result.append(item); break; } } } return result; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPAxisRect. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its QCPInsetLayout::update function. \seebaseclassmethod */ void QCPAxisRect::update(UpdatePhase phase) { QCPLayoutElement::update(phase); switch (phase) { case upPreparation: { foreach (QCPAxis *axis, axes()) axis->setupTickVectors(); break; } case upLayout: { mInsetLayout->setOuterRect(rect()); break; } default: break; } // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): mInsetLayout->update(phase); } /* inherits documentation from base class */ QList QCPAxisRect::elements(bool recursive) const { QList result; if (mInsetLayout) { result << mInsetLayout; if (recursive) result << mInsetLayout->elements(recursive); } return result; } /* inherits documentation from base class */ void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPAxisRect::draw(QCPPainter *painter) { drawBackground(painter); } /*! Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! \overload Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. The brush will be drawn before (under) any background pixmap, which may be specified with \ref setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. \see setBackground(const QPixmap &pm) */ void QCPAxisRect::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCPAxisRect::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. \see setBackground, setBackgroundScaled */ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns the first one (use \ref rangeDragAxes to retrieve a list with all set axes). \see setRangeDragAxes */ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) { if (orientation == Qt::Horizontal) return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data(); else return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data(); } /*! Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns the first one (use \ref rangeZoomAxes to retrieve a list with all set axes). \see setRangeZoomAxes */ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) { if (orientation == Qt::Horizontal) return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data(); else return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data(); } /*! Returns all range drag axes of the \a orientation provided. \see rangeZoomAxis, setRangeZoomAxes */ QList QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) { QList result; if (orientation == Qt::Horizontal) { foreach (QPointer axis, mRangeDragHorzAxis) { if (!axis.isNull()) result.append(axis.data()); } } else { foreach (QPointer axis, mRangeDragVertAxis) { if (!axis.isNull()) result.append(axis.data()); } } return result; } /*! Returns all range zoom axes of the \a orientation provided. \see rangeDragAxis, setRangeDragAxes */ QList QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation) { QList result; if (orientation == Qt::Horizontal) { foreach (QPointer axis, mRangeZoomHorzAxis) { if (!axis.isNull()) result.append(axis.data()); } } else { foreach (QPointer axis, mRangeZoomVertAxis) { if (!axis.isNull()) result.append(axis.data()); } } return result; } /*! Returns the range zoom factor of the \a orientation provided. \see setRangeZoomFactor */ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); } /*! Sets which axis orientation may be range dragged by the user with mouse interaction. What orientation corresponds to which specific axis can be set with \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging interaction. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag */ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) { mRangeDrag = orientations; } /*! Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming interaction. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag */ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) { mRangeZoom = orientations; } /*! \overload Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective orientation. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall react to dragging interactions. \see setRangeZoomAxes */ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) { QList horz, vert; if (horizontal) horz.append(horizontal); if (vertical) vert.append(vertical); setRangeDragAxes(horz, vert); } /*! \overload This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag orientation that the respective axis will react to is deduced from its orientation (\ref QCPAxis::orientation). In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag motion, use the overload taking two separate lists for horizontal and vertical dragging. */ void QCPAxisRect::setRangeDragAxes(QList axes) { QList horz, vert; foreach (QCPAxis *ax, axes) { if (ax->orientation() == Qt::Horizontal) horz.append(ax); else vert.append(ax); } setRangeDragAxes(horz, vert); } /*! \overload This method allows to set multiple axes up to react to horizontal and vertical dragging, and define specifically which axis reacts to which drag orientation (irrespective of the axis orientation). */ void QCPAxisRect::setRangeDragAxes(QList horizontal, QList vertical) { mRangeDragHorzAxis.clear(); foreach (QCPAxis *ax, horizontal) { QPointer axPointer(ax); if (!axPointer.isNull()) mRangeDragHorzAxis.append(axPointer); else qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast(ax); } mRangeDragVertAxis.clear(); foreach (QCPAxis *ax, vertical) { QPointer axPointer(ax); if (!axPointer.isNull()) mRangeDragVertAxis.append(axPointer); else qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast(ax); } } /*! Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the QCustomPlot widget. Pass \c nullptr if no axis shall be zoomed in the respective orientation. The two axes can be zoomed with different strengths, when different factors are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor). Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall react to zooming interactions. \see setRangeDragAxes */ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) { QList horz, vert; if (horizontal) horz.append(horizontal); if (vertical) vert.append(vertical); setRangeZoomAxes(horz, vert); } /*! \overload This method allows to set up multiple axes to react to horizontal and vertical range zooming. The zoom orientation that the respective axis will react to is deduced from its orientation (\ref QCPAxis::orientation). In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom interaction, use the overload taking two separate lists for horizontal and vertical zooming. */ void QCPAxisRect::setRangeZoomAxes(QList axes) { QList horz, vert; foreach (QCPAxis *ax, axes) { if (ax->orientation() == Qt::Horizontal) horz.append(ax); else vert.append(ax); } setRangeZoomAxes(horz, vert); } /*! \overload This method allows to set multiple axes up to react to horizontal and vertical zooming, and define specifically which axis reacts to which zoom orientation (irrespective of the axis orientation). */ void QCPAxisRect::setRangeZoomAxes(QList horizontal, QList vertical) { mRangeZoomHorzAxis.clear(); foreach (QCPAxis *ax, horizontal) { QPointer axPointer(ax); if (!axPointer.isNull()) mRangeZoomHorzAxis.append(axPointer); else qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast(ax); } mRangeZoomVertAxis.clear(); foreach (QCPAxis *ax, vertical) { QPointer axPointer(ax); if (!axPointer.isNull()) mRangeZoomVertAxis.append(axPointer); else qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast(ax); } } /*! Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal and which is vertical, can be set with \ref setRangeZoomAxes. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user) will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the same scrolling direction will zoom out. */ void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) { mRangeZoomFactorHorz = horizontalFactor; mRangeZoomFactorVert = verticalFactor; } /*! \overload Sets both the horizontal and vertical zoom \a factor. */ void QCPAxisRect::setRangeZoomFactor(double factor) { mRangeZoomFactorHorz = factor; mRangeZoomFactorVert = factor; } /*! \internal Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::drawBackground(QCPPainter *painter) { // draw background fill: if (mBackgroundBrush != Qt::NoBrush) painter->fillRect(mRect, mBackgroundBrush); // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mRect.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); } } } /*! \internal This function makes sure multiple axes on the side specified with \a type don't collide, but are distributed according to their respective space requirement (QCPAxis::calculateMargin). It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the one with index zero. This function is called by \ref calculateAutoMargin. */ void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) { const QList axesList = mAxes.value(type); if (axesList.isEmpty()) return; bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) { if (!isFirstVisible) offset += axesList.at(i)->tickLengthIn(); isFirstVisible = false; } axesList.at(i)->setOffset(offset); } } /* inherits documentation from base class */ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) { if (!mAutoMargins.testFlag(side)) qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; updateAxesOffset(QCPAxis::marginSideToAxisType(side)); // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); if (!axesList.isEmpty()) return axesList.last()->offset() + axesList.last()->calculateMargin(); else return 0; } /*! \internal Reacts to a change in layout to potentially set the convenience axis pointers \ref QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective axes of this axis rect. This is only done if the respective convenience pointer is currently zero and if there is no QCPAxisRect at position (0, 0) of the plot layout. This automation makes it simpler to replace the main axis rect with a newly created one, without the need to manually reset the convenience pointers. */ void QCPAxisRect::layoutChanged() { if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this) { if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis) mParentPlot->xAxis = axis(QCPAxis::atBottom); if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis) mParentPlot->yAxis = axis(QCPAxis::atLeft); if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2) mParentPlot->xAxis2 = axis(QCPAxis::atTop); if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2) mParentPlot->yAxis2 = axis(QCPAxis::atRight); } } /*! \internal Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. \see mouseMoveEvent, mouseReleaseEvent */ void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details) { Q_UNUSED(details) if (event->buttons() & Qt::LeftButton) { mDragging = true; // initialize antialiasing backup in case we start dragging: if (mParentPlot->noAntialiasingOnDrag()) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { mDragStartHorzRange.clear(); foreach (QPointer axis, mRangeDragHorzAxis) mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range()); mDragStartVertRange.clear(); foreach (QPointer axis, mRangeDragVertAxis) mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range()); } } } /*! \internal Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. \see mousePressEvent, mouseReleaseEvent */ void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(startPos) // Mouse range dragging interaction: if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDrag.testFlag(Qt::Horizontal)) { for (int i=0; i= mDragStartHorzRange.size()) break; if (ax->mScaleType == QCPAxis::stLinear) { double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x()); ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff); } else if (ax->mScaleType == QCPAxis::stLogarithmic) { double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x()); ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff); } } } if (mRangeDrag.testFlag(Qt::Vertical)) { for (int i=0; i= mDragStartVertRange.size()) break; if (ax->mScaleType == QCPAxis::stLinear) { double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y()); ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff); } else if (ax->mScaleType == QCPAxis::stLogarithmic) { double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y()); ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff); } } } if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot { if (mParentPlot->noAntialiasingOnDrag()) mParentPlot->setNotAntialiasedElements(QCP::aeAll); mParentPlot->replot(QCustomPlot::rpQueuedReplot); } } } /* inherits documentation from base class */ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(event) Q_UNUSED(startPos) mDragging = false; if (mParentPlot->noAntialiasingOnDrag()) { mParentPlot->setAntialiasedElements(mAADragBackup); mParentPlot->setNotAntialiasedElements(mNotAADragBackup); } } /*! \internal Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of the scaling operation is the current cursor position inside the axis rect. The scaling factor is dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. Note, that event->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of the range zoom factor. This takes care of the wheel direction automatically, by inverting the factor, when the wheel step is negative (f^-1 = 1/f). */ void QCPAxisRect::wheelEvent(QWheelEvent *event) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) const double delta = event->delta(); #else const double delta = event->angleDelta().y(); #endif #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) const QPointF pos = event->pos(); #else const QPointF pos = event->position(); #endif // Mouse range zooming interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { if (mRangeZoom != 0) { double factor; double wheelSteps = delta/120.0; // a single step delta is +/-120 usually if (mRangeZoom.testFlag(Qt::Horizontal)) { factor = qPow(mRangeZoomFactorHorz, wheelSteps); foreach (QPointer axis, mRangeZoomHorzAxis) { if (!axis.isNull()) axis->scaleRange(factor, axis->pixelToCoord(pos.x())); } } if (mRangeZoom.testFlag(Qt::Vertical)) { factor = qPow(mRangeZoomFactorVert, wheelSteps); foreach (QPointer axis, mRangeZoomVertAxis) { if (!axis.isNull()) axis->scaleRange(factor, axis->pixelToCoord(pos.y())); } } mParentPlot->replot(); } } } /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */ /* including file 'src/layoutelements/layoutelement-legend.cpp' */ /* modified 2021-03-29T02:30:44, size 31762 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractLegendItem \brief The abstract base class for all entries in a QCPLegend. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the legend, the subclass \ref QCPPlottableLegendItem is more suitable. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry that's not even associated with a plottable). You must implement the following pure virtual functions: \li \ref draw (from QCPLayerable) You inherit the following members you may use:
QCPLegend *\b mParentLegend A pointer to the parent QCPLegend.
QFont \b mFont The generic font of the item. You should use this font for all or at least the most prominent text of the item.
*/ /* start of documentation of signals */ /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) This signal is emitted when the selection state of this legend item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end of documentation of signals */ /*! Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. */ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : QCPLayoutElement(parent->parentPlot()), mParentLegend(parent), mFont(parent->font()), mTextColor(parent->textColor()), mSelectedFont(parent->selectedFont()), mSelectedTextColor(parent->selectedTextColor()), mSelectable(true), mSelected(false) { setLayer(QLatin1String("legend")); setMargins(QMargins(0, 0, 0, 0)); } /*! Sets the default font of this specific legend item to \a font. \see setTextColor, QCPLegend::setFont */ void QCPAbstractLegendItem::setFont(const QFont &font) { mFont = font; } /*! Sets the default text color of this specific legend item to \a color. \see setFont, QCPLegend::setTextColor */ void QCPAbstractLegendItem::setTextColor(const QColor &color) { mTextColor = color; } /*! When this legend item is selected, \a font is used to draw generic text, instead of the normal font set with \ref setFont. \see setFont, QCPLegend::setSelectedFont */ void QCPAbstractLegendItem::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! When this legend item is selected, \a color is used to draw generic text, instead of the normal color set with \ref setTextColor. \see setTextColor, QCPLegend::setSelectedTextColor */ void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether this specific legend item is selectable. \see setSelectedParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this specific legend item is selected. It is possible to set the selection state of this item by calling this function directly, even if setSelectable is set to false. \see setSelectableParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (!mParentPlot) return -1; if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) return -1; if (mRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /* inherits documentation from base class */ void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); } /* inherits documentation from base class */ QRect QCPAbstractLegendItem::clipRect() const { return mOuterRect; } /* inherits documentation from base class */ void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlottableLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlottableLegendItem \brief A legend item representing a plottable with an icon and the plottable name. This is the standard legend item for plottables. It displays an icon of the plottable next to the plottable name. The icon is drawn by the respective plottable itself (\ref QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the middle. Legend items of this type are always associated with one plottable (retrievable via the plottable() function and settable with the constructor). You may change the font of the plottable name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend creates/removes legend items of this type. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout interface, QCPLegend has specialized functions for handling legend items conveniently, see the documentation of \ref QCPLegend. */ /*! Creates a new legend item associated with \a plottable. Once it's created, it can be added to the legend via \ref QCPLegend::addItem. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. */ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : QCPAbstractLegendItem(parent), mPlottable(plottable) { setAntialiased(false); } /*! \internal Returns the pen that shall be used to draw the icon border, taking into account the selection state of this item. */ QPen QCPPlottableLegendItem::getIconBorderPen() const { return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } /*! \internal Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } /*! \internal Returns the font that shall be used to draw text, taking into account the selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Draws the item with \a painter. The size and position of the drawn legend item is defined by the parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref maximumOuterSizeHint of this legend item. */ void QCPPlottableLegendItem::draw(QCPPainter *painter) { if (!mPlottable) return; painter->setFont(getFont()); painter->setPen(QPen(getTextColor())); QSize iconSize = mParentLegend->iconSize(); QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); QRect iconRect(mRect.topLeft(), iconSize); int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); // draw icon: painter->save(); painter->setClipRect(iconRect, Qt::IntersectClip); mPlottable->drawLegendIcon(painter, iconRect); painter->restore(); // draw icon border: if (getIconBorderPen().style() != Qt::NoPen) { painter->setPen(getIconBorderPen()); painter->setBrush(Qt::NoBrush); int halfPen = qCeil(painter->pen().widthF()*0.5)+1; painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped painter->drawRect(iconRect); } } /*! \internal Calculates and returns the size of this item. This includes the icon, the text and the padding in between. \seebaseclassmethod */ QSize QCPPlottableLegendItem::minimumOuterSizeHint() const { if (!mPlottable) return {}; QSize result(0, 0); QRect textRect; QFontMetrics fontMetrics(getFont()); QSize iconSize = mParentLegend->iconSize(); textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); result.setHeight(qMax(textRect.height(), iconSize.height())); result.rwidth() += mMargins.left()+mMargins.right(); result.rheight() += mMargins.top()+mMargins.bottom(); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLegend //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLegend \brief Manages a legend inside a QCustomPlot. A legend is a small box somewhere in the plot which lists plottables with their name and icon. A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the plottable, for which a legend item shall be created. In the case of the main legend (\ref QCustomPlot::legend), simply adding plottables to the plot while \ref QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding legend items. The legend item associated with a certain plottable can be removed with \ref QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc. Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as mentioned above. In principle, any other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout System\endlink for examples on how to add other elements to the legend and move it outside the axis rect. Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control in which order (column first or row first) the legend is filled up when calling \ref addItem, and at which column or row wrapping occurs. The default fill order for legends is \ref foRowsFirst. By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement interface. */ /* start of documentation of signals */ /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. \see setSelectedParts, setSelectableParts */ /* end of documentation of signals */ /*! Constructs a new QCPLegend instance with default values. Note that by default, QCustomPlot already contains a legend ready to be used as \ref QCustomPlot::legend */ QCPLegend::QCPLegend() : mIconTextPadding{} { setFillOrder(QCPLayoutGrid::foRowsFirst); setWrap(0); setRowSpacing(3); setColumnSpacing(8); setMargins(QMargins(7, 5, 7, 4)); setAntialiased(false); setIconSize(32, 18); setIconTextPadding(7); setSelectableParts(spLegendBox | spItems); setSelectedParts(spNone); setBorderPen(QPen(Qt::black, 0)); setSelectedBorderPen(QPen(Qt::blue, 2)); setIconBorderPen(Qt::NoPen); setSelectedIconBorderPen(QPen(Qt::blue, 2)); setBrush(Qt::white); setSelectedBrush(Qt::white); setTextColor(Qt::black); setSelectedTextColor(Qt::blue); } QCPLegend::~QCPLegend() { clearItems(); if (qobject_cast(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) mParentPlot->legendRemoved(this); } /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { // check whether any legend elements selected, if yes, add spItems to return value bool hasSelectedItems = false; for (int i=0; iselected()) { hasSelectedItems = true; break; } } if (hasSelectedItems) return mSelectedParts | spItems; else return mSelectedParts & ~spItems; } /*! Sets the pen, the border of the entire legend is drawn with. */ void QCPLegend::setBorderPen(const QPen &pen) { mBorderPen = pen; } /*! Sets the brush of the legend background. */ void QCPLegend::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will use this font by default. However, a different font can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a font on all already existing legend items. \see QCPAbstractLegendItem::setFont */ void QCPLegend::setFont(const QFont &font) { mFont = font; for (int i=0; isetFont(mFont); } } /*! Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) will use this color by default. However, a different colors can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a color on all already existing legend items. \see QCPAbstractLegendItem::setTextColor */ void QCPLegend::setTextColor(const QColor &color) { mTextColor = color; for (int i=0; isetTextColor(color); } } /*! Sets the size of legend icons. Legend items that draw an icon (e.g. a visual representation of the graph) will use this size by default. */ void QCPLegend::setIconSize(const QSize &size) { mIconSize = size; } /*! \overload */ void QCPLegend::setIconSize(int width, int height) { mIconSize.setWidth(width); mIconSize.setHeight(height); } /*! Sets the horizontal space in pixels between the legend icon and the text next to it. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the name of the graph) will use this space by default. */ void QCPLegend::setIconTextPadding(int padding) { mIconTextPadding = padding; } /*! Sets the pen used to draw a border around each legend icon. Legend items that draw an icon (e.g. a visual representation of the graph) will use this pen by default. If no border is wanted, set this to \a Qt::NoPen. */ void QCPLegend::setIconBorderPen(const QPen &pen) { mIconBorderPen = pen; } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPLegend::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected doesn't contain \ref spItems, those items become deselected. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions contains iSelectLegend. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part even when \ref setSelectableParts was set to a value that actually excludes the part. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set before, because there's no way to specify which exact items to newly select. Do this by calling \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont */ void QCPLegend::setSelectedParts(const SelectableParts &selected) { SelectableParts newSelected = selected; mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed if (mSelectedParts != newSelected) { if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) { qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; newSelected &= ~spItems; } if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection { for (int i=0; isetSelected(false); } } mSelectedParts = newSelected; emit selectionChanged(mSelectedParts); } } /*! When the legend box is selected, this pen is used to draw the border instead of the normal pen set via \ref setBorderPen. \see setSelectedParts, setSelectableParts, setSelectedBrush */ void QCPLegend::setSelectedBorderPen(const QPen &pen) { mSelectedBorderPen = pen; } /*! Sets the pen legend items will use to draw their icon borders, when they are selected. \see setSelectedParts, setSelectableParts, setSelectedFont */ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) { mSelectedIconBorderPen = pen; } /*! When the legend box is selected, this brush is used to draw the legend background instead of the normal brush set via \ref setBrush. \see setSelectedParts, setSelectableParts, setSelectedBorderPen */ void QCPLegend::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the default font that is used by legend items when they are selected. This function will also set \a font on all already existing legend items. \see setFont, QCPAbstractLegendItem::setSelectedFont */ void QCPLegend::setSelectedFont(const QFont &font) { mSelectedFont = font; for (int i=0; isetSelectedFont(font); } } /*! Sets the default text color that is used by legend items when they are selected. This function will also set \a color on all already existing legend items. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor */ void QCPLegend::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; for (int i=0; isetSelectedTextColor(color); } } /*! Returns the item with index \a i. If non-legend items were added to the legend, and the element at the specified cell index is not a QCPAbstractLegendItem, returns \c nullptr. Note that the linear index depends on the current fill order (\ref setFillOrder). \see itemCount, addItem, itemWithPlottable */ QCPAbstractLegendItem *QCPLegend::item(int index) const { return qobject_cast(elementAt(index)); } /*! Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns \c nullptr. \see hasItemWithPlottable */ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const { for (int i=0; i(item(i))) { if (pli->plottable() == plottable) return pli; } } return nullptr; } /*! Returns the number of items currently in the legend. It is identical to the base class QCPLayoutGrid::elementCount(), and unlike the other "item" interface methods of QCPLegend, doesn't only address elements which can be cast to QCPAbstractLegendItem. Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid base class which allows creating empty cells), they are included in the returned count. \see item */ int QCPLegend::itemCount() const { return elementCount(); } /*! Returns whether the legend contains \a item. \see hasItemWithPlottable */ bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const { for (int i=0; iitem(i)) return true; } return false; } /*! Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false. \see itemWithPlottable */ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const { return itemWithPlottable(plottable); } /*! Adds \a item to the legend, if it's not present already. The element is arranged according to the current fill order (\ref setFillOrder) and wrapping (\ref setWrap). Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added. The legend takes ownership of the item. \see removeItem, item, hasItem */ bool QCPLegend::addItem(QCPAbstractLegendItem *item) { return addElement(item); } /*! \overload Removes the item with the specified \a index from the legend and deletes it. After successful removal, the legend is reordered according to the current fill order (\ref setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid. Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes elements derived from \ref QCPAbstractLegendItem. \see itemCount, clearItems */ bool QCPLegend::removeItem(int index) { if (QCPAbstractLegendItem *ali = item(index)) { bool success = remove(ali); if (success) setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering return success; } else return false; } /*! \overload Removes \a item from the legend and deletes it. After successful removal, the legend is reordered according to the current fill order (\ref setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid. Returns true, if successful. \see clearItems */ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) { bool success = remove(item); if (success) setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering return success; } /*! Removes all items from the legend. */ void QCPLegend::clearItems() { for (int i=elementCount()-1; i>=0; --i) { if (item(i)) removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item } setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed } /*! Returns the legend items that are currently selected. If no items are selected, the list is empty. \see QCPAbstractLegendItem::setSelected, setSelectable */ QList QCPLegend::selectedItems() const { QList result; for (int i=0; iselected()) result.append(ali); } } return result; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing main legend elements. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \seebaseclassmethod \see setAntialiased */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); } /*! \internal Returns the pen used to paint the border of the legend, taking into account the selection state of the legend box. */ QPen QCPLegend::getBorderPen() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; } /*! \internal Returns the brush used to paint the background of the legend, taking into account the selection state of the legend box. */ QBrush QCPLegend::getBrush() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; } /*! \internal Draws the legend box with the provided \a painter. The individual legend items are layerables themselves, thus are drawn independently. */ void QCPLegend::draw(QCPPainter *painter) { // draw background rect: painter->setBrush(getBrush()); painter->setPen(getBorderPen()); painter->drawRect(mOuterRect); } /* inherits documentation from base class */ double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) return -1; if (mOuterRect.contains(pos.toPoint())) { if (details) details->setValue(spLegendBox); return mParentPlot->selectionTolerance()*0.99; } return -1; } /* inherits documentation from base class */ void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) mSelectedParts = selectedParts(); // in case item selection has changed if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPLegend::deselectEvent(bool *selectionStateChanged) { mSelectedParts = selectedParts(); // in case item selection has changed if (mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(selectedParts() & ~spLegendBox); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPLegend::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) { if (parentPlot && !parentPlot->legend) parentPlot->legend = this; } /* end of 'src/layoutelements/layoutelement-legend.cpp' */ /* including file 'src/layoutelements/layoutelement-textelement.cpp' */ /* modified 2021-03-29T02:30:44, size 12925 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPTextElement //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPTextElement \brief A layout element displaying a text The text may be specified with \ref setText, the formatting can be controlled with \ref setFont, \ref setTextColor, and \ref setTextFlags. A text element can be added as follows: \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation */ /* start documentation of signals */ /*! \fn void QCPTextElement::selectionChanged(bool selected) This signal is emitted when the selection state has changed to \a selected, either by user interaction or by a direct call to \ref setSelected. \see setSelected, setSelectable */ /*! \fn void QCPTextElement::clicked(QMouseEvent *event) This signal is emitted when the text element is clicked. \see doubleClicked, selectTest */ /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event) This signal is emitted when the text element is double clicked. \see clicked, selectTest */ /* end documentation of signals */ /*! \overload Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref setText). */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mText(), mTextFlags(Qt::AlignCenter), mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below mTextColor(Qt::black), mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { if (parentPlot) { mFont = parentPlot->font(); mSelectedFont = parentPlot->font(); } setMargins(QMargins(2, 2, 2, 2)); } /*! \overload Creates a new QCPTextElement instance and sets default values. The initial text is set to \a text. */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) : QCPLayoutElement(parentPlot), mText(text), mTextFlags(Qt::AlignCenter), mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below mTextColor(Qt::black), mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { if (parentPlot) { mFont = parentPlot->font(); mSelectedFont = parentPlot->font(); } setMargins(QMargins(2, 2, 2, 2)); } /*! \overload Creates a new QCPTextElement instance and sets default values. The initial text is set to \a text with \a pointSize. */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) : QCPLayoutElement(parentPlot), mText(text), mTextFlags(Qt::AlignCenter), mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below mTextColor(Qt::black), mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer if (parentPlot) { mFont = parentPlot->font(); mFont.setPointSizeF(pointSize); mSelectedFont = parentPlot->font(); mSelectedFont.setPointSizeF(pointSize); } setMargins(QMargins(2, 2, 2, 2)); } /*! \overload Creates a new QCPTextElement instance and sets default values. The initial text is set to \a text with \a pointSize and the specified \a fontFamily. */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) : QCPLayoutElement(parentPlot), mText(text), mTextFlags(Qt::AlignCenter), mFont(QFont(fontFamily, int(pointSize))), mTextColor(Qt::black), mSelectedFont(QFont(fontFamily, int(pointSize))), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer setMargins(QMargins(2, 2, 2, 2)); } /*! \overload Creates a new QCPTextElement instance and sets default values. The initial text is set to \a text with the specified \a font. */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) : QCPLayoutElement(parentPlot), mText(text), mTextFlags(Qt::AlignCenter), mFont(font), mTextColor(Qt::black), mSelectedFont(font), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { setMargins(QMargins(2, 2, 2, 2)); } /*! Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". \see setFont, setTextColor, setTextFlags */ void QCPTextElement::setText(const QString &text) { mText = text; } /*! Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of \c Qt::AlignmentFlag and \c Qt::TextFlag enums. Possible enums are: - Qt::AlignLeft - Qt::AlignRight - Qt::AlignHCenter - Qt::AlignJustify - Qt::AlignTop - Qt::AlignBottom - Qt::AlignVCenter - Qt::AlignCenter - Qt::TextDontClip - Qt::TextSingleLine - Qt::TextExpandTabs - Qt::TextShowMnemonic - Qt::TextWordWrap - Qt::TextIncludeTrailingSpaces */ void QCPTextElement::setTextFlags(int flags) { mTextFlags = flags; } /*! Sets the \a font of the text. \see setTextColor, setSelectedFont */ void QCPTextElement::setFont(const QFont &font) { mFont = font; } /*! Sets the \a color of the text. \see setFont, setSelectedTextColor */ void QCPTextElement::setTextColor(const QColor &color) { mTextColor = color; } /*! Sets the \a font of the text that will be used if the text element is selected (\ref setSelected). \see setFont */ void QCPTextElement::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the \a color of the text that will be used if the text element is selected (\ref setSelected). \see setTextColor */ void QCPTextElement::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether the user may select this text element. Note that even when \a selectable is set to false, the selection state may be changed programmatically via \ref setSelected. */ void QCPTextElement::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets the selection state of this text element to \a selected. If the selection has changed, \ref selectionChanged is emitted. Note that this function can change the selection state independently of the current \ref setSelectable state. */ void QCPTextElement::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeOther); } /* inherits documentation from base class */ void QCPTextElement::draw(QCPPainter *painter) { painter->setFont(mainFont()); painter->setPen(QPen(mainTextColor())); painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect); } /* inherits documentation from base class */ QSize QCPTextElement::minimumOuterSizeHint() const { QFontMetrics metrics(mFont); QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size()); result.rwidth() += mMargins.left()+mMargins.right(); result.rheight() += mMargins.top()+mMargins.bottom(); return result; } /* inherits documentation from base class */ QSize QCPTextElement::maximumOuterSizeHint() const { QFontMetrics metrics(mFont); QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size()); result.setWidth(QWIDGETSIZE_MAX); result.rheight() += mMargins.top()+mMargins.bottom(); return result; } /* inherits documentation from base class */ void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPTextElement::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /*! Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is within the bounding box of the text element's text. Note that this bounding box is updated in the draw call. If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text element is not selectable (\ref setSelectable), returns -1. \seebaseclassmethod */ double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (mTextBoundingRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /*! Accepts the mouse event in order to emit the according click signal in the \ref mouseReleaseEvent. \seebaseclassmethod */ void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details) { Q_UNUSED(details) event->accept(); } /*! Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref mousePressEvent. \seebaseclassmethod */ void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { if ((QPointF(event->pos())-startPos).manhattanLength() <= 3) emit clicked(event); } /*! Emits the \ref doubleClicked signal. \seebaseclassmethod */ void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) { Q_UNUSED(details) emit doubleClicked(event); } /*! \internal Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to true, else mFont is returned. */ QFont QCPTextElement::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to true, else mTextColor is returned. */ QColor QCPTextElement::mainTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } /* end of 'src/layoutelements/layoutelement-textelement.cpp' */ /* including file 'src/layoutelements/layoutelement-colorscale.cpp' */ /* modified 2021-03-29T02:30:44, size 26531 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScale //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScale \brief A color scale for use with color coding data such as QCPColorMap This layout element can be placed on the plot to correlate a color gradient with data values. It is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". \image html QCPColorScale.png The color scale can be either horizontal or vertical, as shown in the image above. The orientation and the side where the numbers appear is controlled with \ref setType. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are connected, they share their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color scale, to make them all synchronize these properties. To have finer control over the number display and axis behaviour, you can directly access the \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if you want to change the number of automatically generated ticks, call \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount Placing a color scale next to the main axis rect works like with any other layout element: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation In this case we have placed it to the right of the default axis rect, so it wasn't necessary to call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color scale can be set with \ref setLabel. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup Color scales are initialized with a non-zero minimum top and bottom margin (\ref setMinimumMargins), because vertical color scales are most common and the minimum top/bottom margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you might want to also change the minimum margins accordingly, e.g. setMinimumMargins(QMargins(6, 0, 6, 0)). */ /* start documentation of inline functions */ /*! \fn QCPAxis *QCPColorScale::axis() const Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on the QCPColorScale or on its QCPAxis. If the type of the color scale is changed with \ref setType, the axis returned by this method will change, too, to either the left, right, bottom or top axis, depending on which type was set. */ /* end documentation of signals */ /* start documentation of signals */ /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange); This signal is emitted when the data range changes. \see setDataRange */ /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the data scale type changes. \see setDataScaleType */ /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient); This signal is emitted when the gradient changes. \see setGradient */ /* end documentation of signals */ /*! Constructs a new QCPColorScale. */ QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight mDataScaleType(QCPAxis::stLinear), mGradient(QCPColorGradient::gpCold), mBarWidth(20), mAxisRect(new QCPColorScaleAxisRectPrivate(this)) { setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) setType(QCPAxis::atRight); setDataRange(QCPRange(0, 6)); } QCPColorScale::~QCPColorScale() { delete mAxisRect; } /* undocumented getter */ QString QCPColorScale::label() const { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return QString(); } return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /* undocumented getter */ bool QCPColorScale::rangeZoom() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /*! Sets at which side of the color scale the axis is placed, and thus also its orientation. Note that after setting \a type to a different value, the axis returned by \ref axis() will be a different one. The new axis will adopt the following properties from the previous axis: The range, scale type, label and ticker (the latter will be shared and not copied). */ void QCPColorScale::setType(QCPAxis::AxisType type) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (mType != type) { mType = type; QCPRange rangeTransfer(0, 6); QString labelTransfer; QSharedPointer tickerTransfer; // transfer/revert some settings on old axis if it exists: bool doTransfer = !mColorAxis.isNull(); if (doTransfer) { rangeTransfer = mColorAxis.data()->range(); labelTransfer = mColorAxis.data()->label(); tickerTransfer = mColorAxis.data()->ticker(); mColorAxis.data()->setLabel(QString()); disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } const QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; foreach (QCPAxis::AxisType atype, allAxisTypes) { mAxisRect.data()->axis(atype)->setTicks(atype == mType); mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); } // set new mColorAxis pointer: mColorAxis = mAxisRect.data()->axis(mType); // transfer settings to new axis: if (doTransfer) { mColorAxis.data()->setRange(rangeTransfer); // range transfer necessary if axis changes from vertical to horizontal or vice versa (axes with same orientation are synchronized via signals) mColorAxis.data()->setLabel(labelTransfer); mColorAxis.data()->setTicker(tickerTransfer); } connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); mAxisRect.data()->setRangeDragAxes(QList() << mColorAxis.data()); } } /*! Sets the range spanned by the color gradient and that is shown by the axis in the color scale. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its range with \ref QCPAxis::setRange. \see setDataScaleType, setGradient, rescaleDataRange */ void QCPColorScale::setDataRange(const QCPRange &dataRange) { if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { mDataRange = dataRange; if (mColorAxis) mColorAxis.data()->setRange(mDataRange); emit dataRangeChanged(mDataRange); } } /*! Sets the scale type of the color scale, i.e. whether values are associated with colors linearly or logarithmically. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its scale type with \ref QCPAxis::setScaleType. Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog : \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. \see setDataRange, setGradient */ void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; if (mColorAxis) mColorAxis.data()->setScaleType(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); emit dataScaleTypeChanged(mDataScaleType); } } /*! Sets the color gradient that will be used to represent data values. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. \see setDataRange, setDataScaleType */ void QCPColorScale::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; if (mAxisRect) mAxisRect.data()->mGradientImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on the internal \ref axis. */ void QCPColorScale::setLabel(const QString &str) { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return; } mColorAxis.data()->setLabel(str); } /*! Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed will have. */ void QCPColorScale::setBarWidth(int width) { mBarWidth = width; } /*! Sets whether the user can drag the data range (\ref setDataRange). Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeDrag(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) { mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); } else { #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0) mAxisRect.data()->setRangeDrag(nullptr); #else mAxisRect.data()->setRangeDrag({}); #endif } } /*! Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeZoom(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) { mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); } else { #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0) mAxisRect.data()->setRangeDrag(nullptr); #else mAxisRect.data()->setRangeZoom({}); #endif } } /*! Returns a list of all the color maps associated with this color scale. */ QList QCPColorScale::colorMaps() const { QList result; for (int i=0; iplottableCount(); ++i) { if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) if (cm->colorScale() == this) result.append(cm); } return result; } /*! Changes the data range such that all color maps associated with this color scale are fully mapped to the gradient in the data dimension. \see setDataRange */ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) { QList maps = colorMaps(); QCPRange newRange; bool haveRange = false; QCP::SignDomain sign = QCP::sdBoth; if (mDataScaleType == QCPAxis::stLogarithmic) sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); foreach (QCPColorMap *map, maps) { if (!map->realVisibility() && onlyVisibleMaps) continue; QCPRange mapRange; if (map->colorScale() == this) { bool currentFoundRange = true; mapRange = map->data()->dataBounds(); if (sign == QCP::sdPositive) { if (mapRange.lower <= 0 && mapRange.upper > 0) mapRange.lower = mapRange.upper*1e-3; else if (mapRange.lower <= 0 && mapRange.upper <= 0) currentFoundRange = false; } else if (sign == QCP::sdNegative) { if (mapRange.upper >= 0 && mapRange.lower < 0) mapRange.upper = mapRange.lower*1e-3; else if (mapRange.upper >= 0 && mapRange.lower >= 0) currentFoundRange = false; } if (currentFoundRange) { if (!haveRange) newRange = mapRange; else newRange.expand(mapRange); haveRange = true; } } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mDataScaleType == QCPAxis::stLinear) { newRange.lower = center-mDataRange.size()/2.0; newRange.upper = center+mDataRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); } } setDataRange(newRange); } } /* inherits documentation from base class */ void QCPColorScale::update(UpdatePhase phase) { QCPLayoutElement::update(phase); if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->update(phase); switch (phase) { case upMargins: { if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) { setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()); setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()); } else { setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX); setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0); } break; } case upLayout: { mAxisRect.data()->setOuterRect(rect()); break; } default: break; } } /* inherits documentation from base class */ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mousePressEvent(event, details); } /* inherits documentation from base class */ void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseMoveEvent(event, startPos); } /* inherits documentation from base class */ void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseReleaseEvent(event, startPos); } /* inherits documentation from base class */ void QCPColorScale::wheelEvent(QWheelEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->wheelEvent(event); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScaleAxisRectPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScaleAxisRectPrivate \internal \brief An axis rect subclass for use in a QCPColorScale This is a private class and not part of the public QCustomPlot interface. It provides the axis rect functionality for the QCPColorScale class. */ /*! Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : QCPAxisRect(parentColorScale->parentPlot(), true), mParentColorScale(parentColorScale), mGradientImageInvalidated(true) { setParentLayerable(parentColorScale); setMinimumMargins(QMargins(0, 0, 0, 0)); const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { axis(type)->setVisible(true); axis(type)->grid()->setVisible(false); axis(type)->setPadding(0); connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); } connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); // make layer transfers of color scale transfer to axis rect and axes // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); foreach (QCPAxis::AxisType type, allAxisTypes) connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); } /*! \internal Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation. \seebaseclassmethod */ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) { if (mGradientImageInvalidated) updateGradientImage(); bool mirrorHorz = false; bool mirrorVert = false; if (mParentColorScale->mColorAxis) { mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); } painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); QCPAxisRect::draw(painter); } /*! \internal Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to generate a gradient image. This gradient image will be used in the \ref draw method. */ void QCPColorScaleAxisRectPrivate::updateGradientImage() { if (rect().isEmpty()) return; const QImage::Format format = QImage::Format_ARGB32_Premultiplied; int n = mParentColorScale->mGradient.levelCount(); int w, h; QVector data(n); for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) { w = n; h = rect().height(); mGradientImage = QImage(w, h, format); QVector pixels; for (int y=0; y(mGradientImage.scanLine(y))); mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); for (int y=1; y(mGradientImage.scanLine(y)); const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); for (int x=0; x allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { if (QCPAxis *senderAxis = qobject_cast(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectedParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); else axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); } } } /*! \internal This slot is connected to the selectableChanged signals of the four axes in the constructor. It synchronizes the selectability of the axes. */ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) { // synchronize axis base selectability: const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { if (QCPAxis *senderAxis = qobject_cast(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectableParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); else axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); } } } /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */ /* including file 'src/plottables/plottable-graph.cpp' */ /* modified 2021-03-29T02:30:44, size 74518 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGraphData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGraphData \brief Holds the data of one single data point for QCPGraph. The stored data is: \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey) \li \a value: coordinate on the value axis of this data point (this is the \a mainValue) The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the documentation there for an explanation regarding the data type's generic methods. \see QCPGraphDataContainer */ /* start documentation of inline functions */ /*! \fn double QCPGraphData::sortKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey) Returns a data point with the specified \a sortKey. All other members are set to zero. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static static bool QCPGraphData::sortKeyIsMainKey() Since the member \a key is both the data point key coordinate and the data ordering parameter, this method returns true. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPGraphData::mainKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPGraphData::mainValue() const Returns the \a value member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn QCPRange QCPGraphData::valueRange() const Returns a QCPRange with both lower and upper boundary set to \a value of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /* end documentation of inline functions */ /*! Constructs a data point with key and value set to zero. */ QCPGraphData::QCPGraphData() : key(0), value(0) { } /*! Constructs a data point with the specified \a key and \a value. */ QCPGraphData::QCPGraphData(double key, double value) : key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGraph //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGraph \brief A plottable representing a graph in a plot. \image html QCPGraph.png Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be accessed via QCustomPlot::graph. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPGraphDataContainer. Graphs are used to display single-valued data. Single-valued means that there should only be one data point per unique key coordinate. In other words, the graph can't have \a loops. If you do want to plot non-single-valued curves, rather use the QCPCurve plottable. Gaps in the graph line can be created by adding data points with NaN as value (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be separated. \section qcpgraph-appearance Changing the appearance The appearance of the graph is mainly determined by the line style, scatter style, brush and pen of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen). \subsection filling Filling under or between graphs QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill between this graph and another one, call \ref setChannelFillGraph with the other graph as parameter. \see QCustomPlot::addGraph, QCustomPlot::graph */ /* start of documentation of inline functions */ /*! \fn QSharedPointer QCPGraph::data() const Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods. */ /* end of documentation of inline functions */ /*! Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually but use QCustomPlot::removePlottable() instead. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function. */ QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable1D(keyAxis, valueAxis), mLineStyle{}, mScatterSkip{}, mAdaptiveSampling{} { // special handling for QCPGraphs to maintain the simple graph interface: mParentPlot->registerGraph(this); setPen(QPen(Qt::blue, 0)); setBrush(Qt::NoBrush); setLineStyle(lsLine); setScatterSkip(0); setChannelFillGraph(nullptr); setAdaptiveSampling(true); } QCPGraph::~QCPGraph() { } /*! \overload Replaces the current data container with the provided \a data container. Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely. Modifying the data in the container will then affect all graphs that share the container. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1 If you do not wish to share containers, but create a copy from an existing container, rather use the \ref QCPDataContainer::set method on the graph's data container directly: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2 \see addData */ void QCPGraph::setData(QSharedPointer data) { mDataContainer = data; } /*! \overload Replaces the current data with the provided points in \a keys and \a values. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. \see addData */ void QCPGraph::setData(const QVector &keys, const QVector &values, bool alreadySorted) { mDataContainer->clear(); addData(keys, values, alreadySorted); } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPGraph::setLineStyle(LineStyle ls) { mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of scatter points are skipped/not drawn after every drawn scatter point. This can be used to make the data appear sparser while for example still having a smooth line, and to improve performance for very high density plots. If \a skip is set to 0 (default), all scatter points are drawn. \see setScatterStyle */ void QCPGraph::setScatterSkip(int skip) { mScatterSkip = qMax(0, skip); } /*! Sets the target graph for filling the area between this graph and \a targetGraph with the current brush (\ref setBrush). When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To disable any filling, set the brush to Qt::NoBrush. \see setBrush */ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) { // prevent setting channel target to this graph itself: if (targetGraph == this) { qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; mChannelFillGraph = nullptr; return; } // prevent setting channel target to a graph not in the plot: if (targetGraph && targetGraph->mParentPlot != mParentPlot) { qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; mChannelFillGraph = nullptr; return; } mChannelFillGraph = targetGraph; } /*! Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive sampling technique can drastically improve the replot performance for graphs with a larger number of points (e.g. above 10,000), without notably changing the appearance of the graph. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no disadvantage in almost all cases. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are reproduced reliably, as well as the overall shape of the data set. The replot time reduces dramatically though. This allows QCustomPlot to display large amounts of data in realtime. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" Care must be taken when using high-density scatter plots in combination with adaptive sampling. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still gives a significant reduction of replot times, but not quite as much as for line plots. This is because scatter plots inherently need more data points to be preserved in order to still resemble the original, non-adaptive-sampling plot. As shown above, the results still aren't quite identical, as banding occurs for the outer data points. This is in fact intentional, such that the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, depends on the point density, i.e. the number of points in the plot. For some situations with scatter plots it might thus be desirable to manually turn adaptive sampling off. For example, when saving the plot to disk. This can be achieved by setting \a enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled back to true afterwards. */ void QCPGraph::setAdaptiveSampling(bool enabled) { mAdaptiveSampling = enabled; } /*! \overload Adds the provided points in \a keys and \a values to the current data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPGraph::addData(const QVector &keys, const QVector &values, bool alreadySorted) { if (keys.size() != values.size()) qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size(); const int n = qMin(keys.size(), values.size()); QVector tempData(n); QVector::iterator it = tempData.begin(); const QVector::iterator itEnd = tempData.end(); int i = 0; while (it != itEnd) { it->key = keys[i]; it->value = values[i]; ++it; ++i; } mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write } /*! \overload Adds the provided data point as \a key and \a value to the current data. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPGraph::addData(double key, double value) { mDataContainer->add(QCPGraphData(key, value)); } /*! Implements a selectTest specific to this plottable's point geometry. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); double result = pointDistance(pos, closestDataPoint); if (details) { int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); } return result; } else return -1; } /* inherits documentation from base class */ QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { return mDataContainer->keyRange(foundRange, inSignDomain); } /* inherits documentation from base class */ QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ void QCPGraph::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return; if (mLineStyle == lsNone && mScatterStyle.isNone()) return; QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments // loop over and draw segments of unselected/selected data: QList selectedSegments, unselectedSegments, allSegments; getDataSegments(selectedSegments, unselectedSegments); allSegments << unselectedSegments << selectedSegments; for (int i=0; i= unselectedSegments.size(); // get line pixel points appropriate to line style: QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care) getLines(&lines, lineDataRange); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPGraphDataContainer::const_iterator it; for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) { if (QCP::isInvalidData(it->key, it->value)) qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); } #endif // draw fill of graph: if (isSelectedSegment && mSelectionDecorator) mSelectionDecorator->applyBrush(painter); else painter->setBrush(mBrush); painter->setPen(Qt::NoPen); drawFill(painter, &lines); // draw line: if (mLineStyle != lsNone) { if (isSelectedSegment && mSelectionDecorator) mSelectionDecorator->applyPen(painter); else painter->setPen(mPen); painter->setBrush(Qt::NoBrush); if (mLineStyle == lsImpulse) drawImpulsePlot(painter, lines); else drawLinePlot(painter, lines); // also step plots can be drawn as a line plot } // draw scatters: QCPScatterStyle finalScatterStyle = mScatterStyle; if (isSelectedSegment && mSelectionDecorator) finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); if (!finalScatterStyle.isNone()) { getScatters(&scatters, allSegments.at(i)); drawScatterPlot(painter, scatters, finalScatterStyle); } } // draw other selection decoration that isn't just line/scatter pens and brushes: if (mSelectionDecorator) mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal This method retrieves an optimized set of data points via \ref getOptimizedLineData, and branches out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc. according to the line style of the graph. \a lines will be filled with points in pixel coordinates, that can be drawn with the according draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines aren't necessarily the original data points. For example, step line styles require additional points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a lines vector will be empty. \a dataRange specifies the beginning and ending data indices that will be taken into account for conversion. In this function, the specified range may exceed the total data bounds without harm: a correspondingly trimmed data range will be used. This takes the burden off the user of this function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref getDataSegments. \see getScatters */ void QCPGraph::getLines(QVector *lines, const QCPDataRange &dataRange) const { if (!lines) return; QCPGraphDataContainer::const_iterator begin, end; getVisibleDataBounds(begin, end, dataRange); if (begin == end) { lines->clear(); return; } QVector lineData; if (mLineStyle != lsNone) getOptimizedLineData(&lineData, begin, end); if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing) std::reverse(lineData.begin(), lineData.end()); switch (mLineStyle) { case lsNone: lines->clear(); break; case lsLine: *lines = dataToLines(lineData); break; case lsStepLeft: *lines = dataToStepLeftLines(lineData); break; case lsStepRight: *lines = dataToStepRightLines(lineData); break; case lsStepCenter: *lines = dataToStepCenterLines(lineData); break; case lsImpulse: *lines = dataToImpulseLines(lineData); break; } } /*! \internal This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be passed to \ref drawScatterPlot. \a dataRange specifies the beginning and ending data indices that will be taken into account for conversion. In this function, the specified range may exceed the total data bounds without harm: a correspondingly trimmed data range will be used. This takes the burden off the user of this function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref getDataSegments. */ void QCPGraph::getScatters(QVector *scatters, const QCPDataRange &dataRange) const { if (!scatters) return; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; } QCPGraphDataContainer::const_iterator begin, end; getVisibleDataBounds(begin, end, dataRange); if (begin == end) { scatters->clear(); return; } QVector data; getOptimizedScatterData(&data, begin, end); if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing) std::reverse(data.begin(), data.end()); scatters->resize(data.size()); if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; icoordToPixel(data.at(i).value)); (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key)); } } } else { for (int i=0; icoordToPixel(data.at(i).key)); (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value)); } } } } /*! \internal Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel coordinate points which are suitable for drawing the line style \ref lsLine. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot */ QVector QCPGraph::dataToLines(const QVector &data) const { QVector result; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } result.resize(data.size()); // transform data points to pixels: if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; icoordToPixel(data.at(i).value)); result[i].setY(keyAxis->coordToPixel(data.at(i).key)); } } else // key axis is horizontal { for (int i=0; icoordToPixel(data.at(i).key)); result[i].setY(valueAxis->coordToPixel(data.at(i).value)); } } return result; } /*! \internal Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel coordinate points which are suitable for drawing the line style \ref lsStepLeft. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot */ QVector QCPGraph::dataToStepLeftLines(const QVector &data) const { QVector result; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } result.resize(data.size()*2); // calculate steps from data and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastValue = valueAxis->coordToPixel(data.first().value); for (int i=0; icoordToPixel(data.at(i).key); result[i*2+0].setX(lastValue); result[i*2+0].setY(key); lastValue = valueAxis->coordToPixel(data.at(i).value); result[i*2+1].setX(lastValue); result[i*2+1].setY(key); } } else // key axis is horizontal { double lastValue = valueAxis->coordToPixel(data.first().value); for (int i=0; icoordToPixel(data.at(i).key); result[i*2+0].setX(key); result[i*2+0].setY(lastValue); lastValue = valueAxis->coordToPixel(data.at(i).value); result[i*2+1].setX(key); result[i*2+1].setY(lastValue); } } return result; } /*! \internal Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel coordinate points which are suitable for drawing the line style \ref lsStepRight. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot */ QVector QCPGraph::dataToStepRightLines(const QVector &data) const { QVector result; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } result.resize(data.size()*2); // calculate steps from data and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(data.first().key); for (int i=0; icoordToPixel(data.at(i).value); result[i*2+0].setX(value); result[i*2+0].setY(lastKey); lastKey = keyAxis->coordToPixel(data.at(i).key); result[i*2+1].setX(value); result[i*2+1].setY(lastKey); } } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(data.first().key); for (int i=0; icoordToPixel(data.at(i).value); result[i*2+0].setX(lastKey); result[i*2+0].setY(value); lastKey = keyAxis->coordToPixel(data.at(i).key); result[i*2+1].setX(lastKey); result[i*2+1].setY(value); } } return result; } /*! \internal Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel coordinate points which are suitable for drawing the line style \ref lsStepCenter. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot */ QVector QCPGraph::dataToStepCenterLines(const QVector &data) const { QVector result; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } result.resize(data.size()*2); // calculate steps from data and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(data.first().key); double lastValue = valueAxis->coordToPixel(data.first().value); result[0].setX(lastValue); result[0].setY(lastKey); for (int i=1; icoordToPixel(data.at(i).key)+lastKey)*0.5; result[i*2-1].setX(lastValue); result[i*2-1].setY(key); lastValue = valueAxis->coordToPixel(data.at(i).value); lastKey = keyAxis->coordToPixel(data.at(i).key); result[i*2+0].setX(lastValue); result[i*2+0].setY(key); } result[data.size()*2-1].setX(lastValue); result[data.size()*2-1].setY(lastKey); } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(data.first().key); double lastValue = valueAxis->coordToPixel(data.first().value); result[0].setX(lastKey); result[0].setY(lastValue); for (int i=1; icoordToPixel(data.at(i).key)+lastKey)*0.5; result[i*2-1].setX(key); result[i*2-1].setY(lastValue); lastValue = valueAxis->coordToPixel(data.at(i).value); lastKey = keyAxis->coordToPixel(data.at(i).key); result[i*2+0].setX(key); result[i*2+0].setY(lastValue); } result[data.size()*2-1].setX(lastKey); result[data.size()*2-1].setY(lastValue); } return result; } /*! \internal Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel coordinate points which are suitable for drawing the line style \ref lsImpulse. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot */ QVector QCPGraph::dataToImpulseLines(const QVector &data) const { QVector result; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } result.resize(data.size()*2); // transform data points to pixels: if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; icoordToPixel(data.at(i).key); result[i*2+0].setX(valueAxis->coordToPixel(0)); result[i*2+0].setY(key); result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value)); result[i*2+1].setY(key); } } else // key axis is horizontal { for (int i=0; icoordToPixel(data.at(i).key); result[i*2+0].setX(key); result[i*2+0].setY(valueAxis->coordToPixel(0)); result[i*2+1].setX(key); result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value)); } } return result; } /*! \internal Draws the fill of the graph using the specified \a painter, with the currently set brush. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas), this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN segments of the two involved graphs, before passing the overlapping pairs to \ref getChannelFillPolygon. Pass the points of this graph's line as \a lines, in pixel coordinates. \see drawLinePlot, drawImpulsePlot, drawScatterPlot */ void QCPGraph::drawFill(QCPPainter *painter, QVector *lines) const { if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return; applyFillAntialiasingHint(painter); const QVector segments = getNonNanSegments(lines, keyAxis()->orientation()); if (!mChannelFillGraph) { // draw base fill under graph, fill goes all the way to the zero-value-line: foreach (QCPDataRange segment, segments) painter->drawPolygon(getFillPolygon(lines, segment)); } else { // draw fill between this graph and mChannelFillGraph: QVector otherLines; mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount())); if (!otherLines.isEmpty()) { QVector otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation()); QVector > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines); for (int i=0; idrawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); } } } /*! \internal Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The scatters will be drawn with \a painter and have the appearance as specified in \a style. \see drawLinePlot, drawImpulsePlot */ void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const { applyScattersAntialiasingHint(painter); style.applyTo(painter, mPen); foreach (const QPointF &scatter, scatters) style.drawShape(painter, scatter.x(), scatter.y()); } /*! \internal Draws lines between the points in \a lines, given in pixel coordinates. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline */ void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector &lines) const { if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); drawPolyline(painter, lines); } } /*! \internal Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines from the regular graph data points. \see drawLinePlot, drawScatterPlot */ void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector &lines) const { if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); QPen oldPen = painter->pen(); QPen newPen = painter->pen(); newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line painter->setPen(newPen); painter->drawLines(lines); painter->setPen(oldPen); } } /*! \internal Returns via \a lineData the data points that need to be visualized for this graph when plotting graph lines, taking into consideration the currently visible axis ranges and, if \ref setAdaptiveSampling is enabled, local point densities. The considered data can be restricted further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref getDataSegments). This method is used by \ref getLines to retrieve the basic working set of data. \see getOptimizedScatterData */ void QCPGraph::getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const { if (!lineData) return; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (begin == end) return; int dataCount = int(end-begin); int maxCount = (std::numeric_limits::max)(); if (mAdaptiveSampling) { double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)); if (2*keyPixelSpan+2 < static_cast((std::numeric_limits::max)())) maxCount = int(2*keyPixelSpan+2); } if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average { QCPGraphDataContainer::const_iterator it = begin; double minValue = it->value; double maxValue = it->value; QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it; int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound)); double lastIntervalEndKey = currentIntervalStartKey; double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect while (it != end) { if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary { if (it->value < minValue) minValue = it->value; else if (it->value > maxValue) maxValue = it->value; ++intervalDataCount; } else // new pixel interval started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value)); lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); if (it->key > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value)); } else lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value)); lastIntervalEndKey = (it-1)->key; minValue = it->value; maxValue = it->value; currentIntervalFirstPoint = it; currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } ++it; } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value)); lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); } else lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value)); } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output { lineData->resize(dataCount); std::copy(begin, end, lineData->begin()); } } /*! \internal Returns via \a scatterData the data points that need to be visualized for this graph when plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref setAdaptiveSampling is enabled, local point densities. The considered data can be restricted further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref getDataSegments). This method is used by \ref getScatters to retrieve the basic working set of data. \see getOptimizedLineData */ void QCPGraph::getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const { if (!scatterData) return; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } const int scatterModulo = mScatterSkip+1; const bool doScatterSkip = mScatterSkip > 0; int beginIndex = int(begin-mDataContainer->constBegin()); int endIndex = int(end-mDataContainer->constBegin()); while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter { ++beginIndex; ++begin; } if (begin == end) return; int dataCount = int(end-begin); int maxCount = (std::numeric_limits::max)(); if (mAdaptiveSampling) { int keyPixelSpan = int(qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key))); maxCount = 2*keyPixelSpan+2; } if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average { double valueMaxRange = valueAxis->range().upper; double valueMinRange = valueAxis->range().lower; QCPGraphDataContainer::const_iterator it = begin; int itIndex = int(beginIndex); double minValue = it->value; double maxValue = it->value; QCPGraphDataContainer::const_iterator minValueIt = it; QCPGraphDataContainer::const_iterator maxValueIt = it; QCPGraphDataContainer::const_iterator currentIntervalStart = it; int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound)); double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect: if (!doScatterSkip) ++it; else { itIndex += scatterModulo; if (itIndex < endIndex) // make sure we didn't jump over end it += scatterModulo; else { it = end; itIndex = endIndex; } } // main loop over data points: while (it != end) { if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary { if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange) { minValue = it->value; minValueIt = it; } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange) { maxValue = it->value; maxValueIt = it; } ++intervalDataCount; } else // new pixel started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart; int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange) scatterData->append(*intervalIt); ++c; if (!doScatterSkip) ++intervalIt; else intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here } } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange) scatterData->append(*currentIntervalStart); minValue = it->value; maxValue = it->value; currentIntervalStart = it; currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } // advance to next data point: if (!doScatterSkip) ++it; else { itIndex += scatterModulo; if (itIndex < endIndex) // make sure we didn't jump over end it += scatterModulo; else { it = end; itIndex = endIndex; } } } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart; int intervalItIndex = int(intervalIt-mDataContainer->constBegin()); int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange) scatterData->append(*intervalIt); ++c; if (!doScatterSkip) ++intervalIt; else // here we can't guarantee that adding scatterModulo doesn't exceed "it" (because "it" is equal to "end" here, and "end" isn't scatterModulo-aligned), so check via index comparison: { intervalItIndex += scatterModulo; if (intervalItIndex < itIndex) intervalIt += scatterModulo; else { intervalIt = it; intervalItIndex = itIndex; } } } } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange) scatterData->append(*currentIntervalStart); } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output { QCPGraphDataContainer::const_iterator it = begin; int itIndex = beginIndex; scatterData->reserve(dataCount); while (it != end) { scatterData->append(*it); // advance to next data point: if (!doScatterSkip) ++it; else { itIndex += scatterModulo; if (itIndex < endIndex) it += scatterModulo; else { it = end; itIndex = endIndex; } } } } } /*! This method outputs the currently visible data range via \a begin and \a end. The returned range will also never exceed \a rangeRestriction. This method takes into account that the drawing of data lines at the axis rect border always requires the points just outside the visible axis range. So \a begin and \a end may actually indicate a range that contains one additional data point to the left and right of the visible axis range. */ void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const { if (rangeRestriction.isEmpty()) { end = mDataContainer->constEnd(); begin = end; } else { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // get visible data range: begin = mDataContainer->findBegin(keyAxis->range().lower); end = mDataContainer->findEnd(keyAxis->range().upper); // limit lower/upperEnd to rangeRestriction: mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything } } /*! \internal This method goes through the passed points in \a lineData and returns a list of the segments which don't contain NaN data points. \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c Qt::Vertical, the \a x member is checked. \see getOverlappingSegments, drawFill */ QVector QCPGraph::getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const { QVector result; const int n = lineData->size(); QCPDataRange currentSegment(-1, -1); int i = 0; if (keyOrientation == Qt::Horizontal) { while (i < n) { while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point ++i; if (i == n) break; currentSegment.setBegin(i++); while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data ++i; currentSegment.setEnd(i++); result.append(currentSegment); } } else // keyOrientation == Qt::Vertical { while (i < n) { while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point ++i; if (i == n) break; currentSegment.setBegin(i++); while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data ++i; currentSegment.setEnd(i++); result.append(currentSegment); } } return result; } /*! \internal This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and \a otherSegments, and their associated point data \a thisData and \a otherData. It returns all pairs of segments (the first from \a thisSegments, the second from \a otherSegments), which overlap in plot coordinates. This method is useful in the case of a channel fill between two graphs, when only those non-NaN segments which actually overlap in their key coordinate shall be considered for drawing a channel fill polygon. It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and that the segments don't overlap themselves. The same is assumed for the segments in \a otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments. \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon */ QVector > QCPGraph::getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const { QVector > result; if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty()) return result; int thisIndex = 0; int otherIndex = 0; const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical; while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size()) { if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow { ++thisIndex; continue; } if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow { ++otherIndex; continue; } double thisLower, thisUpper, otherLower, otherUpper; if (!verticalKey) { thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x(); thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x(); otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x(); otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x(); } else { thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y(); thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y(); otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y(); otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y(); } int bPrecedence; if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence)) result.append(QPair(thisSegments.at(thisIndex), otherSegments.at(otherIndex))); if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment ++otherIndex; else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment ++thisIndex; } return result; } /*! \internal Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper) have overlap. The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if both segment's upper bounds are identical, 0 is returned as \a bPrecedence. It is assumed that the lower bounds always have smaller or equal values than the upper bounds. \see getOverlappingSegments */ bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const { bPrecedence = 0; if (aLower > bUpper) { bPrecedence = -1; return false; } else if (bLower > aUpper) { bPrecedence = 1; return false; } else { if (aUpper > bUpper) bPrecedence = -1; else if (aUpper < bUpper) bPrecedence = 1; return true; } } /*! \internal Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. \a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or y value of the returned point, respectively. */ QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; } QPointF result; if (valueAxis->scaleType() == QCPAxis::stLinear) { if (keyAxis->orientation() == Qt::Horizontal) { result.setX(matchingDataPoint.x()); result.setY(valueAxis->coordToPixel(0)); } else // keyAxis->orientation() == Qt::Vertical { result.setX(valueAxis->coordToPixel(0)); result.setY(matchingDataPoint.y()); } } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { // In logarithmic scaling we can't just draw to value 0 so we just fill all the way // to the axis which is in the direction towards 0 if (keyAxis->orientation() == Qt::Vertical) { if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis result.setX(keyAxis->axisRect()->right()); else result.setX(keyAxis->axisRect()->left()); result.setY(matchingDataPoint.y()); } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { result.setX(matchingDataPoint.x()); if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis result.setY(keyAxis->axisRect()->top()); else result.setY(keyAxis->axisRect()->bottom()); } } return result; } /*! \internal Returns the polygon needed for drawing normal fills between this graph and the key axis. Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment which shall be used for the fill. The collection of \a lineData points described by \a segment must not contain NaN data points (see \ref getNonNanSegments). The returned fill polygon will be closed at the key axis (the zero-value line) for linear value axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect side (see \ref getFillBasePoint). For increased performance (due to implicit sharing), keep the returned QPolygonF const. \see drawFill, getNonNanSegments */ const QPolygonF QCPGraph::getFillPolygon(const QVector *lineData, QCPDataRange segment) const { if (segment.size() < 2) return QPolygonF(); QPolygonF result(segment.size()+2); result[0] = getFillBasePoint(lineData->at(segment.begin())); std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1); result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1)); return result; } /*! \internal Returns the polygon needed for drawing (partial) channel fills between this graph and the graph specified by \ref setChannelFillGraph. The data points of this graph are passed as pixel coordinates via \a thisData, the data of the other graph as \a otherData. The returned polygon will be calculated for the specified data segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a otherData, respectively. The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap need to be processed here. For increased performance due to implicit sharing, keep the returned QPolygonF const. \see drawFill, getOverlappingSegments, getNonNanSegments */ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *thisData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) const { if (!mChannelFillGraph) return QPolygonF(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation()) return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis) if (thisData->isEmpty()) return QPolygonF(); QVector thisSegmentData(thisSegment.size()); QVector otherSegmentData(otherSegment.size()); std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin()); std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin()); // pointers to be able to swap them, depending which data range needs cropping: QVector *staticData = &thisSegmentData; QVector *croppedData = &otherSegmentData; // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): if (keyAxis->orientation() == Qt::Horizontal) { // x is key // crop lower bound: if (staticData->first().x() < croppedData->first().x()) // other one must be cropped qSwap(staticData, croppedData); const int lowBound = findIndexBelowX(croppedData, staticData->first().x()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x())) slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); else slope = 0; (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); (*croppedData)[0].setX(staticData->first().x()); // crop upper bound: if (staticData->last().x() > croppedData->last().x()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexAboveX(croppedData, staticData->last().x()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation const int li = croppedData->size()-1; // last index if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x())) slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); else slope = 0; (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); (*croppedData)[li].setX(staticData->last().x()); } else // mKeyAxis->orientation() == Qt::Vertical { // y is key // crop lower bound: if (staticData->first().y() < croppedData->first().y()) // other one must be cropped qSwap(staticData, croppedData); int lowBound = findIndexBelowY(croppedData, staticData->first().y()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); else slope = 0; (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); (*croppedData)[0].setY(staticData->first().y()); // crop upper bound: if (staticData->last().y() > croppedData->last().y()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexAboveY(croppedData, staticData->last().y()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation int li = croppedData->size()-1; // last index if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); else slope = 0; (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); (*croppedData)[li].setY(staticData->last().y()); } // return joined: for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted thisSegmentData << otherSegmentData.at(i); return QPolygonF(thisSegmentData); } /*! \internal Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is horizontal. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveX(const QVector *data, double x) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).x() < x) { if (isize()-1) return i+1; else return data->size()-1; } } return -1; } /*! \internal Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is horizontal. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowX(const QVector *data, double x) const { for (int i=0; isize(); ++i) { if (data->at(i).x() > x) { if (i>0) return i-1; else return 0; } } return -1; } /*! \internal Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is vertical. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveY(const QVector *data, double y) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).y() < y) { if (isize()-1) return i+1; else return data->size()-1; } } return -1; } /*! \internal Calculates the minimum distance in pixels the graph's representation has from the given \a pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if the graph has a line representation, the returned distance may be smaller than the distance to the \a closestData point, since the distance to the graph line is also taken into account. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0. */ double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const { closestData = mDataContainer->constEnd(); if (mDataContainer->isEmpty()) return -1.0; if (mLineStyle == lsNone && mScatterStyle.isNone()) return -1.0; // calculate minimum distances to graph data points and find closestData iterator: double minDistSqr = (std::numeric_limits::max)(); // determine which key range comes into question, taking selection tolerance around pos into account: double posKeyMin, posKeyMax, dummy; pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy); pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy); if (posKeyMin > posKeyMax) qSwap(posKeyMin, posKeyMax); // iterate over found data points and then choose the one with the shortest distance to pos: QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true); QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true); for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it) { const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestData = it; } } // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): if (mLineStyle != lsNone) { // line displayed, calculate distance to line segments: QVector lineData; getLines(&lineData, QCPDataRange(0, dataCount())); // don't limit data range further since with sharp data spikes, line segments may be closer to test point than segments with closer key coordinate QCPVector2D p(pixelPoint); const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected for (int i=0; i *data, double y) const { for (int i=0; isize(); ++i) { if (data->at(i).y() > y) { if (i>0) return i-1; else return 0; } } return -1; } /* end of 'src/plottables/plottable-graph.cpp' */ /* including file 'src/plottables/plottable-curve.cpp' */ /* modified 2021-03-29T02:30:44, size 63851 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurveData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurveData \brief Holds the data of one single data point for QCPCurve. The stored data is: \li \a t: the free ordering parameter of this curve point, like in the mathematical vector (x(t), y(t)). (This is the \a sortKey) \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey) \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue) The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the documentation there for an explanation regarding the data type's generic methods. \see QCPCurveDataContainer */ /* start documentation of inline functions */ /*! \fn double QCPCurveData::sortKey() const Returns the \a t member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey) Returns a data point with the specified \a sortKey (assigned to the data point's \a t member). All other members are set to zero. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static static bool QCPCurveData::sortKeyIsMainKey() Since the member \a key is the data point key coordinate and the member \a t is the data ordering parameter, this method returns false. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPCurveData::mainKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPCurveData::mainValue() const Returns the \a value member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn QCPRange QCPCurveData::valueRange() const Returns a QCPRange with both lower and upper boundary set to \a value of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /* end documentation of inline functions */ /*! Constructs a curve data point with t, key and value set to zero. */ QCPCurveData::QCPCurveData() : t(0), key(0), value(0) { } /*! Constructs a curve data point with the specified \a t, \a key and \a value. */ QCPCurveData::QCPCurveData(double t, double key, double value) : t(t), key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurve \brief A plottable representing a parametric curve in a plot. \image html QCPCurve.png Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, so their visual representation can have \a loops. This is realized by introducing a third coordinate \a t, which defines the order of the points described by the other two coordinates \a x and \a y. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can also access and modify the curve's data via the \ref data method, which returns a pointer to the internal \ref QCPCurveDataContainer. Gaps in the curve can be created by adding data points with NaN as key and value (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be separated. \section qcpcurve-appearance Changing the appearance The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). \section qcpcurve-usage Usage Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2 */ /* start of documentation of inline functions */ /*! \fn QSharedPointer QCPCurve::data() const Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods. */ /* end of documentation of inline functions */ /*! Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually but use QCustomPlot::removePlottable() instead. */ QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable1D(keyAxis, valueAxis), mScatterSkip{}, mLineStyle{} { // modify inherited properties from abstract plottable: setPen(QPen(Qt::blue, 0)); setBrush(Qt::NoBrush); setScatterStyle(QCPScatterStyle()); setLineStyle(lsLine); setScatterSkip(0); } QCPCurve::~QCPCurve() { } /*! \overload Replaces the current data container with the provided \a data container. Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely. Modifying the data in the container will then affect all curves that share the container. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1 If you do not wish to share containers, but create a copy from an existing container, rather use the \ref QCPDataContainer::set method on the curve's data container directly: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2 \see addData */ void QCPCurve::setData(QSharedPointer data) { mDataContainer = data; } /*! \overload Replaces the current data with the provided points in \a t, \a keys and \a values. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a t in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. \see addData */ void QCPCurve::setData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted) { mDataContainer->clear(); addData(t, keys, values, alreadySorted); } /*! \overload Replaces the current data with the provided points in \a keys and \a values. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. The t parameter of each data point will be set to the integer index of the respective key/value pair. \see addData */ void QCPCurve::setData(const QVector &keys, const QVector &values) { mDataContainer->clear(); addData(keys, values); } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of scatter points are skipped/not drawn after every drawn scatter point. This can be used to make the data appear sparser while for example still having a smooth line, and to improve performance for very high density plots. If \a skip is set to 0 (default), all scatter points are drawn. \see setScatterStyle */ void QCPCurve::setScatterSkip(int skip) { mScatterSkip = qMax(0, skip); } /*! Sets how the single data points are connected in the plot or how they are represented visually apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) { mLineStyle = style; } /*! \overload Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPCurve::addData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted) { if (t.size() != keys.size() || t.size() != values.size()) qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size(); const int n = qMin(qMin(t.size(), keys.size()), values.size()); QVector tempData(n); QVector::iterator it = tempData.begin(); const QVector::iterator itEnd = tempData.end(); int i = 0; while (it != itEnd) { it->t = t[i]; it->key = keys[i]; it->value = values[i]; ++it; ++i; } mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write } /*! \overload Adds the provided points in \a keys and \a values to the current data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. The t parameter of each data point will be set to the integer index of the respective key/value pair. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPCurve::addData(const QVector &keys, const QVector &values) { if (keys.size() != values.size()) qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size(); const int n = qMin(keys.size(), values.size()); double tStart; if (!mDataContainer->isEmpty()) tStart = (mDataContainer->constEnd()-1)->t + 1.0; else tStart = 0; QVector tempData(n); QVector::iterator it = tempData.begin(); const QVector::iterator itEnd = tempData.end(); int i = 0; while (it != itEnd) { it->t = tStart + i; it->key = keys[i]; it->value = values[i]; ++it; ++i; } mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write } /*! \overload Adds the provided data point as \a t, \a key and \a value to the current data. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPCurve::addData(double t, double key, double value) { mDataContainer->add(QCPCurveData(t, key, value)); } /*! \overload Adds the provided data point as \a key and \a value to the current data. The t parameter is generated automatically by increments of 1 for each point, starting at the highest t of previously existing data or 0, if the curve data is empty. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPCurve::addData(double key, double value) { if (!mDataContainer->isEmpty()) mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value)); else mDataContainer->add(QCPCurveData(0.0, key, value)); } /*! Implements a selectTest specific to this plottable's point geometry. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); double result = pointDistance(pos, closestDataPoint); if (details) { int pointIndex = int( closestDataPoint-mDataContainer->constBegin() ); details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); } return result; } else return -1; } /* inherits documentation from base class */ QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { return mDataContainer->keyRange(foundRange, inSignDomain); } /* inherits documentation from base class */ QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ void QCPCurve::draw(QCPPainter *painter) { if (mDataContainer->isEmpty()) return; // allocate line vector: QVector lines, scatters; // loop over and draw segments of unselected/selected data: QList selectedSegments, unselectedSegments, allSegments; getDataSegments(selectedSegments, unselectedSegments); allSegments << unselectedSegments << selectedSegments; for (int i=0; i= unselectedSegments.size(); // fill with curve data: QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width if (isSelectedSegment && mSelectionDecorator) finalCurvePen = mSelectionDecorator->pen(); QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getCurveLines takes care) getCurveLines(&lines, lineDataRange, finalCurvePen.widthF()); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) { if (QCP::isInvalidData(it->t) || QCP::isInvalidData(it->key, it->value)) qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); } #endif // draw curve fill: applyFillAntialiasingHint(painter); if (isSelectedSegment && mSelectionDecorator) mSelectionDecorator->applyBrush(painter); else painter->setBrush(mBrush); painter->setPen(Qt::NoPen); if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) painter->drawPolygon(QPolygonF(lines)); // draw curve line: if (mLineStyle != lsNone) { painter->setPen(finalCurvePen); painter->setBrush(Qt::NoBrush); drawCurveLine(painter, lines); } // draw scatters: QCPScatterStyle finalScatterStyle = mScatterStyle; if (isSelectedSegment && mSelectionDecorator) finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); if (!finalScatterStyle.isNone()) { getScatters(&scatters, allSegments.at(i), finalScatterStyle.size()); drawScatterPlot(painter, scatters, finalScatterStyle); } } // draw other selection decoration that isn't just line/scatter pens and brushes: if (mSelectionDecorator) mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal Draws lines between the points in \a lines, given in pixel coordinates. \see drawScatterPlot, getCurveLines */ void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector &lines) const { if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); drawPolyline(painter, lines); } } /*! \internal Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The scatters will be drawn with \a painter and have the appearance as specified in \a style. \see drawCurveLine, getCurveLines */ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const { // draw scatter point symbols: applyScattersAntialiasingHint(painter); style.applyTo(painter, mPen); foreach (const QPointF &point, points) if (!qIsNaN(point.x()) && !qIsNaN(point.y())) style.drawShape(painter, point); } /*! \internal Called by \ref draw to generate points in pixel coordinates which represent the line of the curve. Line segments that aren't visible in the current axis rect are handled in an optimized way. They are projected onto a rectangle slightly larger than the visible axis rect and simplified regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside the visible axis rect by generating new temporary points on the outer rect if necessary. \a lines will be filled with points in pixel coordinates, that can be drawn with \ref drawCurveLine. \a dataRange specifies the beginning and ending data indices that will be taken into account for conversion. In this function, the specified range may exceed the total data bounds without harm: a correspondingly trimmed data range will be used. This takes the burden off the user of this function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref getDataSegments. \a penWidth specifies the pen width that will be used to later draw the lines generated by this function. This is needed here to calculate an accordingly wider margin around the axis rect when performing the line optimization. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints. \see drawCurveLine, drawScatterPlot */ void QCPCurve::getCurveLines(QVector *lines, const QCPDataRange &dataRange, double penWidth) const { if (!lines) return; lines->clear(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // add margins to rect to compensate for stroke width const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation()); const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation()); const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation()); const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation()); QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin(); QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd(); mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange); if (itBegin == itEnd) return; QCPCurveDataContainer::const_iterator it = itBegin; QCPCurveDataContainer::const_iterator prevIt = itEnd-1; int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin); QVector trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right) while (it != itEnd) { const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin); if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R { if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal { QPointF crossA, crossB; if (prevRegion == 5) // we're coming from R, so add this point optimized { lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin)); // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); } else if (mayTraverse(prevRegion, currentRegion) && getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB)) { // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point: QVector beforeTraverseCornerPoints, afterTraverseCornerPoints; getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints); if (it != itBegin) { *lines << beforeTraverseCornerPoints; lines->append(crossA); lines->append(crossB); *lines << afterTraverseCornerPoints; } else { lines->append(crossB); *lines << afterTraverseCornerPoints; trailingPoints << beforeTraverseCornerPoints << crossA ; } } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s) { *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); } } else // segment does end in R, so we add previous point optimized and this point at original position { if (it == itBegin) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); else lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin)); lines->append(coordsToPixels(it->key, it->value)); } } else // region didn't change { if (currentRegion == 5) // still in R, keep adding original points { lines->append(coordsToPixels(it->key, it->value)); } else // still outside R, no need to add anything { // see how this is not doing anything? That's the main optimization... } } prevIt = it; prevRegion = currentRegion; ++it; } *lines << trailingPoints; } /*! \internal Called by \ref draw to generate points in pixel coordinates which represent the scatters of the curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly sparser. Scatters that aren't visible in the current axis rect are optimized away. \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref drawScatterPlot. \a dataRange specifies the beginning and ending data indices that will be taken into account for conversion. \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel coordinates generated by this function. This is needed here to calculate an accordingly wider margin around the axis rect when performing the data point reduction. \see draw, drawScatterPlot */ void QCPCurve::getScatters(QVector *scatters, const QCPDataRange &dataRange, double scatterWidth) const { if (!scatters) return; scatters->clear(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin(); QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd(); mDataContainer->limitIteratorsToDataRange(begin, end, dataRange); if (begin == end) return; const int scatterModulo = mScatterSkip+1; const bool doScatterSkip = mScatterSkip > 0; int endIndex = int( end-mDataContainer->constBegin() ); QCPRange keyRange = keyAxis->range(); QCPRange valueRange = valueAxis->range(); // extend range to include width of scatter symbols: keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation()); keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation()); valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation()); valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation()); QCPCurveDataContainer::const_iterator it = begin; int itIndex = int( begin-mDataContainer->constBegin() ); while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter { ++itIndex; ++it; } if (keyAxis->orientation() == Qt::Vertical) { while (it != end) { if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value)) scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key))); // advance iterator to next (non-skipped) data point: if (!doScatterSkip) ++it; else { itIndex += scatterModulo; if (itIndex < endIndex) // make sure we didn't jump over end it += scatterModulo; else { it = end; itIndex = endIndex; } } } } else { while (it != end) { if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value)) scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value))); // advance iterator to next (non-skipped) data point: if (!doScatterSkip) ++it; else { itIndex += scatterModulo; if (itIndex < endIndex) // make sure we didn't jump over end it += scatterModulo; else { it = end; itIndex = endIndex; } } } } } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveLines. It returns the region of the given point (\a key, \a value) with respect to a rectangle defined by \a keyMin, \a keyMax, \a valueMin, and \a valueMax. The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a keyMin to \a keyMax):
147
258
369
With the rectangle being region 5, and the outer regions extending infinitely outwards. In the curve optimization algorithm, region 5 is considered to be the visible portion of the plot. */ int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { if (key < keyMin) // region 123 { if (value > valueMax) return 1; else if (value < valueMin) return 3; else return 2; } else if (key > keyMax) // region 789 { if (value > valueMax) return 7; else if (value < valueMin) return 9; else return 8; } else // region 456 { if (value > valueMax) return 4; else if (value < valueMin) return 6; else return 5; } } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveLines. This method is used in case the current segment passes from inside the visible rect (region 5, see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). It returns the intersection point of the segment with the border of region 5. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or leaving it. It is important though that \a otherRegion correctly identifies the other region not equal to 5. */ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { // The intersection point interpolation here is done in pixel coordinates, so we don't need to // differentiate between different axis scale types. Note that the nomenclature // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be // different in pixel coordinates (horz/vert key axes, reversed ranges) const double keyMinPx = mKeyAxis->coordToPixel(keyMin); const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); const double valueMinPx = mValueAxis->coordToPixel(valueMin); const double valueMaxPx = mValueAxis->coordToPixel(valueMax); const double otherValuePx = mValueAxis->coordToPixel(otherValue); const double valuePx = mValueAxis->coordToPixel(value); const double otherKeyPx = mKeyAxis->coordToPixel(otherKey); const double keyPx = mKeyAxis->coordToPixel(key); double intersectKeyPx = keyMinPx; // initial key just a fail-safe double intersectValuePx = valueMinPx; // initial value just a fail-safe switch (otherRegion) { case 1: // top and left edge { intersectValuePx = valueMaxPx; intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) { intersectKeyPx = keyMinPx; intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); } break; } case 2: // left edge { intersectKeyPx = keyMinPx; intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); break; } case 3: // bottom and left edge { intersectValuePx = valueMinPx; intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) { intersectKeyPx = keyMinPx; intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); } break; } case 4: // top edge { intersectValuePx = valueMaxPx; intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); break; } case 5: { break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table } case 6: // bottom edge { intersectValuePx = valueMinPx; intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); break; } case 7: // top and right edge { intersectValuePx = valueMaxPx; intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) { intersectKeyPx = keyMaxPx; intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); } break; } case 8: // right edge { intersectKeyPx = keyMaxPx; intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); break; } case 9: // bottom and right edge { intersectValuePx = valueMinPx; intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) { intersectKeyPx = keyMaxPx; intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); } break; } } if (mKeyAxis->orientation() == Qt::Horizontal) return {intersectKeyPx, intersectValuePx}; else return {intersectValuePx, intersectKeyPx}; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveLines. In situations where a single segment skips over multiple regions it might become necessary to add extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. This method provides these points that must be added, assuming the original segment doesn't start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by \ref getTraverseCornerPoints.) For example, consider a segment which directly goes from region 4 to 2 but originally is far out to the top left such that it doesn't cross region 5. Naively optimizing these points by projecting them on the top and left borders of region 5 will create a segment that surely crosses 5, creating a visual artifact in the plot. This method prevents this by providing extra points at the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without traversing 5. */ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { QVector result; switch (prevRegion) { case 1: { switch (currentRegion) { case 2: { result << coordsToPixels(keyMin, valueMax); break; } case 4: { result << coordsToPixels(keyMin, valueMax); break; } case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; } case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; } case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); } else { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); } break; } } break; } case 2: { switch (currentRegion) { case 1: { result << coordsToPixels(keyMin, valueMax); break; } case 3: { result << coordsToPixels(keyMin, valueMin); break; } case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; } case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; } } break; } case 3: { switch (currentRegion) { case 2: { result << coordsToPixels(keyMin, valueMin); break; } case 6: { result << coordsToPixels(keyMin, valueMin); break; } case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; } case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; } case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); } else { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); } break; } } break; } case 4: { switch (currentRegion) { case 1: { result << coordsToPixels(keyMin, valueMax); break; } case 7: { result << coordsToPixels(keyMax, valueMax); break; } case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; } case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; } } break; } case 5: { switch (currentRegion) { case 1: { result << coordsToPixels(keyMin, valueMax); break; } case 7: { result << coordsToPixels(keyMax, valueMax); break; } case 9: { result << coordsToPixels(keyMax, valueMin); break; } case 3: { result << coordsToPixels(keyMin, valueMin); break; } } break; } case 6: { switch (currentRegion) { case 3: { result << coordsToPixels(keyMin, valueMin); break; } case 9: { result << coordsToPixels(keyMax, valueMin); break; } case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; } case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; } } break; } case 7: { switch (currentRegion) { case 4: { result << coordsToPixels(keyMax, valueMax); break; } case 8: { result << coordsToPixels(keyMax, valueMax); break; } case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; } case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; } case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); } else { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); } break; } } break; } case 8: { switch (currentRegion) { case 7: { result << coordsToPixels(keyMax, valueMax); break; } case 9: { result << coordsToPixels(keyMax, valueMin); break; } case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; } case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; } } break; } case 9: { switch (currentRegion) { case 6: { result << coordsToPixels(keyMax, valueMin); break; } case 8: { result << coordsToPixels(keyMax, valueMin); break; } case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; } case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; } case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); } else { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); } break; } } break; } } return result; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveLines. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion nor \a currentRegion is 5 itself. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref getTraverse). */ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const { switch (prevRegion) { case 1: { switch (currentRegion) { case 4: case 7: case 2: case 3: return false; default: return true; } } case 2: { switch (currentRegion) { case 1: case 3: return false; default: return true; } } case 3: { switch (currentRegion) { case 1: case 2: case 6: case 9: return false; default: return true; } } case 4: { switch (currentRegion) { case 1: case 7: return false; default: return true; } } case 5: return false; // should never occur case 6: { switch (currentRegion) { case 3: case 9: return false; default: return true; } } case 7: { switch (currentRegion) { case 1: case 4: case 8: case 9: return false; default: return true; } } case 8: { switch (currentRegion) { case 7: case 9: return false; default: return true; } } case 9: { switch (currentRegion) { case 3: case 6: case 8: case 7: return false; default: return true; } } default: return true; } } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveLines. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible region 5. The return value of this method indicates whether the segment actually traverses region 5 or not. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and exit points of region 5. They will become the optimized points for that segment. */ bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const { // The intersection point interpolation here is done in pixel coordinates, so we don't need to // differentiate between different axis scale types. Note that the nomenclature // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be // different in pixel coordinates (horz/vert key axes, reversed ranges) QList intersections; const double valueMinPx = mValueAxis->coordToPixel(valueMin); const double valueMaxPx = mValueAxis->coordToPixel(valueMax); const double keyMinPx = mKeyAxis->coordToPixel(keyMin); const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); const double keyPx = mKeyAxis->coordToPixel(key); const double valuePx = mValueAxis->coordToPixel(value); const double prevKeyPx = mKeyAxis->coordToPixel(prevKey); const double prevValuePx = mValueAxis->coordToPixel(prevValue); if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis { // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx)); } else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis { // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx)); } else // line is skewed { double gamma; double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx); // check top of rect: gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx; if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma)); // check bottom of rect: gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx; if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma)); const double valuePerKeyPx = 1.0/keyPerValuePx; // check left of rect: gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx; if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx)); // check right of rect: gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx; if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx)); } // handle cases where found points isn't exactly 2: if (intersections.size() > 2) { // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: double distSqrMax = 0; QPointF pv1, pv2; for (int i=0; i distSqrMax) { pv1 = intersections.at(i); pv2 = intersections.at(k); distSqrMax = distSqr; } } } intersections = QList() << pv1 << pv2; } else if (intersections.size() != 2) { // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment return false; } // possibly re-sort points so optimized point segment has same direction as original segment: double xDelta = keyPx-prevKeyPx; double yDelta = valuePx-prevValuePx; if (mKeyAxis->orientation() != Qt::Horizontal) qSwap(xDelta, yDelta); if (xDelta*(intersections.at(1).x()-intersections.at(0).x()) + yDelta*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction intersections.move(0, 1); crossA = intersections.at(0); crossB = intersections.at(1); return true; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveLines. This method assumes that the \ref getTraverse test has returned true, so the segment definitely traverses the visible region 5 when going from \a prevRegion to \a currentRegion. In certain situations it is not sufficient to merely generate the entry and exit points of the segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in addition to traversing region 5, skips another region outside of region 5, which makes it necessary to add an optimized corner point there (very similar to the job \ref getOptimizedCornerPoints does for segments that are completely in outside regions and don't traverse 5). As an example, consider a segment going from region 1 to region 6, traversing the lower left corner of region 5. In this configuration, the segment additionally crosses the border between region 1 and 2 before entering region 5. This makes it necessary to add an additional point in the top left corner, before adding the optimized traverse points. So in this case, the output parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be empty. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse return the respective corner points. */ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector &beforeTraverse, QVector &afterTraverse) const { switch (prevRegion) { case 1: { switch (currentRegion) { case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; } case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; } case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; } } break; } case 2: { switch (currentRegion) { case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } } break; } case 3: { switch (currentRegion) { case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; } case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; } case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; } } break; } case 4: { switch (currentRegion) { case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } } break; } case 5: { break; } // shouldn't happen because this method only handles full traverses case 6: { switch (currentRegion) { case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } } break; } case 7: { switch (currentRegion) { case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; } case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; } case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; } } break; } case 8: { switch (currentRegion) { case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } } break; } case 9: { switch (currentRegion) { case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; } case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; } case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; } } break; } } } /*! \internal Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if the curve has a line representation, the returned distance may be smaller than the distance to the \a closestData point, since the distance to the curve line is also taken into account. If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns -1.0. */ double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const { closestData = mDataContainer->constEnd(); if (mDataContainer->isEmpty()) return -1.0; if (mLineStyle == lsNone && mScatterStyle.isNone()) return -1.0; if (mDataContainer->size() == 1) { QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value); closestData = mDataContainer->constBegin(); return QCPVector2D(dataPoint-pixelPoint).length(); } // calculate minimum distances to curve data points and find closestData iterator: double minDistSqr = (std::numeric_limits::max)(); // iterate over found data points and then choose the one with the shortest distance to pos: QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin(); QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd(); for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it) { const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestData = it; } } // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point): if (mLineStyle != lsNone) { QVector lines; getCurveLines(&lines, QCPDataRange(0, dataCount()), mParentPlot->selectionTolerance()*1.2); // optimized lines outside axis rect shouldn't respond to clicks at the edge, so use 1.2*tolerance as pen width for (int i=0; i QCPBarsGroup::bars() const Returns all bars currently in this group. \see bars(int index) */ /*! \fn int QCPBarsGroup::size() const Returns the number of QCPBars plottables that are part of this group. */ /*! \fn bool QCPBarsGroup::isEmpty() const Returns whether this bars group is empty. \see size */ /*! \fn bool QCPBarsGroup::contains(QCPBars *bars) Returns whether the specified \a bars plottable is part of this group. */ /* end of documentation of inline functions */ /*! Constructs a new bars group for the specified QCustomPlot instance. */ QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : QObject(parentPlot), mParentPlot(parentPlot), mSpacingType(stAbsolute), mSpacing(4) { } QCPBarsGroup::~QCPBarsGroup() { clear(); } /*! Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. The actual spacing can then be specified with \ref setSpacing. \see setSpacing */ void QCPBarsGroup::setSpacingType(SpacingType spacingType) { mSpacingType = spacingType; } /*! Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is defined by the current \ref SpacingType, which can be set with \ref setSpacingType. \see setSpacingType */ void QCPBarsGroup::setSpacing(double spacing) { mSpacing = spacing; } /*! Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars exists, returns \c nullptr. \see bars(), size */ QCPBars *QCPBarsGroup::bars(int index) const { if (index >= 0 && index < mBars.size()) { return mBars.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return nullptr; } } /*! Removes all QCPBars plottables from this group. \see isEmpty */ void QCPBarsGroup::clear() { const QList oldBars = mBars; foreach (QCPBars *bars, oldBars) bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars } /*! Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref QCPBars::setBarsGroup on the \a bars instance. \see insert, remove */ void QCPBarsGroup::append(QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } if (!mBars.contains(bars)) bars->setBarsGroup(this); else qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); } /*! Inserts the specified \a bars plottable into this group at the specified index position \a i. This gives you full control over the ordering of the bars. \a bars may already be part of this group. In that case, \a bars is just moved to the new index position. \see append, remove */ void QCPBarsGroup::insert(int i, QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } // first append to bars list normally: if (!mBars.contains(bars)) bars->setBarsGroup(this); // then move to according position: mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); } /*! Removes the specified \a bars plottable from this group. \see contains, clear */ void QCPBarsGroup::remove(QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } if (mBars.contains(bars)) bars->setBarsGroup(nullptr); else qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); } /*! \internal Adds the specified \a bars to the internal mBars list of bars. This method does not change the barsGroup property on \a bars. \see unregisterBars */ void QCPBarsGroup::registerBars(QCPBars *bars) { if (!mBars.contains(bars)) mBars.append(bars); } /*! \internal Removes the specified \a bars from the internal mBars list of bars. This method does not change the barsGroup property on \a bars. \see registerBars */ void QCPBarsGroup::unregisterBars(QCPBars *bars) { mBars.removeOne(bars); } /*! \internal Returns the pixel offset in the key dimension the specified \a bars plottable should have at the given key coordinate \a keyCoord. The offset is relative to the pixel position of the key coordinate \a keyCoord. */ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) { // find list of all base bars in case some mBars are stacked: QList baseBars; foreach (const QCPBars *b, mBars) { while (b->barBelow()) b = b->barBelow(); if (!baseBars.contains(b)) baseBars.append(b); } // find base bar this "bars" is stacked on: const QCPBars *thisBase = bars; while (thisBase->barBelow()) thisBase = thisBase->barBelow(); // determine key pixel offset of this base bars considering all other base bars in this barsgroup: double result = 0; int index = baseBars.indexOf(thisBase); if (index >= 0) { if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) { return result; } else { double lowerPixelWidth, upperPixelWidth; int startIndex; int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative if (baseBars.size() % 2 == 0) // even number of bars { startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0); result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing } else // uneven number of bars { startIndex = (baseBars.size()-1)/2+dir; baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing } for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars { baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth); result += getPixelSpacing(baseBars.at(i), keyCoord); } // finally half of our bars width: baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // correct sign of result depending on orientation and direction of key axis: result *= dir*thisBase->keyAxis()->pixelOrientation(); } } return result; } /*! \internal Returns the spacing in pixels which is between this \a bars and the following one, both at the key coordinate \a keyCoord. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only needed to get access to the key axis transformation and axis rect for the modes \ref stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in \ref stPlotCoords on a logarithmic axis. */ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) { switch (mSpacingType) { case stAbsolute: { return mSpacing; } case stAxisRectRatio: { if (bars->keyAxis()->orientation() == Qt::Horizontal) return bars->keyAxis()->axisRect()->width()*mSpacing; else return bars->keyAxis()->axisRect()->height()*mSpacing; } case stPlotCoords: { double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel); } } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBarsData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBarsData \brief Holds the data of one single data point (one bar) for QCPBars. The stored data is: \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey) \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue) The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the documentation there for an explanation regarding the data type's generic methods. \see QCPBarsDataContainer */ /* start documentation of inline functions */ /*! \fn double QCPBarsData::sortKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey) Returns a data point with the specified \a sortKey. All other members are set to zero. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static static bool QCPBarsData::sortKeyIsMainKey() Since the member \a key is both the data point key coordinate and the data ordering parameter, this method returns true. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPBarsData::mainKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPBarsData::mainValue() const Returns the \a value member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn QCPRange QCPBarsData::valueRange() const Returns a QCPRange with both lower and upper boundary set to \a value of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /* end documentation of inline functions */ /*! Constructs a bar data point with key and value set to zero. */ QCPBarsData::QCPBarsData() : key(0), value(0) { } /*! Constructs a bar data point with the specified \a key and \a value. */ QCPBarsData::QCPBarsData(double key, double value) : key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBars //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBars \brief A plottable representing a bar chart in a plot. \image html QCPBars.png To plot data, assign it with the \ref setData or \ref addData functions. \section qcpbars-appearance Changing the appearance The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear stacked. If you would like to group multiple QCPBars plottables together so they appear side by side as shown below, use QCPBarsGroup. \image html QCPBarsGroup.png \section qcpbars-usage Usage Like all data representing objects in QCustomPlot, the QCPBars is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2 */ /* start of documentation of inline functions */ /*! \fn QSharedPointer QCPBars::data() const Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods. */ /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns \c nullptr. \see barAbove, moveBelow, moveAbove */ /*! \fn QCPBars *QCPBars::barAbove() const Returns the bars plottable that is directly above this bars plottable. If there is no such plottable, returns \c nullptr. \see barBelow, moveBelow, moveAbove */ /* end of documentation of inline functions */ /*! Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually but use QCustomPlot::removePlottable() instead. */ QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable1D(keyAxis, valueAxis), mWidth(0.75), mWidthType(wtPlotCoords), mBarsGroup(nullptr), mBaseValue(0), mStackingGap(1) { // modify inherited properties from abstract plottable: mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(QColor(40, 50, 255, 30)); mBrush.setStyle(Qt::SolidPattern); mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPBars::~QCPBars() { setBarsGroup(nullptr); if (mBarBelow || mBarAbove) connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking } /*! \overload Replaces the current data container with the provided \a data container. Since a QSharedPointer is used, multiple QCPBars may share the same data container safely. Modifying the data in the container will then affect all bars that share the container. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1 If you do not wish to share containers, but create a copy from an existing container, rather use the \ref QCPDataContainer::set method on the bar's data container directly: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2 \see addData */ void QCPBars::setData(QSharedPointer data) { mDataContainer = data; } /*! \overload Replaces the current data with the provided points in \a keys and \a values. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. \see addData */ void QCPBars::setData(const QVector &keys, const QVector &values, bool alreadySorted) { mDataContainer->clear(); addData(keys, values, alreadySorted); } /*! Sets the width of the bars. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...), depends on the currently set width type, see \ref setWidthType and \ref WidthType. */ void QCPBars::setWidth(double width) { mWidth = width; } /*! Sets how the width of the bars is defined. See the documentation of \ref WidthType for an explanation of the possible values for \a widthType. The default value is \ref wtPlotCoords. \see setWidth */ void QCPBars::setWidthType(QCPBars::WidthType widthType) { mWidthType = widthType; } /*! Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref QCPBarsGroup::append. To remove this QCPBars from any group, set \a barsGroup to \c nullptr. */ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) { // deregister at old group: if (mBarsGroup) mBarsGroup->unregisterBars(this); mBarsGroup = barsGroup; // register at new group: if (mBarsGroup) mBarsGroup->registerBars(this); } /*! Sets the base value of this bars plottable. The base value defines where on the value coordinate the bars start. How far the bars extend from the base value is given by their individual value data. For example, if the base value is set to 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at 3. For stacked bars, only the base value of the bottom-most QCPBars has meaning. The default base value is 0. */ void QCPBars::setBaseValue(double baseValue) { mBaseValue = baseValue; } /*! If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by the bars below it. */ void QCPBars::setStackingGap(double pixels) { mStackingGap = pixels; } /*! \overload Adds the provided points in \a keys and \a values to the current data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPBars::addData(const QVector &keys, const QVector &values, bool alreadySorted) { if (keys.size() != values.size()) qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size(); const int n = qMin(keys.size(), values.size()); QVector tempData(n); QVector::iterator it = tempData.begin(); const QVector::iterator itEnd = tempData.end(); int i = 0; while (it != itEnd) { it->key = keys[i]; it->value = values[i]; ++it; ++i; } mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write } /*! \overload Adds the provided data point as \a key and \a value to the current data. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPBars::addData(double key, double value) { mDataContainer->add(QCPBarsData(key, value)); } /*! Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear below the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object below itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to \c nullptr. \see moveBelow, barAbove, barBelow */ void QCPBars::moveBelow(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar below it: if (bars) { if (bars->mBarBelow) connectBars(bars->mBarBelow.data(), this); connectBars(this, bars); } } /*! Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear above the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object above itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to \c nullptr. \see moveBelow, barBelow, barAbove */ void QCPBars::moveAbove(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar above it: if (bars) { if (bars->mBarAbove) connectBars(this, bars->mBarAbove.data()); connectBars(bars, this); } } /*! \copydoc QCPPlottableInterface1D::selectTestRect */ QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const { QCPDataSelection result; if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return result; if (!mKeyAxis || !mValueAxis) return result; QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd); for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { if (rect.intersects(getBarRect(it->key, it->value))) result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); } result.simplify(); return result; } /*! Implements a selectTest specific to this plottable's point geometry. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { // get visible data range: QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd); for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { if (getBarRect(it->key, it->value).contains(pos)) { if (details) { int pointIndex = int(it-mDataContainer->constBegin()); details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); } return mParentPlot->selectionTolerance()*0.99; } } } return -1; } /* inherits documentation from base class */ QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in absolute pixels), using this method to adapt the key axis range to fit the bars into the currently visible axis range will not work perfectly. Because in the moment the axis range is changed to the new range, the fixed pixel widths/spacings will represent different coordinate spans than before, which in turn would require a different key range to perfectly fit, and so on. The only solution would be to iteratively approach the perfect fitting axis range, but the mismatch isn't large enough in most applications, to warrant this here. If a user does need a better fit, he should call the corresponding axis rescale multiple times in a row. */ QCPRange range; range = mDataContainer->keyRange(foundRange, inSignDomain); // determine exact range of bars by including bar width and barsgroup offset: if (foundRange && mKeyAxis) { double lowerPixelWidth, upperPixelWidth, keyPixel; // lower range bound: getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth); keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth; if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, range.lower); const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel); if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected) range.lower = lowerCorrected; // upper range bound: getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth); keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth; if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, range.upper); const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel); if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected) range.upper = upperCorrected; } return range; } /* inherits documentation from base class */ QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { // Note: can't simply use mDataContainer->valueRange here because we need to // take into account bar base value and possible stacking of multiple bars QCPRange range; range.lower = mBaseValue; range.upper = mBaseValue; bool haveLower = true; // set to true, because baseValue should always be visible in bar charts bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin(); QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd(); if (inKeyRange != QCPRange()) { itBegin = mDataContainer->findBegin(inKeyRange.lower, false); itEnd = mDataContainer->findEnd(inKeyRange.upper, false); } for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it) { const double current = it->value + getStackedBaseValue(it->key, it->value >= 0); if (qIsNaN(current)) continue; if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } } foundRange = true; // return true because bar charts always have the 0-line visible return range; } /* inherits documentation from base class */ QPointF QCPBars::dataPixelPosition(int index) const { if (index >= 0 && index < mDataContainer->size()) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; } const QCPDataContainer::const_iterator it = mDataContainer->constBegin()+index; const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value); const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0); if (keyAxis->orientation() == Qt::Horizontal) return {keyPixel, valuePixel}; else return {valuePixel, keyPixel}; } else { qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; return {}; } } /* inherits documentation from base class */ void QCPBars::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mDataContainer->isEmpty()) return; QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd); // loop over and draw segments of unselected/selected data: QList selectedSegments, unselectedSegments, allSegments; getDataSegments(selectedSegments, unselectedSegments); allSegments << unselectedSegments << selectedSegments; for (int i=0; i= unselectedSegments.size(); QCPBarsDataContainer::const_iterator begin = visibleBegin; QCPBarsDataContainer::const_iterator end = visibleEnd; mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i)); if (begin == end) continue; for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it) { // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(it->key, it->value)) qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); #endif // draw bar: if (isSelectedSegment && mSelectionDecorator) { mSelectionDecorator->applyBrush(painter); mSelectionDecorator->applyPen(painter); } else { painter->setBrush(mBrush); painter->setPen(mPen); } applyDefaultAntialiasingHint(painter); painter->drawPolygon(getBarRect(it->key, it->value)); } } // draw other selection decoration that isn't just line/scatter pens and brushes: if (mSelectionDecorator) mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setBrush(mBrush); painter->setPen(mPen); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! \internal called by \ref draw to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. It also takes into account the bar width. \a begin returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end may also lie just outside of the visible range. if the plottable contains no data, both \a begin and \a end point to constEnd. */ void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; begin = mDataContainer->constEnd(); end = mDataContainer->constEnd(); return; } if (mDataContainer->isEmpty()) { begin = mDataContainer->constEnd(); end = mDataContainer->constEnd(); return; } // get visible data range as QMap iterators begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower); end = mDataContainer->findEnd(mKeyAxis.data()->range().upper); double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower); double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper); bool isVisible = false; // walk left from begin to find lower bar that actually is completely outside visible pixel range: QCPBarsDataContainer::const_iterator it = begin; while (it != mDataContainer->constBegin()) { --it; const QRectF barRect = getBarRect(it->key, it->value); if (mKeyAxis.data()->orientation() == Qt::Horizontal) isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound)); else // keyaxis is vertical isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound)); if (isVisible) begin = it; else break; } // walk right from ubound to find upper bar that actually is completely outside visible pixel range: it = end; while (it != mDataContainer->constEnd()) { const QRectF barRect = getBarRect(it->key, it->value); if (mKeyAxis.data()->orientation() == Qt::Horizontal) isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound)); else // keyaxis is vertical isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound)); if (isVisible) end = it+1; else break; ++it; } } /*! \internal Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref setBaseValue), and to have non-overlapping border lines with the bars stacked below. */ QRectF QCPBars::getBarRect(double key, double value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; } double lowerPixelWidth, upperPixelWidth; getPixelWidth(key, lowerPixelWidth, upperPixelWidth); double base = getStackedBaseValue(key, value >= 0); double basePixel = valueAxis->coordToPixel(base); double valuePixel = valueAxis->coordToPixel(base+value); double keyPixel = keyAxis->coordToPixel(key); if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, key); double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF()); bottomOffset += mBarBelow ? mStackingGap : 0; bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation(); if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset)) bottomOffset = valuePixel-basePixel; if (keyAxis->orientation() == Qt::Horizontal) { return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized(); } else { return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized(); } } /*! \internal This function is used to determine the width of the bar at coordinate \a key, according to the specified width (\ref setWidth) and width type (\ref setWidthType). The output parameters \a lower and \a upper return the number of pixels the bar extends to lower and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a lower is negative and \a upper positive). */ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const { lower = 0; upper = 0; switch (mWidthType) { case wtAbsolute: { upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation(); lower = -upper; break; } case wtAxisRectRatio: { if (mKeyAxis && mKeyAxis.data()->axisRect()) { if (mKeyAxis.data()->orientation() == Qt::Horizontal) upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); else upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); lower = -upper; } else qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; break; } case wtPlotCoords: { if (mKeyAxis) { double keyPixel = mKeyAxis.data()->coordToPixel(key); upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by // coordinate transform which includes range direction } else qDebug() << Q_FUNC_INFO << "No key axis defined"; break; } } } /*! \internal This function is called to find at which value to start drawing the base of a bar at \a key, when it is stacked on top of another QCPBars (e.g. with \ref moveAbove). positive and negative bars are separated per stack (positive are stacked above baseValue upwards, negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the bar for which we need the base value is negative, set \a positive to false. */ double QCPBars::getStackedBaseValue(double key, bool positive) const { if (mBarBelow) { double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack // find bars of mBarBelow that are approximately at key and find largest one: double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point if (key == 0) epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14); QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon); QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon); while (it != itEnd) { if (it->key > key-epsilon && it->key < key+epsilon) { if ((positive && it->value > max) || (!positive && it->value < max)) max = it->value; } ++it; } // recurse down the bar-stack to find the total height: return max + mBarBelow.data()->getStackedBaseValue(key, positive); } else return mBaseValue; } /*! \internal Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently above lower and below upper will become disconnected to lower/upper. If lower is zero, upper will be disconnected at the bottom. If upper is zero, lower will be disconnected at the top. */ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) { if (!lower && !upper) return; if (!lower) // disconnect upper at bottom { // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = nullptr; upper->mBarBelow = nullptr; } else if (!upper) // disconnect lower at top { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = nullptr; lower->mBarAbove = nullptr; } else // connect lower and upper { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = nullptr; // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = nullptr; lower->mBarAbove = upper; upper->mBarBelow = lower; } } /* end of 'src/plottables/plottable-bars.cpp' */ /* including file 'src/plottables/plottable-statisticalbox.cpp' */ /* modified 2021-03-29T02:30:44, size 28951 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPStatisticalBoxData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPStatisticalBoxData \brief Holds the data of one single data point for QCPStatisticalBox. The stored data is: \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey) \li \a minimum: the position of the lower whisker, typically the minimum measurement of the sample that's not considered an outlier. \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they should contain 50% of the sample data. \li \a median: the value of the median mark inside the quartile box. The median separates the sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue) \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they should contain 50% of the sample data. \li \a maximum: the position of the upper whisker, typically the maximum measurement of the sample that's not considered an outlier. \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle) The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template parameter. See the documentation there for an explanation regarding the data type's generic methods. \see QCPStatisticalBoxDataContainer */ /* start documentation of inline functions */ /*! \fn double QCPStatisticalBoxData::sortKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey) Returns a data point with the specified \a sortKey. All other members are set to zero. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey() Since the member \a key is both the data point key coordinate and the data ordering parameter, this method returns true. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPStatisticalBoxData::mainKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPStatisticalBoxData::mainValue() const Returns the \a median member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn QCPRange QCPStatisticalBoxData::valueRange() const Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box data point, possibly further expanded by outliers. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /* end documentation of inline functions */ /*! Constructs a data point with key and all values set to zero. */ QCPStatisticalBoxData::QCPStatisticalBoxData() : key(0), minimum(0), lowerQuartile(0), median(0), upperQuartile(0), maximum(0) { } /*! Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile, \a maximum and optionally a number of \a outliers. */ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers) : key(key), minimum(minimum), lowerQuartile(lowerQuartile), median(median), upperQuartile(upperQuartile), maximum(maximum), outliers(outliers) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPStatisticalBox //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPStatisticalBox \brief A plottable representing a single statistical box in a plot. \image html QCPStatisticalBox.png To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPStatisticalBoxDataContainer. Additionally each data point can itself have a list of outliers, drawn as scatter points at the key coordinate of the respective statistical box data point. They can either be set by using the respective \ref addData(double,double,double,double,double,double,const QVector&) "addData" method or accessing the individual data points through \ref data, and setting the QVector outliers of the data points directly. \section qcpstatisticalbox-appearance Changing the appearance The appearance of each data point box, ranging from the lower to the upper quartile, is controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref setWidth in plot coordinates. Each data point's visual representation also consists of two whiskers. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower quartile to the minimum. The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat. The median indicator line inside the box has its own pen, \ref setMedianPen. The outlier data points are drawn as normal scatter points. Their look can be controlled with \ref setOutlierStyle \section qcpstatisticalbox-usage Usage Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2 */ /* start documentation of inline functions */ /*! \fn QSharedPointer QCPStatisticalBox::data() const Returns a shared pointer to the internal data storage of type \ref QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods. */ /* end documentation of inline functions */ /*! Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not delete it manually but use QCustomPlot::removePlottable() instead. */ QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable1D(keyAxis, valueAxis), mWidth(0.5), mWhiskerWidth(0.2), mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap), mWhiskerBarPen(Qt::black), mWhiskerAntialiased(false), mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap), mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6) { setPen(QPen(Qt::black)); setBrush(Qt::NoBrush); } /*! \overload Replaces the current data container with the provided \a data container. Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container safely. Modifying the data in the container will then affect all statistical boxes that share the container. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1 If you do not wish to share containers, but create a copy from an existing container, rather use the \ref QCPDataContainer::set method on the statistical box data container directly: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2 \see addData */ void QCPStatisticalBox::setData(QSharedPointer data) { mDataContainer = data; } /*! \overload Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. \see addData */ void QCPStatisticalBox::setData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted) { mDataContainer->clear(); addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted); } /*! Sets the width of the boxes in key coordinates. \see setWhiskerWidth */ void QCPStatisticalBox::setWidth(double width) { mWidth = width; } /*! Sets the width of the whiskers in key coordinates. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower quartile to the minimum. \see setWidth */ void QCPStatisticalBox::setWhiskerWidth(double width) { mWhiskerWidth = width; } /*! Sets the pen used for drawing the whisker backbone. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower quartile to the minimum. Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat. \see setWhiskerBarPen */ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) { mWhiskerPen = pen; } /*! Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at each end of the whisker backbone. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower quartile to the minimum. \see setWhiskerPen */ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) { mWhiskerBarPen = pen; } /*! Sets whether the statistical boxes whiskers are drawn with antialiasing or not. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPStatisticalBox::setWhiskerAntialiased(bool enabled) { mWhiskerAntialiased = enabled; } /*! Sets the pen used for drawing the median indicator line inside the statistical boxes. */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { mMedianPen = pen; } /*! Sets the appearance of the outlier data points. Outliers can be specified with the method \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers) */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { mOutlierStyle = style; } /*! \overload Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and \a maximum to the current data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPStatisticalBox::addData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted) { if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() || median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size()) qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:" << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size(); const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size()))))); QVector tempData(n); QVector::iterator it = tempData.begin(); const QVector::iterator itEnd = tempData.end(); int i = 0; while (it != itEnd) { it->key = keys[i]; it->minimum = minimum[i]; it->lowerQuartile = lowerQuartile[i]; it->median = median[i]; it->upperQuartile = upperQuartile[i]; it->maximum = maximum[i]; ++it; ++i; } mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write } /*! \overload Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and \a maximum to the current data. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers) { mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers)); } /*! \copydoc QCPPlottableInterface1D::selectTestRect */ QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const { QCPDataSelection result; if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return result; if (!mKeyAxis || !mValueAxis) return result; QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd); for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { if (rect.intersects(getQuartileBox(it))) result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); } result.simplify(); return result; } /*! Implements a selectTest specific to this plottable's point geometry. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { // get visible data range: QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd; QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); getVisibleDataBounds(visibleBegin, visibleEnd); double minDistSqr = (std::numeric_limits::max)(); for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { if (getQuartileBox(it).contains(pos)) // quartile box { double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestDataPoint = it; } } else // whiskers { const QVector whiskerBackbones = getWhiskerBackboneLines(it); const QCPVector2D posVec(pos); foreach (const QLineF &backbone, whiskerBackbones) { double currentDistSqr = posVec.distanceSquaredToLine(backbone); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestDataPoint = it; } } } } if (details) { int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); } return qSqrt(minDistSqr); } return -1; } /* inherits documentation from base class */ QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain); // determine exact range by including width of bars/flags: if (foundRange) { if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0) range.lower -= mWidth*0.5; if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0) range.upper += mWidth*0.5; } return range; } /* inherits documentation from base class */ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { if (mDataContainer->isEmpty()) return; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd); // loop over and draw segments of unselected/selected data: QList selectedSegments, unselectedSegments, allSegments; getDataSegments(selectedSegments, unselectedSegments); allSegments << unselectedSegments << selectedSegments; for (int i=0; i= unselectedSegments.size(); QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin; QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd; mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i)); if (begin == end) continue; for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it) { // check data validity if flag set: # ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(it->key, it->minimum) || QCP::isInvalidData(it->lowerQuartile, it->median) || QCP::isInvalidData(it->upperQuartile, it->maximum)) qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name(); for (int i=0; ioutliers.size(); ++i) if (QCP::isInvalidData(it->outliers.at(i))) qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); # endif if (isSelectedSegment && mSelectionDecorator) { mSelectionDecorator->applyPen(painter); mSelectionDecorator->applyBrush(painter); } else { painter->setPen(mPen); painter->setBrush(mBrush); } QCPScatterStyle finalOutlierStyle = mOutlierStyle; if (isSelectedSegment && mSelectionDecorator) finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle); drawStatisticalBox(painter, it, finalOutlierStyle); } } // draw other selection decoration that isn't just line/scatter pens and brushes: if (mSelectionDecorator) mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->setBrush(mBrush); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! Draws the graphical representation of a single statistical box with the data given by the iterator \a it with the provided \a painter. If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle. \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines */ void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const { // draw quartile box: applyDefaultAntialiasingHint(painter); const QRectF quartileBox = getQuartileBox(it); painter->drawRect(quartileBox); // draw median line with cliprect set to quartile box: painter->save(); painter->setClipRect(quartileBox, Qt::IntersectClip); painter->setPen(mMedianPen); painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median))); painter->restore(); // draw whisker lines: applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables); painter->setPen(mWhiskerPen); painter->drawLines(getWhiskerBackboneLines(it)); painter->setPen(mWhiskerBarPen); painter->drawLines(getWhiskerBarLines(it)); // draw outliers: applyScattersAntialiasingHint(painter); outlierStyle.applyTo(painter, mPen); for (int i=0; ioutliers.size(); ++i) outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i))); } /*! \internal called by \ref draw to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. It also takes into account the bar width. \a begin returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end may also lie just outside of the visible range. if the plottable contains no data, both \a begin and \a end point to constEnd. */ void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; begin = mDataContainer->constEnd(); end = mDataContainer->constEnd(); return; } begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points } /*! \internal Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the value range from the lower to the upper quartile, of the data given by \a it. \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines */ QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const { QRectF result; result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile)); result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile)); return result; } /*! \internal Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value range from the minimum to the lower quartile, and from the upper quartile to the maximum of the data given by \a it. \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines */ QVector QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const { QVector result(2); result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone return result; } /*! \internal Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the end of the whisker backbones, at the minimum and maximum of the data given by \a it. \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines */ QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const { QVector result(2); result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar return result; } /* end of 'src/plottables/plottable-statisticalbox.cpp' */ /* including file 'src/plottables/plottable-colormap.cpp' */ /* modified 2021-03-29T02:30:44, size 48149 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorMapData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorMapData \brief Holds the two-dimensional data of a QCPColorMap plottable. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a color, depending on the value. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref setKeyRange, \ref setValueRange). The data cells can be accessed in two ways: They can be directly addressed by an integer index with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are provided by the functions \ref coordToCell and \ref cellToCoord. A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map. This class also buffers the minimum and maximum values that are in the data set, to provide QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value that is greater than the current maximum increases this maximum to the new value. However, setting the cell that currently holds the maximum value to a smaller value doesn't decrease the maximum again, because finding the true new maximum would require going through the entire data array, which might be time consuming. The same holds for the data minimum. This functionality is given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience parameter \a recalculateDataBounds which may be set to true to automatically call \ref recalculateDataBounds internally. */ /* start of documentation of inline functions */ /*! \fn bool QCPColorMapData::isEmpty() const Returns whether this instance carries no data. This is equivalent to having a size where at least one of the dimensions is 0 (see \ref setSize). */ /* end of documentation of inline functions */ /*! Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap at the coordinates \a keyRange and \a valueRange. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange */ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : mKeySize(0), mValueSize(0), mKeyRange(keyRange), mValueRange(valueRange), mIsEmpty(true), mData(nullptr), mAlpha(nullptr), mDataModified(true) { setSize(keySize, valueSize); fill(0); } QCPColorMapData::~QCPColorMapData() { delete[] mData; delete[] mAlpha; } /*! Constructs a new QCPColorMapData instance copying the data and range of \a other. */ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : mKeySize(0), mValueSize(0), mIsEmpty(true), mData(nullptr), mAlpha(nullptr), mDataModified(true) { *this = other; } /*! Overwrites this color map data instance with the data stored in \a other. The alpha map state is transferred, too. */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { if (&other != this) { const int keySize = other.keySize(); const int valueSize = other.valueSize(); if (!other.mAlpha && mAlpha) clearAlpha(); setSize(keySize, valueSize); if (other.mAlpha && !mAlpha) createAlpha(false); setRange(other.keyRange(), other.valueRange()); if (!isEmpty()) { memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize*valueSize)); if (mAlpha) memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize*valueSize)); } mDataBounds = other.mDataBounds; mDataModified = true; } return *this; } /* undocumented getter */ double QCPColorMapData::data(double key, double value) { int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 ); int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 ); if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) return mData[valueCell*mKeySize + keyCell]; else return 0; } /* undocumented getter */ double QCPColorMapData::cell(int keyIndex, int valueIndex) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) return mData[valueIndex*mKeySize + keyIndex]; else return 0; } /*! Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex. If this color map data doesn't have an alpha map (because \ref setAlpha was never called after creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity. \see setAlpha */ unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex) { if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) return mAlpha[valueIndex*mKeySize + keyIndex]; else return 255; } /*! Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setRange, setKeySize, setValueSize */ void QCPColorMapData::setSize(int keySize, int valueSize) { if (keySize != mKeySize || valueSize != mValueSize) { mKeySize = keySize; mValueSize = valueSize; delete[] mData; mIsEmpty = mKeySize == 0 || mValueSize == 0; if (!mIsEmpty) { #ifdef __EXCEPTIONS try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif mData = new double[size_t(mKeySize*mValueSize)]; #ifdef __EXCEPTIONS } catch (...) { mData = nullptr; } #endif if (mData) fill(0); else qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; } else mData = nullptr; if (mAlpha) // if we had an alpha map, recreate it with new size createAlpha(); mDataModified = true; } } /*! Resizes the data array to have \a keySize cells in the key dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. \see setKeyRange, setSize, setValueSize */ void QCPColorMapData::setKeySize(int keySize) { setSize(keySize, mValueSize); } /*! Resizes the data array to have \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setValueRange, setSize, setKeySize */ void QCPColorMapData::setValueSize(int valueSize) { setSize(mKeySize, valueSize); } /*! Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. \see setSize */ void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) { setKeyRange(keyRange); setValueRange(valueRange); } /*! Sets the coordinate range the data shall be distributed over in the key dimension. Together with the value range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. \see setRange, setValueRange, setSize */ void QCPColorMapData::setKeyRange(const QCPRange &keyRange) { mKeyRange = keyRange; } /*! Sets the coordinate range the data shall be distributed over in the value dimension. Together with the key range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there will be cells centered on the value coordinates 2, 2.5 and 3. \see setRange, setKeyRange, setSize */ void QCPColorMapData::setValueRange(const QCPRange &valueRange) { mValueRange = valueRange; } /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. \see setCell, setRange */ void QCPColorMapData::setData(double key, double value, double z) { int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 ); int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 ); if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { mData[valueCell*mKeySize + keyCell] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } } /*! Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see \ref setSize). In the standard plot configuration (horizontal key axis and vertical value axis, both not range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with indices (keySize-1, valueSize-1) is in the top right corner of the color map. \see setData, setSize */ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { mData[valueIndex*mKeySize + keyIndex] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } else qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; } /*! Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully opaque cell. If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha. Note that the cell-wise alpha which can be configured here is independent of any alpha configured in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise and gradient alpha, the alpha values will be blended accordingly during rendering of the color map. \see fillAlpha, clearAlpha */ void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { if (mAlpha || createAlpha()) { mAlpha[valueIndex*mKeySize + keyIndex] = alpha; mDataModified = true; } } else qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; } /*! Goes through the data and updates the buffered minimum and maximum data values. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten with a smaller or larger value respectively, since the buffered maximum/minimum values have been updated the last time. Why this is the case is explained in the class description (\ref QCPColorMapData). Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a recalculateDataBounds for convenience. Setting this to true will call this method for you, before doing the rescale. */ void QCPColorMapData::recalculateDataBounds() { if (mKeySize > 0 && mValueSize > 0) { double minHeight = mData[0]; double maxHeight = mData[0]; const int dataCount = mValueSize*mKeySize; for (int i=0; i maxHeight) maxHeight = mData[i]; if (mData[i] < minHeight) minHeight = mData[i]; } mDataBounds.lower = minHeight; mDataBounds.upper = maxHeight; } } /*! Frees the internal data memory. This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { setSize(0, 0); } /*! Frees the internal alpha map. The color map will have full opacity again. */ void QCPColorMapData::clearAlpha() { if (mAlpha) { delete[] mAlpha; mAlpha = nullptr; mDataModified = true; } } /*! Sets all cells to the value \a z. */ void QCPColorMapData::fill(double z) { const int dataCount = mValueSize*mKeySize; for (int i=0; i(data); return; } if (copy) { *mMapData = *data; } else { delete mMapData; mMapData = data; } mMapImageInvalidated = true; } /*! Sets the data range of this color map to \a dataRange. The data range defines which data values are mapped to the color gradient. To make the data range span the full range of the data set, use \ref rescaleDataRange. \see QCPColorScale::setDataRange */ void QCPColorMap::setDataRange(const QCPRange &dataRange) { if (!QCPRange::validRange(dataRange)) return; if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { if (mDataScaleType == QCPAxis::stLogarithmic) mDataRange = dataRange.sanitizedForLogScale(); else mDataRange = dataRange.sanitizedForLinScale(); mMapImageInvalidated = true; emit dataRangeChanged(mDataRange); } } /*! Sets whether the data is correlated with the color gradient linearly or logarithmically. \see QCPColorScale::setDataScaleType */ void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; mMapImageInvalidated = true; emit dataScaleTypeChanged(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); } } /*! Sets the color gradient that is used to represent the data. For more details on how to create an own gradient or use one of the preset gradients, see \ref QCPColorGradient. The colors defined by the gradient will be used to represent data values in the currently set data range, see \ref setDataRange. Data points that are outside this data range will either be colored uniformly with the respective gradient boundary color, or the gradient will repeat, depending on \ref QCPColorGradient::setPeriodic. \see QCPColorScale::setGradient */ void QCPColorMap::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; mMapImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets whether the color map image shall use bicubic interpolation when displaying the color map shrinked or expanded, and not at a 1:1 pixel-to-data scale. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" */ void QCPColorMap::setInterpolate(bool enabled) { mInterpolate = enabled; mMapImageInvalidated = true; // because oversampling factors might need to change } /*! Sets whether the outer most data rows and columns are clipped to the specified key and value range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). if \a enabled is set to false, the data points at the border of the color map are drawn with the same width and height as all other data points. Since the data points are represented by rectangles of one color centered on the data coordinate, this means that the shown color map extends by half a data point over the specified key/value range in each direction. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" */ void QCPColorMap::setTightBoundary(bool enabled) { mTightBoundary = enabled; } /*! Associates the color scale \a colorScale with this color map. This means that both the color scale and the color map synchronize their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps can be associated with one single color scale. This causes the color maps to also synchronize those properties, via the mutual color scale. This function causes the color map to adopt the current color gradient, data range and data scale type of \a colorScale. After this call, you may change these properties at either the color map or the color scale, and the setting will be applied to both. Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again. */ void QCPColorMap::setColorScale(QCPColorScale *colorScale) { if (mColorScale) // unconnect signals from old color scale { disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } mColorScale = colorScale; if (mColorScale) // connect signals to new color scale { setGradient(mColorScale.data()->gradient()); setDataRange(mColorScale.data()->dataRange()); setDataScaleType(mColorScale.data()->dataScaleType()); connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } } /*! Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, only for the third data dimension of the color map. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For performance reasons, however, they are only updated in an expanding fashion. So the buffered maximum can only increase and the buffered minimum can only decrease. In consequence, changes to the data that actually lower the maximum of the data set (by overwriting the cell holding the current maximum with a smaller value), aren't recognized and the buffered maximum overestimates the true maximum of the data set. The same happens for the buffered minimum. To recalculate the true minimum and maximum by explicitly looking at each cell, the method QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a recalculateDataBounds calls this method before setting the data range to the buffered minimum and maximum. \see setDataRange */ void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) { if (recalculateDataBounds) mMapData->recalculateDataBounds(); setDataRange(mMapData->dataBounds()); } /*! Takes the current appearance of the color map and updates the legend icon, which is used to represent this color map in the legend (see \ref QCPLegend). The \a transformMode specifies whether the rescaling is done by a faster, low quality image scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm (Qt::SmoothTransformation). The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured legend icon size, the thumb will be rescaled during drawing of the legend item. \see setDataRange */ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) { if (mMapImage.isNull() && !data()->isEmpty()) updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again { bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); } } /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) { if (details) details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection. return mParentPlot->selectionTolerance()*0.99; } } return -1; } /* inherits documentation from base class */ QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { foundRange = true; QCPRange result = mMapData->keyRange(); result.normalize(); if (inSignDomain == QCP::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCP::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } /* inherits documentation from base class */ QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { if (inKeyRange != QCPRange()) { if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper) { foundRange = false; return {}; } } foundRange = true; QCPRange result = mMapData->valueRange(); result.normalize(); if (inSignDomain == QCP::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCP::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } /*! \internal Updates the internal map image buffer by going through the internal \ref QCPColorMapData and turning the data values into color pixels with \ref QCPColorGradient::colorize. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image has been invalidated for a different reason (e.g. a change of the data range with \ref setDataRange). If the map cell count is low, the image created will be oversampled in order to avoid a QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images without smooth transform enabled. Accordingly, oversampling isn't performed if \ref setInterpolate is true. */ void QCPColorMap::updateMapImage() { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) return; if (mMapData->isEmpty()) return; const QImage::Format format = QImage::Format_ARGB32_Premultiplied; const int keySize = mMapData->keySize(); const int valueSize = mMapData->valueSize(); int keyOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(keySize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on int valueOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(valueSize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation: if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor)) mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format); else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format); if (mMapImage.isNull()) { qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)"; mMapImage = QImage(QSize(10, 10), format); mMapImage.fill(Qt::black); } else { QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { // resize undersampled map image to actual key/value cell sizes: if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize)) mUndersampledMapImage = QImage(QSize(keySize, valueSize), format); else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) mUndersampledMapImage = QImage(QSize(valueSize, keySize), format); localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image } else if (!mUndersampledMapImage.isNull()) mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it const double *rawData = mMapData->mData; const unsigned char *rawAlpha = mMapData->mAlpha; if (keyAxis->orientation() == Qt::Horizontal) { const int lineCount = valueSize; const int rowCount = keySize; for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) if (rawAlpha) mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); else mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); } } else // keyAxis->orientation() == Qt::Vertical { const int lineCount = keySize; const int rowCount = valueSize; for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) if (rawAlpha) mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); else mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); } } if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { if (keyAxis->orientation() == Qt::Horizontal) mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); else mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); } } mMapData->mDataModified = false; mMapImageInvalidated = false; } /* inherits documentation from base class */ void QCPColorMap::draw(QCPPainter *painter) { if (mMapData->isEmpty()) return; if (!mKeyAxis || !mValueAxis) return; applyDefaultAntialiasingHint(painter); if (mMapData->mDataModified || mMapImageInvalidated) updateMapImage(); // use buffer if painting vectorized (PDF): const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized); QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in QPixmap mapBuffer; if (useBuffer) { const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps mapBufferTarget = painter->clipRegion().boundingRect(); mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize()); mapBuffer.fill(Qt::transparent); localPainter = new QCPPainter(&mapBuffer); localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); localPainter->translate(-mapBufferTarget.topLeft()); } QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): double halfCellWidth = 0; // in pixels double halfCellHeight = 0; // in pixels if (keyAxis()->orientation() == Qt::Horizontal) { if (mMapData->keySize() > 1) halfCellWidth = 0.5*imageRect.width()/double(mMapData->keySize()-1); if (mMapData->valueSize() > 1) halfCellHeight = 0.5*imageRect.height()/double(mMapData->valueSize()-1); } else // keyAxis orientation is Qt::Vertical { if (mMapData->keySize() > 1) halfCellHeight = 0.5*imageRect.height()/double(mMapData->keySize()-1); if (mMapData->valueSize() > 1) halfCellWidth = 0.5*imageRect.width()/double(mMapData->valueSize()-1); } imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform); localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); QRegion clipBackup; if (mTightBoundary) { clipBackup = localPainter->clipRegion(); QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); localPainter->setClipRect(tightClipRect, Qt::IntersectClip); } localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); if (mTightBoundary) localPainter->setClipRegion(clipBackup); localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter { delete localPainter; painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); } } /* inherits documentation from base class */ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { applyDefaultAntialiasingHint(painter); // draw map thumbnail: if (!mLegendIcon.isNull()) { QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); iconRect.moveCenter(rect.center()); painter->drawPixmap(iconRect.topLeft(), scaledIcon); } /* // draw frame: painter->setBrush(Qt::NoBrush); painter->setPen(Qt::black); painter->drawRect(rect.adjusted(1, 1, 0, 0)); */ } /* end of 'src/plottables/plottable-colormap.cpp' */ /* including file 'src/plottables/plottable-financial.cpp' */ /* modified 2021-03-29T02:30:44, size 42914 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPFinancialData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPFinancialData \brief Holds the data of one single data point for QCPFinancial. The stored data is: \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey) \li \a open: The opening value at the data point (this is the \a mainValue) \li \a high: The high/maximum value at the data point \li \a low: The low/minimum value at the data point \li \a close: The closing value at the data point The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the documentation there for an explanation regarding the data type's generic methods. \see QCPFinancialDataContainer */ /* start documentation of inline functions */ /*! \fn double QCPFinancialData::sortKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey) Returns a data point with the specified \a sortKey. All other members are set to zero. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey() Since the member \a key is both the data point key coordinate and the data ordering parameter, this method returns true. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPFinancialData::mainKey() const Returns the \a key member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPFinancialData::mainValue() const Returns the \a open member of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn QCPRange QCPFinancialData::valueRange() const Returns a QCPRange spanning from the \a low to the \a high value of this data point. For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /* end documentation of inline functions */ /*! Constructs a data point with key and all values set to zero. */ QCPFinancialData::QCPFinancialData() : key(0), open(0), high(0), low(0), close(0) { } /*! Constructs a data point with the specified \a key and OHLC values. */ QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : key(key), open(open), high(high), low(low), close(close) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPFinancial //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPFinancial \brief A plottable representing a financial stock chart \image html QCPFinancial.png This plottable represents time series data binned to certain intervals, mainly used for stock charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be set via \ref setChartStyle. The data is passed via \ref setData as a set of open/high/low/close values at certain keys (typically times). This means the data must be already binned appropriately. If data is only available as a series of values (e.g. \a price against \a time), you can use the static convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed to \ref setData. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and the width to (or slightly less than) one time bin interval width. \section qcpfinancial-appearance Changing the appearance Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored, lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush). If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are represented with a different pen and brush than negative changes (\a close < \a open). These can be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used, irrespective of whether the chart is single- or two-colored. \section qcpfinancial-usage Usage Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2 Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data series into a 24-hour binned open-high-low-close data series as QCPFinancial uses. */ /* start of documentation of inline functions */ /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods, in certain situations. */ /* end of documentation of inline functions */ /*! Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually but use QCustomPlot::removePlottable() instead. */ QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable1D(keyAxis, valueAxis), mChartStyle(csCandlestick), mWidth(0.5), mWidthType(wtPlotCoords), mTwoColored(true), mBrushPositive(QBrush(QColor(50, 160, 0))), mBrushNegative(QBrush(QColor(180, 0, 15))), mPenPositive(QPen(QColor(40, 150, 0))), mPenNegative(QPen(QColor(170, 5, 5))) { mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPFinancial::~QCPFinancial() { } /*! \overload Replaces the current data container with the provided \a data container. Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely. Modifying the data in the container will then affect all financials that share the container. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1 If you do not wish to share containers, but create a copy from an existing container, rather use the \ref QCPDataContainer::set method on the financial's data container directly: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2 \see addData, timeSeriesToOhlc */ void QCPFinancial::setData(QSharedPointer data) { mDataContainer = data; } /*! \overload Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a close. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. \see addData, timeSeriesToOhlc */ void QCPFinancial::setData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted) { mDataContainer->clear(); addData(keys, open, high, low, close, alreadySorted); } /*! Sets which representation style shall be used to display the OHLC data. */ void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) { mChartStyle = style; } /*! Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. */ void QCPFinancial::setWidth(double width) { mWidth = width; } /*! Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for an explanation of the possible values for \a widthType. The default value is \ref wtPlotCoords. \see setWidth */ void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType) { mWidthType = widthType; } /*! Sets whether this chart shall contrast positive from negative trends per data point by using two separate colors to draw the respective bars/candlesticks. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setTwoColored(bool twoColored) { mTwoColored = twoColored; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a positive trend (i.e. bars/candlesticks with close >= open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setBrushNegative, setPenPositive, setPenNegative */ void QCPFinancial::setBrushPositive(const QBrush &brush) { mBrushPositive = brush; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a negative trend (i.e. bars/candlesticks with close < open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setBrushPositive, setPenNegative, setPenPositive */ void QCPFinancial::setBrushNegative(const QBrush &brush) { mBrushNegative = brush; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setPenPositive(const QPen &pen) { mPenPositive = pen; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenPositive, setBrushNegative, setBrushPositive */ void QCPFinancial::setPenNegative(const QPen &pen) { mPenNegative = pen; } /*! \overload Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. \see timeSeriesToOhlc */ void QCPFinancial::addData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted) { if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size()) qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size(); const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size())))); QVector tempData(n); QVector::iterator it = tempData.begin(); const QVector::iterator itEnd = tempData.end(); int i = 0; while (it != itEnd) { it->key = keys[i]; it->open = open[i]; it->high = high[i]; it->low = low[i]; it->close = close[i]; ++it; ++i; } mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write } /*! \overload Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current data. Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. \see timeSeriesToOhlc */ void QCPFinancial::addData(double key, double open, double high, double low, double close) { mDataContainer->add(QCPFinancialData(key, open, high, low, close)); } /*! \copydoc QCPPlottableInterface1D::selectTestRect */ QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const { QCPDataSelection result; if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return result; if (!mKeyAxis || !mValueAxis) return result; QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd); for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { if (rect.intersects(selectionHitBox(it))) result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); } result.simplify(); return result; } /*! Implements a selectTest specific to this plottable's point geometry. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { // get visible data range: QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); getVisibleDataBounds(visibleBegin, visibleEnd); // perform select test according to configured style: double result = -1; switch (mChartStyle) { case QCPFinancial::csOhlc: result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; case QCPFinancial::csCandlestick: result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; } if (details) { int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); } return result; } return -1; } /* inherits documentation from base class */ QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain); // determine exact range by including width of bars/flags: if (foundRange) { if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0) range.lower -= mWidth*0.5; if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0) range.upper += mWidth*0.5; } return range; } /* inherits documentation from base class */ QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /*! A convenience function that converts time series data (\a value against \a time) to OHLC binned data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const QCPFinancialDataContainer&). The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour each, set \a timeBinSize to 3600. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. It merely defines the mathematical offset/phase of the bins that will be used to process the data. */ QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) { QCPFinancialDataContainer data; int count = qMin(time.size(), value.size()); if (count == 0) return QCPFinancialDataContainer(); QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); for (int i=0; i currentBinData.high) currentBinData.high = value.at(i); if (i == count-1) // last data point is in current bin, finalize bin: { currentBinData.close = value.at(i); currentBinData.key = timeBinOffset+(index)*timeBinSize; data.add(currentBinData); } } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map: { // finalize current bin: currentBinData.close = value.at(i-1); currentBinData.key = timeBinOffset+(index-1)*timeBinSize; data.add(currentBinData); // start next bin: currentBinIndex = index; currentBinData.open = value.at(i); currentBinData.high = value.at(i); currentBinData.low = value.at(i); } } return data; } /* inherits documentation from base class */ void QCPFinancial::draw(QCPPainter *painter) { // get visible data range: QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd); // loop over and draw segments of unselected/selected data: QList selectedSegments, unselectedSegments, allSegments; getDataSegments(selectedSegments, unselectedSegments); allSegments << unselectedSegments << selectedSegments; for (int i=0; i= unselectedSegments.size(); QCPFinancialDataContainer::const_iterator begin = visibleBegin; QCPFinancialDataContainer::const_iterator end = visibleEnd; mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i)); if (begin == end) continue; // draw data segment according to configured style: switch (mChartStyle) { case QCPFinancial::csOhlc: drawOhlcPlot(painter, begin, end, isSelectedSegment); break; case QCPFinancial::csCandlestick: drawCandlestickPlot(painter, begin, end, isSelectedSegment); break; } } // draw other selection decoration that isn't just line/scatter pens and brushes: if (mSelectionDecorator) mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing if (mChartStyle == csOhlc) { if (mTwoColored) { // draw upper left half icon with positive color: painter->setBrush(mBrushPositive); painter->setPen(mPenPositive); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); // draw bottom right half icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); } else { painter->setBrush(mBrush); painter->setPen(mPen); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); } } else if (mChartStyle == csCandlestick) { if (mTwoColored) { // draw upper left half icon with positive color: painter->setBrush(mBrushPositive); painter->setPen(mPenPositive); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); // draw bottom right half icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); } else { painter->setBrush(mBrush); painter->setPen(mPen); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); } } } /*! \internal Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc. */ void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { if (isSelected && mSelectionDecorator) mSelectionDecorator->applyPen(painter); else if (mTwoColored) painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); else painter->setPen(mPen); double keyPixel = keyAxis->coordToPixel(it->key); double openPixel = valueAxis->coordToPixel(it->open); double closePixel = valueAxis->coordToPixel(it->close); // draw backbone: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low))); // draw open: double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel)); // draw close: painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel)); } } else { for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { if (isSelected && mSelectionDecorator) mSelectionDecorator->applyPen(painter); else if (mTwoColored) painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); else painter->setPen(mPen); double keyPixel = keyAxis->coordToPixel(it->key); double openPixel = valueAxis->coordToPixel(it->open); double closePixel = valueAxis->coordToPixel(it->close); // draw backbone: painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel)); // draw open: double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel)); // draw close: painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth)); } } } /*! \internal Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick. */ void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { if (isSelected && mSelectionDecorator) { mSelectionDecorator->applyPen(painter); mSelectionDecorator->applyBrush(painter); } else if (mTwoColored) { painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); } else { painter->setPen(mPen); painter->setBrush(mBrush); } double keyPixel = keyAxis->coordToPixel(it->key); double openPixel = valueAxis->coordToPixel(it->open); double closePixel = valueAxis->coordToPixel(it->close); // draw high: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); // draw low: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); // draw open-close box: double pixelWidth = getPixelWidth(it->key, keyPixel); painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel))); } } else // keyAxis->orientation() == Qt::Vertical { for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { if (isSelected && mSelectionDecorator) { mSelectionDecorator->applyPen(painter); mSelectionDecorator->applyBrush(painter); } else if (mTwoColored) { painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); } else { painter->setPen(mPen); painter->setBrush(mBrush); } double keyPixel = keyAxis->coordToPixel(it->key); double openPixel = valueAxis->coordToPixel(it->open); double closePixel = valueAxis->coordToPixel(it->close); // draw high: painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); // draw low: painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); // draw open-close box: double pixelWidth = getPixelWidth(it->key, keyPixel); painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth))); } } } /*! \internal This function is used to determine the width of the bar at coordinate \a key, according to the specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel when this function is called). It returns the number of pixels the bar extends to higher keys, relative to the \a key coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed horizontal axis, the return value is negative. This is important so the open/close flags on the \ref csOhlc bar are drawn to the correct side. */ double QCPFinancial::getPixelWidth(double key, double keyPixel) const { double result = 0; switch (mWidthType) { case wtAbsolute: { if (mKeyAxis) result = mWidth*0.5*mKeyAxis.data()->pixelOrientation(); break; } case wtAxisRectRatio: { if (mKeyAxis && mKeyAxis.data()->axisRect()) { if (mKeyAxis.data()->orientation() == Qt::Horizontal) result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); else result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); } else qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; break; } case wtPlotCoords: { if (mKeyAxis) result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; else qDebug() << Q_FUNC_INFO << "No key axis defined"; break; } } return result; } /*! \internal This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical representation of the plottable, and \a closestDataPoint will point to the respective data point. */ double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const { closestDataPoint = mDataContainer->constEnd(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = (std::numeric_limits::max)(); if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { double keyPixel = keyAxis->coordToPixel(it->key); // calculate distance to backbone: double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low))); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestDataPoint = it; } } } else // keyAxis->orientation() == Qt::Vertical { for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { double keyPixel = keyAxis->coordToPixel(it->key); // calculate distance to backbone: double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel)); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestDataPoint = it; } } } return qSqrt(minDistSqr); } /*! \internal This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a end. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical representation of the plottable, and \a closestDataPoint will point to the respective data point. */ double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const { closestDataPoint = mDataContainer->constEnd(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = (std::numeric_limits::max)(); if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5); QCPRange boxValueRange(it->close, it->open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box { currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; } else { // calculate distance to high/low lines: double keyPixel = keyAxis->coordToPixel(it->key); double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestDataPoint = it; } } } else // keyAxis->orientation() == Qt::Vertical { for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5); QCPRange boxValueRange(it->close, it->open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box { currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; } else { // calculate distance to high/low lines: double keyPixel = keyAxis->coordToPixel(it->key); double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestDataPoint = it; } } } return qSqrt(minDistSqr); } /*! \internal called by the drawing methods to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. \a begin returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a begin may still be just outside the visible range. \a end returns the iterator just above the highest data point that needs to be taken into account. Same as before, \a end may also lie just outside of the visible range if the plottable contains no data, both \a begin and \a end point to \c constEnd. */ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; begin = mDataContainer->constEnd(); end = mDataContainer->constEnd(); return; } begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points } /*! \internal Returns the hit box in pixel coordinates that will be used for data selection with the selection rect (\ref selectTestRect), of the data point given by \a it. */ QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; } double keyPixel = keyAxis->coordToPixel(it->key); double highPixel = valueAxis->coordToPixel(it->high); double lowPixel = valueAxis->coordToPixel(it->low); double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5); if (keyAxis->orientation() == Qt::Horizontal) return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized(); else return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized(); } /* end of 'src/plottables/plottable-financial.cpp' */ /* including file 'src/plottables/plottable-errorbar.cpp' */ /* modified 2021-03-29T02:30:44, size 37679 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPErrorBarsData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPErrorBarsData \brief Holds the data of one single error bar for QCPErrorBars. The stored data is: \li \a errorMinus: how much the error bar extends towards negative coordinates from the data point position \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point position The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a typedef for QVector<\ref QCPErrorBarsData>. \see QCPErrorBarsDataContainer */ /*! Constructs an error bar with errors set to zero. */ QCPErrorBarsData::QCPErrorBarsData() : errorMinus(0), errorPlus(0) { } /*! Constructs an error bar with equal \a error in both negative and positive direction. */ QCPErrorBarsData::QCPErrorBarsData(double error) : errorMinus(error), errorPlus(error) { } /*! Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus, respectively. */ QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) : errorMinus(errorMinus), errorPlus(errorPlus) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPErrorBars //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPErrorBars \brief A plottable that adds a set of error bars to other plottables. \image html QCPErrorBars.png The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars. Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the error bars. The orientation of the error bars can be controlled with \ref setErrorType. By using \ref setData, you can supply the actual error data, either as symmetric error or plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute key/value position of each error bar will be adopted from the configured data plottable. The error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points of the data plottable. You can directly access and manipulate the error bar data via \ref data. Set either of the plus/minus errors to NaN (qQNaN() or std::numeric_limits::quiet_NaN()) to not show the respective error bar on the data point at that index. \section qcperrorbars-appearance Changing the appearance The appearance of the error bars is defined by the pen (\ref setPen), and the width of the whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data point center to prevent that error bars are drawn too close to or even through scatter points. This gap size can be controlled via \ref setSymbolGap. */ /* start of documentation of inline functions */ /*! \fn QSharedPointer QCPErrorBars::data() const Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You may use it to directly manipulate the error values, which may be more convenient and faster than using the regular \ref setData methods. */ /* end of documentation of inline functions */ /*! Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. It is also important that the \a keyAxis and \a valueAxis are the same for the error bars plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable). The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not delete it manually but use \ref QCustomPlot::removePlottable() instead. */ QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mDataContainer(new QVector), mErrorType(etValueError), mWhiskerWidth(9), mSymbolGap(10) { setPen(QPen(Qt::black, 0)); setBrush(Qt::NoBrush); } QCPErrorBars::~QCPErrorBars() { } /*! \overload Replaces the current data container with the provided \a data container. Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data container safely. Modifying the data in the container will then affect all \ref QCPErrorBars instances that share the container. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers: \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1 If you do not wish to share containers, but create a copy from an existing container, assign the data containers directly: \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2 (This uses different notation compared with other plottables, because the \ref QCPErrorBars uses a \c QVector as its data container, instead of a \ref QCPDataContainer.) \see addData */ void QCPErrorBars::setData(QSharedPointer data) { mDataContainer = data; } /*! \overload Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one by the data point index to the associated data plottable (\ref setDataPlottable). You can directly access and manipulate the error bar data via \ref data. \see addData */ void QCPErrorBars::setData(const QVector &error) { mDataContainer->clear(); addData(error); } /*! \overload Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be associated one-to-one by the data point index to the associated data plottable (\ref setDataPlottable). You can directly access and manipulate the error bar data via \ref data. \see addData */ void QCPErrorBars::setData(const QVector &errorMinus, const QVector &errorPlus) { mDataContainer->clear(); addData(errorMinus, errorPlus); } /*! Sets the data plottable to which the error bars will be applied. The error values specified e.g. via \ref setData will be associated one-to-one by the data point index to the data points of \a plottable. This means that the error bars will adopt the key/value coordinates of the data point with the same index. The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either of these restrictions is violated, a corresponding qDebug output is generated, and the data plottable of this \ref QCPErrorBars instance is set to zero. For proper display, care must also be taken that the key and value axes of the \a plottable match those configured for this \ref QCPErrorBars instance. */ void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable) { if (plottable && qobject_cast(plottable)) { mDataPlottable = nullptr; qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable"; return; } if (plottable && !plottable->interface1D()) { mDataPlottable = nullptr; qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars"; return; } mDataPlottable = plottable; } /*! Sets in which orientation the error bars shall appear on the data points. If your data needs both error dimensions, create two \ref QCPErrorBars with different \a type. */ void QCPErrorBars::setErrorType(ErrorType type) { mErrorType = type; } /*! Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to \a pixels. */ void QCPErrorBars::setWhiskerWidth(double pixels) { mWhiskerWidth = pixels; } /*! Sets the gap diameter around the data points that will be left out when drawing the error bar backbones. This gap prevents that error bars are drawn too close to or even through scatter points. */ void QCPErrorBars::setSymbolGap(double pixels) { mSymbolGap = pixels; } /*! \overload Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one by the data point index to the associated data plottable (\ref setDataPlottable). You can directly access and manipulate the error bar data via \ref data. \see setData */ void QCPErrorBars::addData(const QVector &error) { addData(error, error); } /*! \overload Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be associated one-to-one by the data point index to the associated data plottable (\ref setDataPlottable). You can directly access and manipulate the error bar data via \ref data. \see setData */ void QCPErrorBars::addData(const QVector &errorMinus, const QVector &errorPlus) { if (errorMinus.size() != errorPlus.size()) qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size(); const int n = qMin(errorMinus.size(), errorPlus.size()); mDataContainer->reserve(n); for (int i=0; iappend(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i))); } /*! \overload Adds a single symmetrical error bar as specified in \a error. The errors will be associated one-to-one by the data point index to the associated data plottable (\ref setDataPlottable). You can directly access and manipulate the error bar data via \ref data. \see setData */ void QCPErrorBars::addData(double error) { mDataContainer->append(QCPErrorBarsData(error)); } /*! \overload Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors will be associated one-to-one by the data point index to the associated data plottable (\ref setDataPlottable). You can directly access and manipulate the error bar data via \ref data. \see setData */ void QCPErrorBars::addData(double errorMinus, double errorPlus) { mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus)); } /* inherits documentation from base class */ int QCPErrorBars::dataCount() const { return mDataContainer->size(); } /* inherits documentation from base class */ double QCPErrorBars::dataMainKey(int index) const { if (mDataPlottable) return mDataPlottable->interface1D()->dataMainKey(index); else qDebug() << Q_FUNC_INFO << "no data plottable set"; return 0; } /* inherits documentation from base class */ double QCPErrorBars::dataSortKey(int index) const { if (mDataPlottable) return mDataPlottable->interface1D()->dataSortKey(index); else qDebug() << Q_FUNC_INFO << "no data plottable set"; return 0; } /* inherits documentation from base class */ double QCPErrorBars::dataMainValue(int index) const { if (mDataPlottable) return mDataPlottable->interface1D()->dataMainValue(index); else qDebug() << Q_FUNC_INFO << "no data plottable set"; return 0; } /* inherits documentation from base class */ QCPRange QCPErrorBars::dataValueRange(int index) const { if (mDataPlottable) { const double value = mDataPlottable->interface1D()->dataMainValue(index); if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError) return {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus}; else return {value, value}; } else { qDebug() << Q_FUNC_INFO << "no data plottable set"; return {}; } } /* inherits documentation from base class */ QPointF QCPErrorBars::dataPixelPosition(int index) const { if (mDataPlottable) return mDataPlottable->interface1D()->dataPixelPosition(index); else qDebug() << Q_FUNC_INFO << "no data plottable set"; return {}; } /* inherits documentation from base class */ bool QCPErrorBars::sortKeyIsMainKey() const { if (mDataPlottable) { return mDataPlottable->interface1D()->sortKeyIsMainKey(); } else { qDebug() << Q_FUNC_INFO << "no data plottable set"; return true; } } /*! \copydoc QCPPlottableInterface1D::selectTestRect */ QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const { QCPDataSelection result; if (!mDataPlottable) return result; if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return result; if (!mKeyAxis || !mValueAxis) return result; QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd; getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount())); QVector backbones, whiskers; for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { backbones.clear(); whiskers.clear(); getErrorBarLines(it, backbones, whiskers); foreach (const QLineF &backbone, backbones) { if (rectIntersectsLine(rect, backbone)) { result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); break; } } } result.simplify(); return result; } /* inherits documentation from base class */ int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const { if (mDataPlottable) { if (mDataContainer->isEmpty()) return 0; int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange); if (beginIndex >= mDataContainer->size()) beginIndex = mDataContainer->size()-1; return beginIndex; } else qDebug() << Q_FUNC_INFO << "no data plottable set"; return 0; } /* inherits documentation from base class */ int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const { if (mDataPlottable) { if (mDataContainer->isEmpty()) return 0; int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange); if (endIndex > mDataContainer->size()) endIndex = mDataContainer->size(); return endIndex; } else qDebug() << Q_FUNC_INFO << "no data plottable set"; return 0; } /*! Implements a selectTest specific to this plottable's point geometry. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mDataPlottable) return -1; if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); double result = pointDistance(pos, closestDataPoint); if (details) { int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); } return result; } else return -1; } /* inherits documentation from base class */ void QCPErrorBars::draw(QCPPainter *painter) { if (!mDataPlottable) return; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return; // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range): bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey(); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPErrorBarsDataContainer::const_iterator it; for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) { if (QCP::isInvalidData(it->errorMinus, it->errorPlus)) qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name(); } #endif applyDefaultAntialiasingHint(painter); painter->setBrush(Qt::NoBrush); // loop over and draw segments of unselected/selected data: QList selectedSegments, unselectedSegments, allSegments; getDataSegments(selectedSegments, unselectedSegments); allSegments << unselectedSegments << selectedSegments; QVector backbones, whiskers; for (int i=0; i= unselectedSegments.size(); if (isSelectedSegment && mSelectionDecorator) mSelectionDecorator->applyPen(painter); else painter->setPen(mPen); if (painter->pen().capStyle() == Qt::SquareCap) { QPen capFixPen(painter->pen()); capFixPen.setCapStyle(Qt::FlatCap); painter->setPen(capFixPen); } backbones.clear(); whiskers.clear(); for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it) { if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin()))) getErrorBarLines(it, backbones, whiskers); } painter->drawLines(backbones); painter->drawLines(whiskers); } // draw other selection decoration that isn't just line/scatter pens and brushes: if (mSelectionDecorator) mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical) { painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1)); painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2)); painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1)); } else { painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y())); painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4)); painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4)); } } /* inherits documentation from base class */ QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { if (!mDataPlottable) { foundRange = false; return {}; } QCPRange range; bool haveLower = false; bool haveUpper = false; QCPErrorBarsDataContainer::const_iterator it; for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) { if (mErrorType == etValueError) { // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center const double current = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin())); if (qIsNaN(current)) continue; if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } } else // mErrorType == etKeyError { const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin())); if (qIsNaN(dataKey)) continue; // plus error: double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus); if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) { if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } // minus error: current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus); if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } } } } if (haveUpper && !haveLower) { range.lower = range.upper; haveLower = true; } else if (haveLower && !haveUpper) { range.upper = range.lower; haveUpper = true; } foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { if (!mDataPlottable) { foundRange = false; return {}; } QCPRange range; const bool restrictKeyRange = inKeyRange != QCPRange(); bool haveLower = false; bool haveUpper = false; QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin(); QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd(); if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange) { itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower, false); itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false); } for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it) { if (restrictKeyRange) { const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin())); if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper) continue; } if (mErrorType == etValueError) { const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin())); if (qIsNaN(dataValue)) continue; // plus error: double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus); if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) { if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } // minus error: current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus); if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } } } else // mErrorType == etKeyError { // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center const double current = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin())); if (qIsNaN(current)) continue; if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } } } if (haveUpper && !haveLower) { range.lower = range.upper; haveLower = true; } else if (haveLower && !haveUpper) { range.upper = range.lower; haveUpper = true; } foundRange = haveLower && haveUpper; return range; } /*! \internal Calculates the lines that make up the error bar belonging to the data point \a it. The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so calling this method with different \a it but the same \a backbones and \a whiskers allows to accumulate lines for multiple data points. This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars instance and within the bounds of the associated data plottable. */ void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector &backbones, QVector &whiskers) const { if (!mDataPlottable) return; int index = int(it-mDataContainer->constBegin()); QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index); if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y())) return; QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data(); QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data(); const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y(); const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y(); const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation(); // plus error: double errorStart, errorEnd; if (!qIsNaN(it->errorPlus)) { errorStart = centerErrorAxisPixel+symbolGap; errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus); if (errorAxis->orientation() == Qt::Vertical) { if ((errorStart > errorEnd) != errorAxis->rangeReversed()) backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd)); whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd)); } else { if ((errorStart < errorEnd) != errorAxis->rangeReversed()) backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel)); whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5)); } } // minus error: if (!qIsNaN(it->errorMinus)) { errorStart = centerErrorAxisPixel-symbolGap; errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus); if (errorAxis->orientation() == Qt::Vertical) { if ((errorStart < errorEnd) != errorAxis->rangeReversed()) backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd)); whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd)); } else { if ((errorStart > errorEnd) != errorAxis->rangeReversed()) backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel)); whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5)); } } } /*! \internal This method outputs the currently visible data range via \a begin and \a end. The returned range will also never exceed \a rangeRestriction. Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key coordinates relative to their data point key, this method checks all outer error bars whether they truly don't reach into the visible portion of the axis rect, by calling \ref errorBarVisible. On the other hand error bars with type \ref etValueError that are associated with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref QCPPlottableInterface1D::findEnd). If the plottable's sort key is not equal to the main key, this method returns the full data range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a point-by-point basis in the \ref draw method. */ void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; end = mDataContainer->constEnd(); begin = end; return; } if (!mDataPlottable || rangeRestriction.isEmpty()) { end = mDataContainer->constEnd(); begin = end; return; } if (!mDataPlottable->interface1D()->sortKeyIsMainKey()) { // if the sort key isn't the main key, it's not possible to find a contiguous range of visible // data points, so this method then only applies the range restriction and otherwise returns // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing QCPDataRange dataRange(0, mDataContainer->size()); dataRange = dataRange.bounded(rangeRestriction); begin = mDataContainer->constBegin()+dataRange.begin(); end = mDataContainer->constBegin()+dataRange.end(); return; } // get visible data range via interface from data plottable, and then restrict to available error data points: const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount()); int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower); int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper); int i = beginIndex; while (i > 0 && i < n && i > rangeRestriction.begin()) { if (errorBarVisible(i)) beginIndex = i; --i; } i = endIndex; while (i >= 0 && i < n && i < rangeRestriction.end()) { if (errorBarVisible(i)) endIndex = i+1; ++i; } QCPDataRange dataRange(beginIndex, endIndex); dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size()))); begin = mDataContainer->constBegin()+dataRange.begin(); end = mDataContainer->constBegin()+dataRange.end(); } /*! \internal Calculates the minimum distance in pixels the error bars' representation has from the given \a pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. */ double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const { closestData = mDataContainer->constEnd(); if (!mDataPlottable || mDataContainer->isEmpty()) return -1.0; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1.0; } QCPErrorBarsDataContainer::const_iterator begin, end; getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount())); // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator: double minDistSqr = (std::numeric_limits::max)(); QVector backbones, whiskers; for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it) { getErrorBarLines(it, backbones, whiskers); foreach (const QLineF &backbone, backbones) { const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestData = it; } } } return qSqrt(minDistSqr); } /*! \internal \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the documentation there for details. */ void QCPErrorBars::getDataSegments(QList &selectedSegments, QList &unselectedSegments) const { selectedSegments.clear(); unselectedSegments.clear(); if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty { if (selected()) selectedSegments << QCPDataRange(0, dataCount()); else unselectedSegments << QCPDataRange(0, dataCount()); } else { QCPDataSelection sel(selection()); sel.simplify(); selectedSegments = sel.dataRanges(); unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges(); } } /*! \internal Returns whether the error bar at the specified \a index is visible within the current key axis range. This method assumes for performance reasons without checking that the key axis, the value axis, and the data plottable (\ref setDataPlottable) are not \c nullptr and that \a index is within valid bounds of this \ref QCPErrorBars instance and the bounds of the data plottable. */ bool QCPErrorBars::errorBarVisible(int index) const { QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index); const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y(); if (qIsNaN(centerKeyPixel)) return false; double keyMin, keyMax; if (mErrorType == etKeyError) { const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel); const double errorPlus = mDataContainer->at(index).errorPlus; const double errorMinus = mDataContainer->at(index).errorMinus; keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus); keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus); } else // mErrorType == etValueError { keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation()); keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation()); } return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper)); } /*! \internal Returns whether \a line intersects (or is contained in) \a pixelRect. \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for error bar lines. */ bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const { if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2()) return false; else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2()) return false; else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2()) return false; else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2()) return false; else return true; } /* end of 'src/plottables/plottable-errorbar.cpp' */ /* including file 'src/items/item-straightline.cpp' */ /* modified 2021-03-29T02:30:44, size 7596 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemStraightLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemStraightLine \brief A straight line that spans infinitely in both directions \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a point1 and \a point2, which define the straight line. */ /*! Creates a straight line item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), point1(createPosition(QLatin1String("point1"))), point2(createPosition(QLatin1String("point2"))) { point1->setCoords(0, 0); point2->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemStraightLine::~QCPItemStraightLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemStraightLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemStraightLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition()); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { QCPVector2D start(point1->pixelPosition()); QCPVector2D end(point2->pixelPosition()); // get visible segment of straight line inside clipRect: int clipPad = qCeil(mainPen().widthF()); QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); } } /*! \internal Returns the section of the straight line defined by \a base and direction vector \a vec, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const { double bx, by; double gamma; QLineF result; if (vec.x() == 0 && vec.y() == 0) return result; if (qFuzzyIsNull(vec.x())) // line is vertical { // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical } else if (qFuzzyIsNull(vec.y())) // line is horizontal { // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal } else // line is skewed { QList pointVectors; // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QCPVector2D(bx+gamma, by)); // check bottom of rect: bx = rect.left(); by = rect.bottom(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QCPVector2D(bx+gamma, by)); // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QCPVector2D(bx, by+gamma)); // check right of rect: bx = rect.right(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QCPVector2D(bx, by+gamma)); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QCPVector2D pv1, pv2; for (int i=0; i distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemStraightLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-straightline.cpp' */ /* including file 'src/items/item-line.cpp' */ /* modified 2021-03-29T02:30:44, size 8525 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemLine \brief A line from one point to another \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a start and \a end, which define the end points of the line. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. */ /*! Creates a line item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition(QLatin1String("start"))), end(createPosition(QLatin1String("end"))) { start->setCoords(0, 0); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemLine::~QCPItemLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemLine::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemLine::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition())); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { QCPVector2D startVec(start->pixelPosition()); QCPVector2D endVec(end->pixelPosition()); if (qFuzzyIsNull((startVec-endVec).lengthSquared())) return; // get visible segment of straight line inside clipRect: int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance())); clipPad = qMax(clipPad, qCeil(mainPen().widthF())); QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, startVec, startVec-endVec); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, endVec, endVec-startVec); } } /*! \internal Returns the section of the line defined by \a start and \a end, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const { bool containsStart = rect.contains(qRound(start.x()), qRound(start.y())); bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y())); if (containsStart && containsEnd) return {start.toPointF(), end.toPointF()}; QCPVector2D base = start; QCPVector2D vec = end-start; double bx, by; double gamma, mu; QLineF result; QList pointVectors; if (!qFuzzyIsNull(vec.y())) // line is not horizontal { // check top of rect: bx = rect.left(); by = rect.top(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QCPVector2D(bx+gamma, by)); } // check bottom of rect: bx = rect.left(); by = rect.bottom(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QCPVector2D(bx+gamma, by)); } } if (!qFuzzyIsNull(vec.x())) // line is not vertical { // check left of rect: bx = rect.left(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QCPVector2D(bx, by+gamma)); } // check right of rect: bx = rect.right(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QCPVector2D(bx, by+gamma)); } } if (containsStart) pointVectors.append(start); if (containsEnd) pointVectors.append(end); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QCPVector2D pv1, pv2; for (int i=0; i distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-line.cpp' */ /* including file 'src/items/item-curve.cpp' */ /* modified 2021-03-29T02:30:44, size 7273 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemCurve \brief A curved line from one point to another \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions." It has four positions, \a start and \a end, which define the end points of the line, and two control points which define the direction the line exits from the start and the direction from which it approaches the end: \a startDir and \a endDir. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. Often it is desirable for the control points to stay at fixed relative positions to the start/end point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. */ /*! Creates a curve item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition(QLatin1String("start"))), startDir(createPosition(QLatin1String("startDir"))), endDir(createPosition(QLatin1String("endDir"))), end(createPosition(QLatin1String("end"))) { start->setCoords(0, 0); startDir->setCoords(0.5, 0); endDir->setCoords(0, 0.5); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemCurve::~QCPItemCurve() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemCurve::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemCurve::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemCurve::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemCurve::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF startVec(start->pixelPosition()); QPointF startDirVec(startDir->pixelPosition()); QPointF endDirVec(endDir->pixelPosition()); QPointF endVec(end->pixelPosition()); QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); QList polygons = cubicPath.toSubpathPolygons(); if (polygons.isEmpty()) return -1; const QPolygonF polygon = polygons.first(); QCPVector2D p(pos); double minDistSqr = (std::numeric_limits::max)(); for (int i=1; ipixelPosition()); QCPVector2D startDirVec(startDir->pixelPosition()); QCPVector2D endDirVec(endDir->pixelPosition()); QCPVector2D endVec(end->pixelPosition()); if ((endVec-startVec).length() > 1e10) // too large curves cause crash return; QPainterPath cubicPath(startVec.toPointF()); cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF()); // paint visible segment, if existent: const int clipEnlarge = qCeil(mainPen().widthF()); QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); QRect cubicRect = cubicPath.controlPointRect().toRect(); if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position cubicRect.adjust(0, 0, 1, 1); if (clip.intersects(cubicRect)) { painter->setPen(mainPen()); painter->drawPath(cubicPath); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI); } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemCurve::mainPen() const { return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-curve.cpp' */ /* including file 'src/items/item-rect.cpp' */ /* modified 2021-03-29T02:30:44, size 6472 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemRect \brief A rectangle \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle. */ /*! Creates a rectangle item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemRect::~QCPItemRect() { } /*! Sets the pen that will be used to draw the line of the rectangle \see setSelectedPen, setBrush */ void QCPItemRect::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the rectangle when selected \see setPen, setSelected */ void QCPItemRect::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemRect::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemRect::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized(); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectDistance(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPosition(); QPointF p2 = bottomRight->pixelPosition(); if (p1.toPoint() == p2.toPoint()) return; QRectF rect = QRectF(p1, p2).normalized(); double clipPad = mainPen().widthF(); QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(rect); } } /* inherits documentation from base class */ QPointF QCPItemRect::anchorPixelPosition(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return {}; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemRect::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemRect::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-rect.cpp' */ /* including file 'src/items/item-text.cpp' */ /* modified 2021-03-29T02:30:44, size 13335 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemText //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemText \brief A text label \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." Its position is defined by the member \a position and the setting of \ref setPositionAlignment. The latter controls which part of the text rect shall be aligned with \a position. The text alignment itself (i.e. left, center, right) can be controlled with \ref setTextAlignment. The text may be rotated around the \a position point with \ref setRotation. */ /*! Creates a text item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemText::QCPItemText(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)), mText(QLatin1String("text")), mPositionAlignment(Qt::AlignCenter), mTextAlignment(Qt::AlignTop|Qt::AlignHCenter), mRotation(0) { position->setCoords(0, 0); setPen(Qt::NoPen); setSelectedPen(Qt::NoPen); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setColor(Qt::black); setSelectedColor(Qt::blue); } QCPItemText::~QCPItemText() { } /*! Sets the color of the text. */ void QCPItemText::setColor(const QColor &color) { mColor = color; } /*! Sets the color of the text that will be used when the item is selected. */ void QCPItemText::setSelectedColor(const QColor &color) { mSelectedColor = color; } /*! Sets the pen that will be used do draw a rectangular border around the text. To disable the border, set \a pen to Qt::NoPen. \see setSelectedPen, setBrush, setPadding */ void QCPItemText::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used do draw a rectangular border around the text, when the item is selected. To disable the border, set \a pen to Qt::NoPen. \see setPen */ void QCPItemText::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used do fill the background of the text. To disable the background, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen, setPadding */ void QCPItemText::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the background, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemText::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the font of the text. \see setSelectedFont, setColor */ void QCPItemText::setFont(const QFont &font) { mFont = font; } /*! Sets the font of the text that will be used when the item is selected. \see setFont */ void QCPItemText::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the text that will be displayed. Multi-line texts are supported by inserting a line break character, e.g. '\n'. \see setFont, setColor, setTextAlignment */ void QCPItemText::setText(const QString &text) { mText = text; } /*! Sets which point of the text rect shall be aligned with \a position. Examples: \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such that the top of the text rect will be horizontally centered on \a position. \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the bottom left corner of the text rect. If you want to control the alignment of (multi-lined) text within the text rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) { mPositionAlignment = alignment; } /*! Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight). */ void QCPItemText::setTextAlignment(Qt::Alignment alignment) { mTextAlignment = alignment; } /*! Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated around \a position. */ void QCPItemText::setRotation(double degrees) { mRotation = degrees; } /*! Sets the distance between the border of the text rectangle and the text. The appearance (and visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush. */ void QCPItemText::setPadding(const QMargins &padding) { mPadding = padding; } /* inherits documentation from base class */ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; // The rect may be rotated, so we transform the actual clicked pos to the rotated // coordinate system, so we can use the normal rectDistance function for non-rotated rects: QPointF positionPixels(position->pixelPosition()); QTransform inputTransform; inputTransform.translate(positionPixels.x(), positionPixels.y()); inputTransform.rotate(-mRotation); inputTransform.translate(-positionPixels.x(), -positionPixels.y()); QPointF rotatedPos = inputTransform.map(pos); QFontMetrics fontMetrics(mFont); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); textBoxRect.moveTopLeft(textPos.toPoint()); return rectDistance(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { QPointF pos(position->pixelPosition()); QTransform transform = painter->transform(); transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); painter->setFont(mainFont()); QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); textBoxRect.moveTopLeft(textPos.toPoint()); int clipPad = qCeil(mainPen().widthF()); QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) { painter->setTransform(transform); if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(textBoxRect); } painter->setBrush(Qt::NoBrush); painter->setPen(QPen(mainColor())); painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); } } /* inherits documentation from base class */ QPointF QCPItemText::anchorPixelPosition(int anchorId) const { // get actual rect points (pretty much copied from draw function): QPointF pos(position->pixelPosition()); QTransform transform; transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); QFontMetrics fontMetrics(mainFont()); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textBoxRect.moveTopLeft(textPos.toPoint()); QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); switch (anchorId) { case aiTopLeft: return rectPoly.at(0); case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; case aiTopRight: return rectPoly.at(1); case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; case aiBottomRight: return rectPoly.at(2); case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; case aiBottomLeft: return rectPoly.at(3); case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return {}; } /*! \internal Returns the point that must be given to the QPainter::drawText function (which expects the top left point of the text rect), according to the position \a pos, the text bounding box \a rect and the requested \a positionAlignment. For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally drawn at that point, the lower left corner of the resulting text rect is at \a pos. */ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const { if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) return pos; QPointF result = pos; // start at top left if (positionAlignment.testFlag(Qt::AlignHCenter)) result.rx() -= rect.width()/2.0; else if (positionAlignment.testFlag(Qt::AlignRight)) result.rx() -= rect.width(); if (positionAlignment.testFlag(Qt::AlignVCenter)) result.ry() -= rect.height()/2.0; else if (positionAlignment.testFlag(Qt::AlignBottom)) result.ry() -= rect.height(); return result; } /*! \internal Returns the font that should be used for drawing text. Returns mFont when the item is not selected and mSelectedFont when it is. */ QFont QCPItemText::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the color that should be used for drawing text. Returns mColor when the item is not selected and mSelectedColor when it is. */ QColor QCPItemText::mainColor() const { return mSelected ? mSelectedColor : mColor; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemText::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemText::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-text.cpp' */ /* including file 'src/items/item-ellipse.cpp' */ /* modified 2021-03-29T02:30:44, size 7881 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemEllipse //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemEllipse \brief An ellipse \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in. */ /*! Creates an ellipse item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), top(createAnchor(QLatin1String("top"), aiTop)), topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), right(createAnchor(QLatin1String("right"), aiRight)), bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), left(createAnchor(QLatin1String("left"), aiLeft)), center(createAnchor(QLatin1String("center"), aiCenter)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemEllipse::~QCPItemEllipse() { } /*! Sets the pen that will be used to draw the line of the ellipse \see setSelectedPen, setBrush */ void QCPItemEllipse::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the ellipse when selected \see setPen, setSelected */ void QCPItemEllipse::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemEllipse::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemEllipse::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF p1 = topLeft->pixelPosition(); QPointF p2 = bottomRight->pixelPosition(); QPointF center((p1+p2)/2.0); double a = qAbs(p1.x()-p2.x())/2.0; double b = qAbs(p1.y()-p2.y())/2.0; double x = pos.x()-center.x(); double y = pos.y()-center.y(); // distance to border: double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); double result = qAbs(c-1)*qSqrt(x*x+y*y); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (x*x/(a*a) + y*y/(b*b) <= 1) result = mParentPlot->selectionTolerance()*0.99; } return result; } /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPosition(); QPointF p2 = bottomRight->pixelPosition(); if (p1.toPoint() == p2.toPoint()) return; QRectF ellipseRect = QRectF(p1, p2).normalized(); const int clipEnlarge = qCeil(mainPen().widthF()); QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); #ifdef __EXCEPTIONS try // drawEllipse sometimes throws exceptions if ellipse is too big { #endif painter->drawEllipse(ellipseRect); #ifdef __EXCEPTIONS } catch (...) { qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; setVisible(false); } #endif } } /* inherits documentation from base class */ QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); switch (anchorId) { case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return {}; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemEllipse::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemEllipse::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-ellipse.cpp' */ /* including file 'src/items/item-pixmap.cpp' */ /* modified 2021-03-29T02:30:44, size 10622 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPixmap //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPixmap \brief An arbitrary pixmap \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to fit the rectangle or be drawn aligned to the topLeft position. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown on the right side of the example image), the pixmap will be flipped in the respective orientations. */ /*! Creates a rectangle item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)), mScaled(false), mScaledPixmapInvalidated(true), mAspectRatioMode(Qt::KeepAspectRatio), mTransformationMode(Qt::SmoothTransformation) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(Qt::NoPen); setSelectedPen(QPen(Qt::blue)); } QCPItemPixmap::~QCPItemPixmap() { } /*! Sets the pixmap that will be displayed. */ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { mPixmap = pixmap; mScaledPixmapInvalidated = true; if (mPixmap.isNull()) qDebug() << Q_FUNC_INFO << "pixmap is null"; } /*! Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a bottomRight positions. */ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) { mScaled = scaled; mAspectRatioMode = aspectRatioMode; mTransformationMode = transformationMode; mScaledPixmapInvalidated = true; } /*! Sets the pen that will be used to draw a border around the pixmap. \see setSelectedPen, setBrush */ void QCPItemPixmap::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw a border around the pixmap when selected \see setPen, setSelected */ void QCPItemPixmap::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return rectDistance(getFinalRect(), pos, true); } /* inherits documentation from base class */ void QCPItemPixmap::draw(QCPPainter *painter) { bool flipHorz = false; bool flipVert = false; QRect rect = getFinalRect(&flipHorz, &flipVert); int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF()); QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) { updateScaledPixmap(rect, flipHorz, flipVert); painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); QPen pen = mainPen(); if (pen.style() != Qt::NoPen) { painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->drawRect(rect); } } } /* inherits documentation from base class */ QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const { bool flipHorz = false; bool flipVert = false; QRect rect = getFinalRect(&flipHorz, &flipVert); // we actually want denormal rects (negative width/height) here, so restore // the flipped state: if (flipHorz) rect.adjust(rect.width(), 0, -rect.width(), 0); if (flipVert) rect.adjust(0, rect.height(), 0, -rect.height()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return {}; } /*! \internal Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a bottomRight.) This function only creates the scaled pixmap when the buffered pixmap has a different size than the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does not cause expensive rescaling every time. If scaling is disabled, sets mScaledPixmap to a null QPixmap. */ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) { if (mPixmap.isNull()) return; if (mScaled) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED double devicePixelRatio = mPixmap.devicePixelRatio(); #else double devicePixelRatio = 1.0; #endif if (finalRect.isNull()) finalRect = getFinalRect(&flipHorz, &flipVert); if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio) { mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode); if (flipHorz || flipVert) mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED mScaledPixmap.setDevicePixelRatio(devicePixelRatio); #endif } } else if (!mScaledPixmap.isNull()) mScaledPixmap = QPixmap(); mScaledPixmapInvalidated = false; } /*! \internal Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions and scaling settings. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn flipped horizontally or vertically in the returned rect. (The returned rect itself is always normalized, i.e. the top left corner of the rect is actually further to the top/left than the bottom right corner). This is the case when the item position \a topLeft is further to the bottom/right than \a bottomRight. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner aligned with the item position \a topLeft. The position \a bottomRight is ignored. */ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const { QRect result; bool flipHorz = false; bool flipVert = false; QPoint p1 = topLeft->pixelPosition().toPoint(); QPoint p2 = bottomRight->pixelPosition().toPoint(); if (p1 == p2) return {p1, QSize(0, 0)}; if (mScaled) { QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); QPoint topLeft = p1; if (newSize.width() < 0) { flipHorz = true; newSize.rwidth() *= -1; topLeft.setX(p2.x()); } if (newSize.height() < 0) { flipVert = true; newSize.rheight() *= -1; topLeft.setY(p2.y()); } QSize scaledSize = mPixmap.size(); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED scaledSize /= mPixmap.devicePixelRatio(); scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode); #else scaledSize.scale(newSize, mAspectRatioMode); #endif result = QRect(topLeft, scaledSize); } else { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio()); #else result = QRect(p1, mPixmap.size()); #endif } if (flippedHorz) *flippedHorz = flipHorz; if (flippedVert) *flippedVert = flipVert; return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemPixmap::mainPen() const { return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-pixmap.cpp' */ /* including file 'src/items/item-tracer.cpp' */ /* modified 2021-03-29T02:30:44, size 14645 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemTracer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemTracer \brief Item that sticks to QCPGraph data points \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions." The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt the coordinate axes of the graph and update its \a position to be on the graph's data. This means the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a position will have no effect because they will be overriden in the next redraw (this is when the coordinate update happens). If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will stay at the corresponding end of the graph. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data points or whether it interpolates data points linearly, if given a key that lies between two data points of the graph. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer have no own visual appearance (set the style to \ref tsNone), and just connect other item positions to the tracer \a position (used as an anchor) via \ref QCPItemPosition::setParentAnchor. \note The tracer position is only automatically updated upon redraws. So when the data of the graph changes and immediately afterwards (without a redraw) the position coordinates of the tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref updatePosition must be called manually, prior to reading the tracer coordinates. */ /*! Creates a tracer item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), mSize(6), mStyle(tsCrosshair), mGraph(nullptr), mGraphKey(0), mInterpolating(false) { position->setCoords(0, 0); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); } QCPItemTracer::~QCPItemTracer() { } /*! Sets the pen that will be used to draw the line of the tracer \see setSelectedPen, setBrush */ void QCPItemTracer::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the tracer when selected \see setPen, setSelected */ void QCPItemTracer::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to draw any fills of the tracer \see setSelectedBrush, setPen */ void QCPItemTracer::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to draw any fills of the tracer, when selected. \see setBrush, setSelected */ void QCPItemTracer::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare does, \ref tsCrosshair does not). */ void QCPItemTracer::setSize(double size) { mSize = size; } /*! Sets the style/visual appearance of the tracer. If you only want to use the tracer \a position as an anchor for other items, set \a style to \ref tsNone. */ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) { mStyle = style; } /*! Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be placed freely like any other item position. This is the state the tracer will assume when its graph gets deleted while still attached to it. \see setGraphKey */ void QCPItemTracer::setGraph(QCPGraph *graph) { if (graph) { if (graph->parentPlot() == mParentPlot) { position->setType(QCPItemPosition::ptPlotCoords); position->setAxes(graph->keyAxis(), graph->valueAxis()); mGraph = graph; updatePosition(); } else qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; } else { mGraph = nullptr; } } /*! Sets the key of the graph's data point the tracer will be positioned at. This is the only free coordinate of a tracer when attached to a graph. Depending on \ref setInterpolating, the tracer will be either positioned on the data point closest to \a key, or will stay exactly at \a key and interpolate the value linearly. \see setGraph, setInterpolating */ void QCPItemTracer::setGraphKey(double key) { mGraphKey = key; } /*! Sets whether the value of the graph's data points shall be interpolated, when positioning the tracer. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on the data point of the graph which is closest to the key, but which is not necessarily exactly there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and the appropriate value will be interpolated from the graph's data points linearly. \see setGraph, setGraphKey */ void QCPItemTracer::setInterpolating(bool enabled) { mInterpolating = enabled; } /* inherits documentation from base class */ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF center(position->pixelPosition()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return -1; case tsPlus: { if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)), QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w)))); break; } case tsCrosshair: { return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())), QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom())))); } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { // distance to border: double centerDist = QCPVector2D(center-pos).length(); double circleLine = w; double result = qAbs(centerDist-circleLine); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (centerDist <= circleLine) result = mParentPlot->selectionTolerance()*0.99; } return result; } break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectDistance(rect, pos, filledRect); } break; } } return -1; } /* inherits documentation from base class */ void QCPItemTracer::draw(QCPPainter *painter) { updatePosition(); if (mStyle == tsNone) return; painter->setPen(mainPen()); painter->setBrush(mainBrush()); QPointF center(position->pixelPosition()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return; case tsPlus: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); } break; } case tsCrosshair: { if (center.y() > clip.top() && center.y() < clip.bottom()) painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); if (center.x() > clip.left() && center.x() < clip.right()) painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); break; } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawEllipse(center, w, w); break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); break; } } } /*! If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a position to reside on the graph data, depending on the configured key (\ref setGraphKey). It is called automatically on every redraw and normally doesn't need to be called manually. One exception is when you want to read the tracer coordinates via \a position and are not sure that the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. In that situation, call this function before accessing \a position, to make sure you don't get out-of-date coordinates. If there is no graph set on this tracer, this function does nothing. */ void QCPItemTracer::updatePosition() { if (mGraph) { if (mParentPlot->hasPlottable(mGraph)) { if (mGraph->data()->size() > 1) { QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin(); QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1; if (mGraphKey <= first->key) position->setCoords(first->key, first->value); else if (mGraphKey >= last->key) position->setCoords(last->key, last->value); else { QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey); if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators { QCPGraphDataContainer::const_iterator prevIt = it; ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before if (mInterpolating) { // interpolate between iterators around mGraphKey: double slope = 0; if (!qFuzzyCompare(double(it->key), double(prevIt->key))) slope = (it->value-prevIt->value)/(it->key-prevIt->key); position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value); } else { // find iterator with key closest to mGraphKey: if (mGraphKey < (prevIt->key+it->key)*0.5) position->setCoords(prevIt->key, prevIt->value); else position->setCoords(it->key, it->value); } } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty) position->setCoords(it->key, it->value); } } else if (mGraph->data()->size() == 1) { QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin(); position->setCoords(it->key, it->value); } else qDebug() << Q_FUNC_INFO << "graph has no data"; } else qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemTracer::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemTracer::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-tracer.cpp' */ /* including file 'src/items/item-bracket.cpp' */ /* modified 2021-03-29T02:30:44, size 10705 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemBracket //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemBracket \brief A bracket for referencing/highlighting certain parts in the plot. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a left and \a right, which define the span of the bracket. If \a left is actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the example image. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket stretches away from the embraced span, can be controlled with \ref setLength. \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine or QCPItemCurve) or a text label (QCPItemText), to the bracket. */ /*! Creates a bracket item and sets default values. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), left(createPosition(QLatin1String("left"))), right(createPosition(QLatin1String("right"))), center(createAnchor(QLatin1String("center"), aiCenter)), mLength(8), mStyle(bsCalligraphic) { left->setCoords(0, 0); right->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); } QCPItemBracket::~QCPItemBracket() { } /*! Sets the pen that will be used to draw the bracket. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use \ref setLength, which has a similar effect. \see setSelectedPen */ void QCPItemBracket::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the bracket when selected \see setPen, setSelected */ void QCPItemBracket::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the \a length in pixels how far the bracket extends in the direction towards the embraced span of the bracket (i.e. perpendicular to the left-right-direction) \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
*/ void QCPItemBracket::setLength(double length) { mLength = length; } /*! Sets the style of the bracket, i.e. the shape/visual appearance. \see setPen */ void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) { mStyle = style; } /* inherits documentation from base class */ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QCPVector2D p(pos); QCPVector2D leftVec(left->pixelPosition()); QCPVector2D rightVec(right->pixelPosition()); if (leftVec.toPoint() == rightVec.toPoint()) return -1; QCPVector2D widthVec = (rightVec-leftVec)*0.5; QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; switch (mStyle) { case QCPItemBracket::bsSquare: case QCPItemBracket::bsRound: { double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec); double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec); double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec); return qSqrt(qMin(qMin(a, b), c)); } case QCPItemBracket::bsCurly: case QCPItemBracket::bsCalligraphic: { double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3); double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15); double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3); double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15); return qSqrt(qMin(qMin(a, b), qMin(c, d))); } } return -1; } /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { QCPVector2D leftVec(left->pixelPosition()); QCPVector2D rightVec(right->pixelPosition()); if (leftVec.toPoint() == rightVec.toPoint()) return; QCPVector2D widthVec = (rightVec-leftVec)*0.5; QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; QPolygon boundingPoly; boundingPoly << leftVec.toPoint() << rightVec.toPoint() << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); const int clipEnlarge = qCeil(mainPen().widthF()); QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); if (clip.intersects(boundingPoly.boundingRect())) { painter->setPen(mainPen()); switch (mStyle) { case bsSquare: { painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); break; } case bsRound: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCurly: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCalligraphic: { painter->setPen(Qt::NoPen); painter->setBrush(QBrush(mainPen().color())); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF()); path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } } } } /* inherits documentation from base class */ QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const { QCPVector2D leftVec(left->pixelPosition()); QCPVector2D rightVec(right->pixelPosition()); if (leftVec.toPoint() == rightVec.toPoint()) return leftVec.toPointF(); QCPVector2D widthVec = (rightVec-leftVec)*0.5; QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; switch (anchorId) { case aiCenter: return centerVec.toPointF(); } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return {}; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemBracket::mainPen() const { return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-bracket.cpp' */ /* including file 'src/polar/radialaxis.cpp' */ /* modified 2021-03-29T02:30:44, size 49415 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPolarAxisRadial //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPolarAxisRadial \brief The radial axis inside a radial plot \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and functionality to be incomplete, as well as changing public interfaces in the future. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the documentation of QCPAxisTicker. */ /* start of documentation of inline functions */ /*! \fn QSharedPointer QCPPolarAxisRadial::ticker() const Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is responsible for generating the tick positions and tick labels of this axis. You can access the \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count (\ref QCPAxisTicker::setTickCount). You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see the documentation there. A new axis ticker can be set with \ref setTicker. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis ticker simply by passing the same shared pointer to multiple axes. \see setTicker */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange) This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following slot would limit the x axis to ranges between 0 and 10: \code customPlot->xAxis->setRange(newRange.bounded(0, 10)) \endcode */ /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType); This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection) This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts); This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ /* end of documentation of signals */ /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) : QCPLayerable(parent->parentPlot(), QString(), parent), mRangeDrag(true), mRangeZoom(true), mRangeZoomFactor(0.85), // axis base: mAngularAxis(parent), mAngle(45), mAngleReference(arAngularAxis), mSelectableParts(spAxis | spTickLabels | spAxisLabel), mSelectedParts(spNone), mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedBasePen(QPen(Qt::blue, 2)), // axis label: mLabelPadding(0), mLabel(), mLabelFont(mParentPlot->font()), mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), mLabelColor(Qt::black), mSelectedLabelColor(Qt::blue), // tick labels: // mTickLabelPadding(0), in label painter mTickLabels(true), // mTickLabelRotation(0), in label painter mTickLabelFont(mParentPlot->font()), mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), mTickLabelColor(Qt::black), mSelectedTickLabelColor(Qt::blue), mNumberPrecision(6), mNumberFormatChar('g'), mNumberBeautifulPowers(true), mNumberMultiplyCross(false), // ticks and subticks: mTicks(true), mSubTicks(true), mTickLengthIn(5), mTickLengthOut(0), mSubTickLengthIn(2), mSubTickLengthOut(0), mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedTickPen(QPen(Qt::blue, 2)), mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedSubTickPen(QPen(Qt::blue, 2)), // scale and range: mRange(0, 5), mRangeReversed(false), mScaleType(stLinear), // internal members: mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect mTicker(new QCPAxisTicker), mLabelPainter(mParentPlot) { setParent(parent); setAntialiased(true); setTickLabelPadding(5); setTickLabelRotation(0); setTickLabelMode(lmUpright); mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent); mLabelPainter.setAbbreviateDecimalPowers(false); } QCPPolarAxisRadial::~QCPPolarAxisRadial() { } QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const { switch (mLabelPainter.anchorMode()) { case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright; case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated; default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break; } return lmUpright; } /* No documentation as it is a property getter */ QString QCPPolarAxisRadial::numberFormat() const { QString result; result.append(mNumberFormatChar); if (mNumberBeautifulPowers) { result.append(QLatin1Char('b')); if (mNumberMultiplyCross) result.append(QLatin1Char('c')); } return result; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::tickLengthIn() const { return mTickLengthIn; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::tickLengthOut() const { return mTickLengthOut; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::subTickLengthIn() const { return mSubTickLengthIn; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::subTickLengthOut() const { return mSubTickLengthOut; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::labelPadding() const { return mLabelPadding; } void QCPPolarAxisRadial::setRangeDrag(bool enabled) { mRangeDrag = enabled; } void QCPPolarAxisRadial::setRangeZoom(bool enabled) { mRangeZoom = enabled; } void QCPPolarAxisRadial::setRangeZoomFactor(double factor) { mRangeZoomFactor = factor; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the axis ticker to an instance of \ref QCPAxisTickerLog : \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. \ref setNumberPrecision */ void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type) { if (mScaleType != type) { mScaleType = type; if (mScaleType == stLogarithmic) setRange(mRange.sanitizedForLogScale()); //mCachedMarginValid = false; emit scaleTypeChanged(mScaleType); } } /*! Sets the range of the axis. This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. To invert the direction of an axis, use \ref setRangeReversed. */ void QCPPolarAxisRadial::setRange(const QCPRange &range) { if (range.lower == mRange.lower && range.upper == mRange.upper) return; if (!QCPRange::validRange(range)) return; QCPRange oldRange = mRange; if (mScaleType == stLogarithmic) { mRange = range.sanitizedForLogScale(); } else { mRange = range.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part, independent of the \ref setSelectableParts setting. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected) { if (mSelectedParts != selected) { mSelectedParts = selected; emit selectionChanged(mSelectedParts); } } /*! \overload Sets the lower and upper bound of the axis range. To invert the direction of an axis, use \ref setRangeReversed. There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPPolarAxisRadial::setRange(double lower, double upper) { if (lower == mRange.lower && upper == mRange.upper) return; if (!QCPRange::validRange(lower, upper)) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! \overload Sets the range of the axis. The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, or center of the range to be aligned with \a position. Any other values of \a alignment will default to Qt::AlignCenter. */ void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment) { if (alignment == Qt::AlignLeft) setRange(position, position+size); else if (alignment == Qt::AlignRight) setRange(position-size, position); else // alignment == Qt::AlignCenter setRange(position-size/2.0, position+size/2.0); } /*! Sets the lower bound of the axis range. The upper bound is not changed. \see setRange */ void QCPPolarAxisRadial::setRangeLower(double lower) { if (mRange.lower == lower) return; QCPRange oldRange = mRange; mRange.lower = lower; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets the upper bound of the axis range. The lower bound is not changed. \see setRange */ void QCPPolarAxisRadial::setRangeUpper(double upper) { if (mRange.upper == upper) return; QCPRange oldRange = mRange; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the direction of increasing values is inverted. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part of the \ref setRange interface will still reference the mathematically smaller number than the \a upper part. */ void QCPPolarAxisRadial::setRangeReversed(bool reversed) { mRangeReversed = reversed; } void QCPPolarAxisRadial::setAngle(double degrees) { mAngle = degrees; } void QCPPolarAxisRadial::setAngleReference(AngleReference reference) { mAngleReference = reference; } /*! The axis ticker is responsible for generating the tick positions and tick labels. See the documentation of QCPAxisTicker for details on how to work with axis tickers. You can change the tick positioning/labeling behaviour of this axis by setting a different QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis ticker, access it via \ref ticker. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis ticker simply by passing the same shared pointer to multiple axes. \see ticker */ void QCPPolarAxisRadial::setTicker(QSharedPointer ticker) { if (ticker) mTicker = ticker; else qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker"; // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector } /*! Sets whether tick marks are displayed. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve that, see \ref setTickLabels. \see setSubTicks */ void QCPPolarAxisRadial::setTicks(bool show) { if (mTicks != show) { mTicks = show; //mCachedMarginValid = false; } } /*! Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. */ void QCPPolarAxisRadial::setTickLabels(bool show) { if (mTickLabels != show) { mTickLabels = show; //mCachedMarginValid = false; if (!mTickLabels) mTickVectorLabels.clear(); } } /*! Sets the distance between the axis base line (including any outward ticks) and the tick labels. \see setLabelPadding, setPadding */ void QCPPolarAxisRadial::setTickLabelPadding(int padding) { mLabelPainter.setPadding(padding); } /*! Sets the font of the tick labels. \see setTickLabels, setTickLabelColor */ void QCPPolarAxisRadial::setTickLabelFont(const QFont &font) { if (font != mTickLabelFont) { mTickLabelFont = font; //mCachedMarginValid = false; } } /*! Sets the color of the tick labels. \see setTickLabels, setTickLabelFont */ void QCPPolarAxisRadial::setTickLabelColor(const QColor &color) { mTickLabelColor = color; } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPPolarAxisRadial::setTickLabelRotation(double degrees) { mLabelPainter.setRotation(degrees); } void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode) { switch (mode) { case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break; case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break; } } /*! Sets the number format for the numbers in tick labels. This \a formatCode is an extended version of the format code used e.g. by QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" section in the detailed description of the QString class. \a formatCode is a string of one, two or three characters. The first character is identical to the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, whichever is shorter. The second and third characters are optional and specific to QCustomPlot:\n If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. Examples for \a formatCode: \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, normal scientific format is used \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with beautifully typeset decimal powers and a dot as multiplication sign \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as multiplication sign \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal powers. Format code will be reduced to 'f'. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format code will not be changed. */ void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode) { if (formatCode.isEmpty()) { qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; return; } //mCachedMarginValid = false; // interpret first char as number format char: QString allowedFormatChars(QLatin1String("eEfgG")); if (allowedFormatChars.contains(formatCode.at(0))) { mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } if (formatCode.length() < 2) { mNumberBeautifulPowers = false; mNumberMultiplyCross = false; } else { // interpret second char as indicator for beautiful decimal powers: if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) mNumberBeautifulPowers = true; else qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; if (formatCode.length() < 3) { mNumberMultiplyCross = false; } else { // interpret third char as indicator for dot or cross multiplication symbol: if (formatCode.at(2) == QLatin1Char('c')) mNumberMultiplyCross = true; else if (formatCode.at(2) == QLatin1Char('d')) mNumberMultiplyCross = false; else qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; } } mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers); mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot); } /*! Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) for details. The effect of precisions are most notably for number Formats starting with 'e', see \ref setNumberFormat */ void QCPPolarAxisRadial::setNumberPrecision(int precision) { if (mNumberPrecision != precision) { mNumberPrecision = precision; //mCachedMarginValid = false; } } /*! Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPPolarAxisRadial::setTickLength(int inside, int outside) { setTickLengthIn(inside); setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPPolarAxisRadial::setTickLengthIn(int inside) { if (mTickLengthIn != inside) { mTickLengthIn = inside; } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPPolarAxisRadial::setTickLengthOut(int outside) { if (mTickLengthOut != outside) { mTickLengthOut = outside; //mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets whether sub tick marks are displayed. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks) \see setTicks */ void QCPPolarAxisRadial::setSubTicks(bool show) { if (mSubTicks != show) { mSubTicks = show; //mCachedMarginValid = false; } } /*! Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPPolarAxisRadial::setSubTickLength(int inside, int outside) { setSubTickLengthIn(inside); setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPPolarAxisRadial::setSubTickLengthIn(int inside) { if (mSubTickLengthIn != inside) { mSubTickLengthIn = inside; } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPPolarAxisRadial::setSubTickLengthOut(int outside) { if (mSubTickLengthOut != outside) { mSubTickLengthOut = outside; //mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the pen, the axis base line is drawn with. \see setTickPen, setSubTickPen */ void QCPPolarAxisRadial::setBasePen(const QPen &pen) { mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. \see setTickLength, setBasePen */ void QCPPolarAxisRadial::setTickPen(const QPen &pen) { mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. \see setSubTickCount, setSubTickLength, setBasePen */ void QCPPolarAxisRadial::setSubTickPen(const QPen &pen) { mSubTickPen = pen; } /*! Sets the font of the axis label. \see setLabelColor */ void QCPPolarAxisRadial::setLabelFont(const QFont &font) { if (mLabelFont != font) { mLabelFont = font; //mCachedMarginValid = false; } } /*! Sets the color of the axis label. \see setLabelFont */ void QCPPolarAxisRadial::setLabelColor(const QColor &color) { mLabelColor = color; } /*! Sets the text of the axis label that will be shown below/above or next to the axis, depending on its orientation. To disable axis labels, pass an empty string as \a str. */ void QCPPolarAxisRadial::setLabel(const QString &str) { if (mLabel != str) { mLabel = str; //mCachedMarginValid = false; } } /*! Sets the distance between the tick labels and the axis label. \see setTickLabelPadding, setPadding */ void QCPPolarAxisRadial::setLabelPadding(int padding) { if (mLabelPadding != padding) { mLabelPadding = padding; //mCachedMarginValid = false; } } /*! Sets the font that is used for tick labels when they are selected. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font) { if (font != mSelectedTickLabelFont) { mSelectedTickLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } } /*! Sets the font that is used for the axis label when it is selected. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font) { mSelectedLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color) { if (color != mSelectedTickLabelColor) { mSelectedTickLabelColor = color; } } /*! Sets the color that is used for the axis label when it is selected. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color) { mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen) { mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen) { mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen) { mSelectedSubTickPen = pen; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPPolarAxisRadial::moveRange(double diff) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { mRange.lower += diff; mRange.upper += diff; } else // mScaleType == stLogarithmic { mRange.lower *= diff; mRange.upper *= diff; } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis by \a factor around the center of the current axis range. For example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around the center will have moved symmetrically closer). If you wish to scale around a different coordinate than the current axis range center, use the overload \ref scaleRange(double factor, double center). */ void QCPPolarAxisRadial::scaleRange(double factor) { scaleRange(factor, range().center()); } /*! \overload Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates around 1.0 will have moved symmetrically closer to 1.0). \see scaleRange(double factor) */ void QCPPolarAxisRadial::scaleRange(double factor, double center) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { QCPRange newRange; newRange.lower = (mRange.lower-center)*factor + center; newRange.upper = (mRange.upper-center)*factor + center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLinScale(); } else // mScaleType == stLogarithmic { if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range { QCPRange newRange; newRange.lower = qPow(mRange.lower/center, factor)*center; newRange.upper = qPow(mRange.upper/center, factor)*center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLogScale(); } else qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; } emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables) { Q_UNUSED(onlyVisiblePlottables) /* TODO QList p = plottables(); QCPRange newRange; bool haveRange = false; for (int i=0; irealVisibility() && onlyVisiblePlottables) continue; QCPRange plottableRange; bool currentFoundRange; QCP::SignDomain signDomain = QCP::sdBoth; if (mScaleType == stLogarithmic) signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); if (p.at(i)->keyAxis() == this) plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); else plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); if (currentFoundRange) { if (!haveRange) newRange = plottableRange; else newRange.expand(plottableRange); haveRange = true; } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mScaleType == stLinear) { newRange.lower = center-mRange.size()/2.0; newRange.upper = center+mRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mRange.upper/mRange.lower); newRange.upper = center*qSqrt(mRange.upper/mRange.lower); } } setRange(newRange); } */ } /*! Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. */ void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const { QCPVector2D posVector(pixelPos-mCenter); radiusCoord = radiusToCoord(posVector.length()); angleCoord = mAngularAxis->angleRadToCoord(posVector.angle()); } /*! Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. */ QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const { const double radiusPixel = coordToRadius(radiusCoord); const double angleRad = mAngularAxis->coordToAngleRad(angleCoord); return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel); } double QCPPolarAxisRadial::coordToRadius(double coord) const { if (mScaleType == stLinear) { if (!mRangeReversed) return (coord-mRange.lower)/mRange.size()*mRadius; else return (mRange.upper-coord)/mRange.size()*mRadius; } else // mScaleType == stLogarithmic { if (coord >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just return outside visible range return !mRangeReversed ? mRadius+200 : mRadius-200; else if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range return !mRangeReversed ? mRadius-200 :mRadius+200; else { if (!mRangeReversed) return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius; else return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius; } } } double QCPPolarAxisRadial::radiusToCoord(double radius) const { if (mScaleType == stLinear) { if (!mRangeReversed) return (radius)/mRadius*mRange.size()+mRange.lower; else return -(radius)/mRadius*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower; else return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper; } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. If the axis is not visible (\ref setVisible), this function always returns \ref spNone. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const { Q_UNUSED(pos) // TODO remove later if (!mVisible) return spNone; /* TODO: if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; else */ return spNone; } /* inherits documentation from base class */ double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; SelectablePart part = getPartAt(pos); if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) return -1; if (details) details->setValue(part); return mParentPlot->selectionTolerance()*0.99; } /* inherits documentation from base class */ void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) SelectablePart part = details.value(); if (mSelectableParts.testFlag(part)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^part : part); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged) { SelectableParts selBefore = mSelectedParts; setSelectedParts(mSelectedParts & ~mSelectableParts); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } /*! \internal This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref QCPAxisRect::setRangeDragAxes) \seebaseclassmethod \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. */ void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details) { Q_UNUSED(details) if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { event->ignore(); return; } if (event->buttons() & Qt::LeftButton) { mDragging = true; // initialize antialiasing backup in case we start dragging: if (mParentPlot->noAntialiasingOnDrag()) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) mDragStartRange = mRange; } } /*! \internal This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. \seebaseclassmethod \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. \see QCPAxis::mousePressEvent */ void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(event) // TODO remove later Q_UNUSED(startPos) // TODO remove later if (mDragging) { /* TODO const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); if (mScaleType == QCPPolarAxisRadial::stLinear) { const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff); } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic) { const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff); } */ if (mParentPlot->noAntialiasingOnDrag()) mParentPlot->setNotAntialiasedElements(QCP::aeAll); mParentPlot->replot(QCustomPlot::rpQueuedReplot); } } /*! \internal This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. \seebaseclassmethod \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. \see QCPAxis::mousePressEvent */ void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(event) Q_UNUSED(startPos) mDragging = false; if (mParentPlot->noAntialiasingOnDrag()) { mParentPlot->setAntialiasedElements(mAADragBackup); mParentPlot->setNotAntialiasedElements(mNotAADragBackup); } } /*! \internal This mouse event reimplementation provides the functionality to let the user zoom individual axes exclusively, by performing the wheel event on top of the axis. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref QCPAxisRect::setRangeZoomAxes) \seebaseclassmethod \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent. */ void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event) { // Mouse range zooming interaction: if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { event->ignore(); return; } // TODO: //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually //const double factor = qPow(mRangeZoomFactor, wheelSteps); //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y())); mParentPlot->replot(); } void QCPPolarAxisRadial::updateGeometry(const QPointF ¢er, double radius) { mCenter = center; mRadius = radius; if (mRadius < 1) mRadius = 1; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \seebaseclassmethod \see setAntialiased */ void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. \seebaseclassmethod */ void QCPPolarAxisRadial::draw(QCPPainter *painter) { const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI; const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF // draw baseline: painter->setPen(getBasePen()); painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5))); // draw subticks: if (!mSubTickVector.isEmpty()) { painter->setPen(getSubTickPen()); for (int i=0; idrawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut)); } } // draw ticks and labels: if (!mTickVector.isEmpty()) { mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range mLabelPainter.setFont(getTickLabelFont()); mLabelPainter.setColor(getTickLabelColor()); const QPen ticksPen = getTickPen(); painter->setPen(ticksPen); for (int i=0; idrawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut)); // possibly draw tick labels: if (!mTickVectorLabels.isEmpty()) { if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) || (mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i)); } } } } /*! \internal Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling QCPAxisTicker::generate on the currently installed ticker. If a change in the label text/count is detected, the cached axis margin is invalidated to make sure the next margin calculation recalculates the label sizes and returns an up-to-date value. */ void QCPPolarAxisRadial::setupTickVectors() { if (!mParentPlot) return; if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return; mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0); } /*! \internal Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPPolarAxisRadial::getBasePen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPPolarAxisRadial::getTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPPolarAxisRadial::getSubTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPPolarAxisRadial::getTickLabelFont() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPPolarAxisRadial::getLabelFont() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPPolarAxisRadial::getTickLabelColor() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPPolarAxisRadial::getLabelColor() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /* inherits documentation from base class */ QCP::Interaction QCPPolarAxisRadial::selectionCategory() const { return QCP::iSelectAxes; } /* end of 'src/polar/radialaxis.cpp' */ /* including file 'src/polar/layoutelement-angularaxis.cpp' */ /* modified 2021-03-29T02:30:44, size 57266 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPolarAxisAngular //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPolarAxisAngular \brief The main container for polar plots, representing the angular axis as a circle \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and functionality to be incomplete, as well as changing public interfaces in the future. */ /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. \see QCPLayoutInset */ /*! \fn int QCPPolarAxisAngular::left() const Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::right() const Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::top() const Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::bottom() const Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::width() const Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::height() const Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPPolarAxisAngular::size() const Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::topLeft() const Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::topRight() const Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::bottomRight() const Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::center() const Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /* end documentation of inline functions */ /*! Creates a QCPPolarAxis instance and sets default values. An axis is added for each of the four sides, the top and right axes are set invisible initially. */ QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mBackgroundBrush(Qt::NoBrush), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mInsetLayout(new QCPLayoutInset), mRangeDrag(false), mRangeZoom(false), mRangeZoomFactor(0.85), // axis base: mAngle(-90), mAngleRad(mAngle/180.0*M_PI), mSelectableParts(spAxis | spTickLabels | spAxisLabel), mSelectedParts(spNone), mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedBasePen(QPen(Qt::blue, 2)), // axis label: mLabelPadding(0), mLabel(), mLabelFont(mParentPlot->font()), mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), mLabelColor(Qt::black), mSelectedLabelColor(Qt::blue), // tick labels: //mTickLabelPadding(0), in label painter mTickLabels(true), //mTickLabelRotation(0), in label painter mTickLabelFont(mParentPlot->font()), mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), mTickLabelColor(Qt::black), mSelectedTickLabelColor(Qt::blue), mNumberPrecision(6), mNumberFormatChar('g'), mNumberBeautifulPowers(true), mNumberMultiplyCross(false), // ticks and subticks: mTicks(true), mSubTicks(true), mTickLengthIn(5), mTickLengthOut(0), mSubTickLengthIn(2), mSubTickLengthOut(0), mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedTickPen(QPen(Qt::blue, 2)), mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedSubTickPen(QPen(Qt::blue, 2)), // scale and range: mRange(0, 360), mRangeReversed(false), // internal members: mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect mGrid(new QCPPolarGrid(this)), mTicker(new QCPAxisTickerFixed), mDragging(false), mLabelPainter(parentPlot) { // TODO: //mInsetLayout->initializeParentPlot(mParentPlot); //mInsetLayout->setParentLayerable(this); //mInsetLayout->setParent(this); if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast().data()) { fixedTicker->setTickStep(30); } setAntialiased(true); setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again setTickLabelPadding(5); setTickLabelRotation(0); setTickLabelMode(lmUpright); mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal); mLabelPainter.setAbbreviateDecimalPowers(false); mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes setMinimumSize(50, 50); setMinimumMargins(QMargins(30, 30, 30, 30)); addRadialAxis(); mGrid->setRadialAxis(radialAxis()); } QCPPolarAxisAngular::~QCPPolarAxisAngular() { delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order mGrid = 0; delete mInsetLayout; mInsetLayout = 0; QList radialAxesList = radialAxes(); for (int i=0; i= 0 && index < mRadialAxes.size()) { return mRadialAxes.at(index); } else { qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; return 0; } } /*! Returns all axes on the axis rect sides specified with \a types. \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. \see axis */ QList QCPPolarAxisAngular::radialAxes() const { return mRadialAxes; } /*! Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to remove an axis, use \ref removeAxis instead of deleting it manually. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership of the axis, so you may not delete it afterwards. Further, the \a axis must have been created with this axis rect as parent and with the same axis type as specified in \a type. If this is not the case, a debug output is generated, the axis is not added, and the method returns 0. This method can not be used to move \a axis between axis rects. The same \a axis instance must not be added multiple times to the same or different axis rects. If an axis rect side already contains one or more axes, the lower and upper endings of the new axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref QCPLineEnding::esHalfBar. \see addAxes, setupFullAxesBox */ QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis) { QCPPolarAxisRadial *newAxis = axis; if (!newAxis) { newAxis = new QCPPolarAxisRadial(this); } else // user provided existing axis instance, do some sanity checks { if (newAxis->angularAxis() != this) { qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis"; return 0; } if (radialAxes().contains(newAxis)) { qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis"; return 0; } } mRadialAxes.append(newAxis); return newAxis; } /*! Removes the specified \a axis from the axis rect and deletes it. Returns true on success, i.e. if \a axis was a valid axis in this axis rect. \see addAxis */ bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis) { if (mRadialAxes.contains(radialAxis)) { mRadialAxes.removeOne(radialAxis); delete radialAxis; return true; } else { qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast(radialAxis); return false; } } QRegion QCPPolarAxisAngular::exactClipRegion() const { return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse); } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPPolarAxisAngular::moveRange(double diff) { QCPRange oldRange = mRange; mRange.lower += diff; mRange.upper += diff; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis by \a factor around the center of the current axis range. For example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around the center will have moved symmetrically closer). If you wish to scale around a different coordinate than the current axis range center, use the overload \ref scaleRange(double factor, double center). */ void QCPPolarAxisAngular::scaleRange(double factor) { scaleRange(factor, range().center()); } /*! \overload Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates around 1.0 will have moved symmetrically closer to 1.0). \see scaleRange(double factor) */ void QCPPolarAxisAngular::scaleRange(double factor, double center) { QCPRange oldRange = mRange; QCPRange newRange; newRange.lower = (mRange.lower-center)*factor + center; newRange.upper = (mRange.upper-center)*factor + center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLinScale(); emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables) { QCPRange newRange; bool haveRange = false; for (int i=0; irealVisibility() && onlyVisiblePlottables) continue; QCPRange range; bool currentFoundRange; if (mGraphs.at(i)->keyAxis() == this) range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth); else range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth); if (currentFoundRange) { if (!haveRange) newRange = range; else newRange.expand(range); haveRange = true; } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason newRange.lower = center-mRange.size()/2.0; newRange.upper = center+mRange.size()/2.0; } setRange(newRange); } } /*! Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. */ void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const { if (!mRadialAxes.isEmpty()) mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord); else qDebug() << Q_FUNC_INFO << "no radial axis configured"; } /*! Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. */ QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const { if (!mRadialAxes.isEmpty()) { return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord); } else { qDebug() << Q_FUNC_INFO << "no radial axis configured"; return QPointF(); } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. If the axis is not visible (\ref setVisible), this function always returns \ref spNone. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const { Q_UNUSED(pos) // TODO remove later if (!mVisible) return spNone; /* TODO: if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; else */ return spNone; } /* inherits documentation from base class */ double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { /* if (!mParentPlot) return -1; SelectablePart part = getPartAt(pos); if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) return -1; if (details) details->setValue(part); return mParentPlot->selectionTolerance()*0.99; */ Q_UNUSED(details) if (onlySelectable) return -1; if (QRectF(mOuterRect).contains(pos)) { if (mParentPlot) return mParentPlot->selectionTolerance()*0.99; else { qDebug() << Q_FUNC_INFO << "parent plot not defined"; return -1; } } else return -1; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPPolarAxisAngular. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its QCPInsetLayout::update function. \seebaseclassmethod */ void QCPPolarAxisAngular::update(UpdatePhase phase) { QCPLayoutElement::update(phase); switch (phase) { case upPreparation: { setupTickVectors(); for (int i=0; isetupTickVectors(); break; } case upLayout: { mCenter = mRect.center(); mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height())); if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble for (int i=0; iupdateGeometry(mCenter, mRadius); mInsetLayout->setOuterRect(rect()); break; } default: break; } // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout): mInsetLayout->update(phase); } /* inherits documentation from base class */ QList QCPPolarAxisAngular::elements(bool recursive) const { QList result; if (mInsetLayout) { result << mInsetLayout; if (recursive) result << mInsetLayout->elements(recursive); } return result; } bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph) { if (!mGraphs.contains(graph)) { qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast(graph); return false; } // remove plottable from legend: graph->removeFromLegend(); // remove plottable: delete graph; mGraphs.removeOne(graph); return true; } /* inherits documentation from base class */ void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /* inherits documentation from base class */ void QCPPolarAxisAngular::draw(QCPPainter *painter) { drawBackground(painter, mCenter, mRadius); // draw baseline circle: painter->setPen(getBasePen()); painter->drawEllipse(mCenter, mRadius, mRadius); // draw subticks: if (!mSubTickVector.isEmpty()) { painter->setPen(getSubTickPen()); for (int i=0; idrawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn), mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut)); } } // draw ticks and labels: if (!mTickVector.isEmpty()) { mLabelPainter.setAnchorReference(mCenter); mLabelPainter.setFont(getTickLabelFont()); mLabelPainter.setColor(getTickLabelColor()); const QPen ticksPen = getTickPen(); painter->setPen(ticksPen); for (int i=0; idrawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick); // draw tick labels: if (!mTickVectorLabels.isEmpty()) { if (i < mTickVectorLabels.count()-1 || (mTickVectorCosSin.at(i)-mTickVectorCosSin.first()).manhattanLength() > 5/180.0*M_PI) // skip last label if it's closer than approx 5 degrees to first mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i)); } } } } /* inherits documentation from base class */ QCP::Interaction QCPPolarAxisAngular::selectionCategory() const { return QCP::iSelectAxes; } /*! Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPPolarAxisAngular::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! \overload Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. The brush will be drawn before (under) any background pixmap, which may be specified with \ref setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. \see setBackground(const QPixmap &pm) */ void QCPPolarAxisAngular::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCPPolarAxisAngular::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. \see setBackground, setBackgroundScaled */ void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } void QCPPolarAxisAngular::setRangeDrag(bool enabled) { mRangeDrag = enabled; } void QCPPolarAxisAngular::setRangeZoom(bool enabled) { mRangeZoom = enabled; } void QCPPolarAxisAngular::setRangeZoomFactor(double factor) { mRangeZoomFactor = factor; } /*! Sets the range of the axis. This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. To invert the direction of an axis, use \ref setRangeReversed. */ void QCPPolarAxisAngular::setRange(const QCPRange &range) { if (range.lower == mRange.lower && range.upper == mRange.upper) return; if (!QCPRange::validRange(range)) return; QCPRange oldRange = mRange; mRange = range.sanitizedForLinScale(); emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part, independent of the \ref setSelectableParts setting. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected) { if (mSelectedParts != selected) { mSelectedParts = selected; emit selectionChanged(mSelectedParts); } } /*! \overload Sets the lower and upper bound of the axis range. To invert the direction of an axis, use \ref setRangeReversed. There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPPolarAxisAngular::setRange(double lower, double upper) { if (lower == mRange.lower && upper == mRange.upper) return; if (!QCPRange::validRange(lower, upper)) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange.upper = upper; mRange = mRange.sanitizedForLinScale(); emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! \overload Sets the range of the axis. The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, or center of the range to be aligned with \a position. Any other values of \a alignment will default to Qt::AlignCenter. */ void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment) { if (alignment == Qt::AlignLeft) setRange(position, position+size); else if (alignment == Qt::AlignRight) setRange(position-size, position); else // alignment == Qt::AlignCenter setRange(position-size/2.0, position+size/2.0); } /*! Sets the lower bound of the axis range. The upper bound is not changed. \see setRange */ void QCPPolarAxisAngular::setRangeLower(double lower) { if (mRange.lower == lower) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange = mRange.sanitizedForLinScale(); emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets the upper bound of the axis range. The lower bound is not changed. \see setRange */ void QCPPolarAxisAngular::setRangeUpper(double upper) { if (mRange.upper == upper) return; QCPRange oldRange = mRange; mRange.upper = upper; mRange = mRange.sanitizedForLinScale(); emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the direction of increasing values is inverted. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part of the \ref setRange interface will still reference the mathematically smaller number than the \a upper part. */ void QCPPolarAxisAngular::setRangeReversed(bool reversed) { mRangeReversed = reversed; } void QCPPolarAxisAngular::setAngle(double degrees) { mAngle = degrees; mAngleRad = mAngle/180.0*M_PI; } /*! The axis ticker is responsible for generating the tick positions and tick labels. See the documentation of QCPAxisTicker for details on how to work with axis tickers. You can change the tick positioning/labeling behaviour of this axis by setting a different QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis ticker, access it via \ref ticker. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis ticker simply by passing the same shared pointer to multiple axes. \see ticker */ void QCPPolarAxisAngular::setTicker(QSharedPointer ticker) { if (ticker) mTicker = ticker; else qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker"; // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector } /*! Sets whether tick marks are displayed. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve that, see \ref setTickLabels. \see setSubTicks */ void QCPPolarAxisAngular::setTicks(bool show) { if (mTicks != show) { mTicks = show; //mCachedMarginValid = false; } } /*! Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. */ void QCPPolarAxisAngular::setTickLabels(bool show) { if (mTickLabels != show) { mTickLabels = show; //mCachedMarginValid = false; if (!mTickLabels) mTickVectorLabels.clear(); } } /*! Sets the distance between the axis base line (including any outward ticks) and the tick labels. \see setLabelPadding, setPadding */ void QCPPolarAxisAngular::setTickLabelPadding(int padding) { mLabelPainter.setPadding(padding); } /*! Sets the font of the tick labels. \see setTickLabels, setTickLabelColor */ void QCPPolarAxisAngular::setTickLabelFont(const QFont &font) { mTickLabelFont = font; } /*! Sets the color of the tick labels. \see setTickLabels, setTickLabelFont */ void QCPPolarAxisAngular::setTickLabelColor(const QColor &color) { mTickLabelColor = color; } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPPolarAxisAngular::setTickLabelRotation(double degrees) { mLabelPainter.setRotation(degrees); } void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode) { switch (mode) { case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break; case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break; } } /*! Sets the number format for the numbers in tick labels. This \a formatCode is an extended version of the format code used e.g. by QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" section in the detailed description of the QString class. \a formatCode is a string of one, two or three characters. The first character is identical to the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, whichever is shorter. The second and third characters are optional and specific to QCustomPlot:\n If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which might be visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. Examples for \a formatCode: \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, normal scientific format is used \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with beautifully typeset decimal powers and a dot as multiplication sign \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as multiplication sign \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal powers. Format code will be reduced to 'f'. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format code will not be changed. */ void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode) { if (formatCode.isEmpty()) { qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; return; } //mCachedMarginValid = false; // interpret first char as number format char: QString allowedFormatChars(QLatin1String("eEfgG")); if (allowedFormatChars.contains(formatCode.at(0))) { mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } if (formatCode.length() < 2) { mNumberBeautifulPowers = false; mNumberMultiplyCross = false; } else { // interpret second char as indicator for beautiful decimal powers: if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) mNumberBeautifulPowers = true; else qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; if (formatCode.length() < 3) { mNumberMultiplyCross = false; } else { // interpret third char as indicator for dot or cross multiplication symbol: if (formatCode.at(2) == QLatin1Char('c')) mNumberMultiplyCross = true; else if (formatCode.at(2) == QLatin1Char('d')) mNumberMultiplyCross = false; else qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; } } mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers); mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot); } /*! Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) for details. The effect of precisions are most notably for number Formats starting with 'e', see \ref setNumberFormat */ void QCPPolarAxisAngular::setNumberPrecision(int precision) { if (mNumberPrecision != precision) { mNumberPrecision = precision; //mCachedMarginValid = false; } } /*! Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPPolarAxisAngular::setTickLength(int inside, int outside) { setTickLengthIn(inside); setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPPolarAxisAngular::setTickLengthIn(int inside) { if (mTickLengthIn != inside) { mTickLengthIn = inside; } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPPolarAxisAngular::setTickLengthOut(int outside) { if (mTickLengthOut != outside) { mTickLengthOut = outside; //mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets whether sub tick marks are displayed. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks) \see setTicks */ void QCPPolarAxisAngular::setSubTicks(bool show) { if (mSubTicks != show) { mSubTicks = show; //mCachedMarginValid = false; } } /*! Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPPolarAxisAngular::setSubTickLength(int inside, int outside) { setSubTickLengthIn(inside); setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPPolarAxisAngular::setSubTickLengthIn(int inside) { if (mSubTickLengthIn != inside) { mSubTickLengthIn = inside; } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPPolarAxisAngular::setSubTickLengthOut(int outside) { if (mSubTickLengthOut != outside) { mSubTickLengthOut = outside; //mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the pen, the axis base line is drawn with. \see setTickPen, setSubTickPen */ void QCPPolarAxisAngular::setBasePen(const QPen &pen) { mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. \see setTickLength, setBasePen */ void QCPPolarAxisAngular::setTickPen(const QPen &pen) { mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. \see setSubTickCount, setSubTickLength, setBasePen */ void QCPPolarAxisAngular::setSubTickPen(const QPen &pen) { mSubTickPen = pen; } /*! Sets the font of the axis label. \see setLabelColor */ void QCPPolarAxisAngular::setLabelFont(const QFont &font) { if (mLabelFont != font) { mLabelFont = font; //mCachedMarginValid = false; } } /*! Sets the color of the axis label. \see setLabelFont */ void QCPPolarAxisAngular::setLabelColor(const QColor &color) { mLabelColor = color; } /*! Sets the text of the axis label that will be shown below/above or next to the axis, depending on its orientation. To disable axis labels, pass an empty string as \a str. */ void QCPPolarAxisAngular::setLabel(const QString &str) { if (mLabel != str) { mLabel = str; //mCachedMarginValid = false; } } /*! Sets the distance between the tick labels and the axis label. \see setTickLabelPadding, setPadding */ void QCPPolarAxisAngular::setLabelPadding(int padding) { if (mLabelPadding != padding) { mLabelPadding = padding; //mCachedMarginValid = false; } } /*! Sets the font that is used for tick labels when they are selected. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font) { if (font != mSelectedTickLabelFont) { mSelectedTickLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } } /*! Sets the font that is used for the axis label when it is selected. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font) { mSelectedLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color) { if (color != mSelectedTickLabelColor) { mSelectedTickLabelColor = color; } } /*! Sets the color that is used for the axis label when it is selected. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color) { mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen) { mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen) { mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen) { mSelectedSubTickPen = pen; } /*! \internal Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF ¢er, double radius) { // draw background fill (don't use circular clip, looks bad): if (mBackgroundBrush != Qt::NoBrush) { QPainterPath ellipsePath; ellipsePath.addEllipse(center, radius, radius); painter->fillPath(ellipsePath, mBackgroundBrush); } // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { QRegion clipCircle(center.x()-radius, center.y()-radius, qRound(2*radius), qRound(2*radius), QRegion::Ellipse); QRegion originalClip = painter->clipRegion(); painter->setClipRegion(clipCircle); if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mRect.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); } painter->setClipRegion(originalClip); } } /*! \internal Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling QCPAxisTicker::generate on the currently installed ticker. If a change in the label text/count is detected, the cached axis margin is invalidated to make sure the next margin calculation recalculates the label sizes and returns an up-to-date value. */ void QCPPolarAxisAngular::setupTickVectors() { if (!mParentPlot) return; if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0); // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice: mTickVectorCosSin.resize(mTickVector.size()); for (int i=0; ibuttons() & Qt::LeftButton) { mDragging = true; // initialize antialiasing backup in case we start dragging: if (mParentPlot->noAntialiasingOnDrag()) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { mDragAngularStart = range(); mDragRadialStart.clear(); for (int i=0; irange()); } } } /*! \internal Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. \see mousePressEvent, mouseReleaseEvent */ void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(startPos) bool doReplot = false; // Mouse range dragging interaction: if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDrag) { doReplot = true; double angleCoordStart, radiusCoordStart; double angleCoord, radiusCoord; pixelToCoord(startPos, angleCoordStart, radiusCoordStart); pixelToCoord(event->pos(), angleCoord, radiusCoord); double diff = angleCoordStart - angleCoord; setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff); } for (int i=0; irangeDrag()) continue; doReplot = true; double angleCoordStart, radiusCoordStart; double angleCoord, radiusCoord; ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart); ax->pixelToCoord(event->pos(), angleCoord, radiusCoord); if (ax->scaleType() == QCPPolarAxisRadial::stLinear) { double diff = radiusCoordStart - radiusCoord; ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff); } else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic) { if (radiusCoord != 0) { double diff = radiusCoordStart/radiusCoord; ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff); } } } if (doReplot) // if either vertical or horizontal drag was enabled, do a replot { if (mParentPlot->noAntialiasingOnDrag()) mParentPlot->setNotAntialiasedElements(QCP::aeAll); mParentPlot->replot(QCustomPlot::rpQueuedReplot); } } } /* inherits documentation from base class */ void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { Q_UNUSED(event) Q_UNUSED(startPos) mDragging = false; if (mParentPlot->noAntialiasingOnDrag()) { mParentPlot->setAntialiasedElements(mAADragBackup); mParentPlot->setNotAntialiasedElements(mNotAADragBackup); } } /*! \internal Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of the scaling operation is the current cursor position inside the axis rect. The scaling factor is dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of the range zoom factor. This takes care of the wheel direction automatically, by inverting the factor, when the wheel step is negative (f^-1 = 1/f). */ void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event) { bool doReplot = false; // Mouse range zooming interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) const double delta = event->delta(); #else const double delta = event->angleDelta().y(); #endif #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) const QPointF pos = event->pos(); #else const QPointF pos = event->position(); #endif const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually if (mRangeZoom) { double angleCoord, radiusCoord; pixelToCoord(pos, angleCoord, radiusCoord); scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord); } for (int i=0; irangeZoom()) continue; doReplot = true; double angleCoord, radiusCoord; ax->pixelToCoord(pos, angleCoord, radiusCoord); ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord); } } if (doReplot) mParentPlot->replot(); } bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph) { if (mGraphs.contains(graph)) { qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast(graph); return false; } if (graph->keyAxis() != this) { qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast(graph); return false; } mGraphs.append(graph); // possibly add plottable to legend: if (mParentPlot->autoAddPlottableToLegend()) graph->addToLegend(); if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) graph->setLayer(mParentPlot->currentLayer()); return true; } /* end of 'src/polar/layoutelement-angularaxis.cpp' */ /* including file 'src/polar/polargrid.cpp' */ /* modified 2021-03-29T02:30:44, size 7493 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPolarGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPolarGrid \brief The grid in both angular and radial dimensions for polar plots \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and functionality to be incomplete, as well as changing public interfaces in the future. */ /*! Creates a QCPPolarGrid instance and sets default values. You shouldn't instantiate grids on their own, since every axis brings its own grid. */ QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) : QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), mType(gtNone), mSubGridType(gtNone), mAntialiasedSubGrid(true), mAntialiasedZeroLine(true), mParentAxis(parentAxis) { // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called setParent(parentAxis); setType(gtAll); setSubGridType(gtNone); setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); setAntialiased(true); } void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis) { mRadialAxis = axis; } void QCPPolarGrid::setType(GridTypes type) { mType = type; } void QCPPolarGrid::setSubGridType(GridTypes type) { mSubGridType = type; } /*! Sets whether sub grid lines are drawn antialiased. */ void QCPPolarGrid::setAntialiasedSubGrid(bool enabled) { mAntialiasedSubGrid = enabled; } /*! Sets whether zero lines are drawn antialiased. */ void QCPPolarGrid::setAntialiasedZeroLine(bool enabled) { mAntialiasedZeroLine = enabled; } /*! Sets the pen with which (major) grid lines are drawn. */ void QCPPolarGrid::setAngularPen(const QPen &pen) { mAngularPen = pen; } /*! Sets the pen with which sub grid lines are drawn. */ void QCPPolarGrid::setAngularSubGridPen(const QPen &pen) { mAngularSubGridPen = pen; } void QCPPolarGrid::setRadialPen(const QPen &pen) { mRadialPen = pen; } void QCPPolarGrid::setRadialSubGridPen(const QPen &pen) { mRadialSubGridPen = pen; } void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen) { mRadialZeroLinePen = pen; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPPolarGrid::draw(QCPPainter *painter) { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } const QPointF center = mParentAxis->mCenter; const double radius = mParentAxis->mRadius; painter->setBrush(Qt::NoBrush); // draw main angular grid: if (mType.testFlag(gtAngular)) drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen); // draw main radial grid: if (mType.testFlag(gtRadial) && mRadialAxis) drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen); applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid); // draw sub angular grid: if (mSubGridType.testFlag(gtAngular)) drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen); // draw sub radial grid: if (mSubGridType.testFlag(gtRadial) && mRadialAxis) drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen); } void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector &coords, const QPen &pen, const QPen &zeroPen) { if (!mRadialAxis) return; if (coords.isEmpty()) return; const bool drawZeroLine = zeroPen != Qt::NoPen; const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6; painter->setPen(pen); for (int i=0; icoordToRadius(coords.at(i)); if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(zeroPen); painter->drawEllipse(center, r, r); painter->setPen(pen); applyDefaultAntialiasingHint(painter); } else { painter->drawEllipse(center, r, r); } } } void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector &ticksCosSin, const QPen &pen) { if (ticksCosSin.isEmpty()) return; painter->setPen(pen); for (int i=0; idrawLine(center, center+ticksCosSin.at(i)*radius); } /* end of 'src/polar/polargrid.cpp' */ /* including file 'src/polar/polargraph.cpp' */ /* modified 2021-03-29T02:30:44, size 44035 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPolarLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPolarLegendItem \brief A legend item for polar plots \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and functionality to be incomplete, as well as changing public interfaces in the future. */ QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) : QCPAbstractLegendItem(parent), mPolarGraph(graph) { setAntialiased(false); } void QCPPolarLegendItem::draw(QCPPainter *painter) { if (!mPolarGraph) return; painter->setFont(getFont()); painter->setPen(QPen(getTextColor())); QSizeF iconSize = mParentLegend->iconSize(); QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name()); QRectF iconRect(mRect.topLeft(), iconSize); int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name()); // draw icon: painter->save(); painter->setClipRect(iconRect, Qt::IntersectClip); mPolarGraph->drawLegendIcon(painter, iconRect); painter->restore(); // draw icon border: if (getIconBorderPen().style() != Qt::NoPen) { painter->setPen(getIconBorderPen()); painter->setBrush(Qt::NoBrush); int halfPen = qCeil(painter->pen().widthF()*0.5)+1; painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped painter->drawRect(iconRect); } } QSize QCPPolarLegendItem::minimumOuterSizeHint() const { if (!mPolarGraph) return QSize(); QSize result(0, 0); QRect textRect; QFontMetrics fontMetrics(getFont()); QSize iconSize = mParentLegend->iconSize(); textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name()); result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); result.setHeight(qMax(textRect.height(), iconSize.height())); result.rwidth() += mMargins.left()+mMargins.right(); result.rheight() += mMargins.top()+mMargins.bottom(); return result; } QPen QCPPolarLegendItem::getIconBorderPen() const { return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } QColor QCPPolarLegendItem::getTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } QFont QCPPolarLegendItem::getFont() const { return mSelected ? mSelectedFont : mFont; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPolarGraph //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPolarGraph \brief A radial graph used to display data in polar plots \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and functionality to be incomplete, as well as changing public interfaces in the future. */ /* start of documentation of inline functions */ // TODO /* end of documentation of inline functions */ /*! Constructs a graph which uses \a keyAxis as its angular and \a valueAxis as its radial axis. \a keyAxis and \a valueAxis must reside in the same QCustomPlot, and the radial axis must be associated with the angular axis. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The created QCPPolarGraph is automatically registered with the QCustomPlot instance inferred from \a keyAxis. This QCustomPlot instance takes ownership of the QCPPolarGraph, so do not delete it manually but use QCPPolarAxisAngular::removeGraph() instead. To directly create a QCPPolarGraph inside a plot, you shoud use the QCPPolarAxisAngular::addGraph method. */ QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) : QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis), mDataContainer(new QCPGraphDataContainer), mName(), mAntialiasedFill(true), mAntialiasedScatters(true), mPen(Qt::black), mBrush(Qt::NoBrush), mPeriodic(true), mKeyAxis(keyAxis), mValueAxis(valueAxis), mSelectable(QCP::stWhole) //mSelectionDecorator(0) // TODO { if (keyAxis->parentPlot() != valueAxis->parentPlot()) qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; mKeyAxis->registerPolarGraph(this); //setSelectionDecorator(new QCPSelectionDecorator); // TODO setPen(QPen(Qt::blue, 0)); setBrush(Qt::NoBrush); setLineStyle(lsLine); } QCPPolarGraph::~QCPPolarGraph() { /* TODO if (mSelectionDecorator) { delete mSelectionDecorator; mSelectionDecorator = 0; } */ } /*! The name is the textual representation of this plottable as it is displayed in the legend (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. */ void QCPPolarGraph::setName(const QString &name) { mName = name; } /*! Sets whether fills of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPPolarGraph::setAntialiasedFill(bool enabled) { mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPPolarGraph::setAntialiasedScatters(bool enabled) { mAntialiasedScatters = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPPolarGraph::setPen(const QPen &pen) { mPen = pen; } /*! The brush is used to draw basic fills of the plottable representation in the plot. The Fill can be a color, gradient or texture, see the usage of QBrush. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. \see setPen */ void QCPPolarGraph::setBrush(const QBrush &brush) { mBrush = brush; } void QCPPolarGraph::setPeriodic(bool enabled) { mPeriodic = enabled; } /*! The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setValueAxis */ void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis) { mKeyAxis = axis; } /*! The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's key axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setKeyAxis */ void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis) { mValueAxis = axis; } /*! Sets whether and to which granularity this plottable can be selected. A selection can happen by clicking on the QCustomPlot surface (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by calling \ref setSelection. \see setSelection, QCP::SelectionType */ void QCPPolarGraph::setSelectable(QCP::SelectionType selectable) { if (mSelectable != selectable) { mSelectable = selectable; QCPDataSelection oldSelection = mSelection; mSelection.enforceType(mSelectable); emit selectableChanged(mSelectable); if (mSelection != oldSelection) { emit selectionChanged(selected()); emit selectionChanged(mSelection); } } } /*! Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref selectionDecorator). The entire selection mechanism for plottables is handled automatically when \ref QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when you wish to change the selection state programmatically. Using \ref setSelectable you can further specify for each plottable whether and to which granularity it is selectable. If \a selection is not compatible with the current \ref QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted accordingly (see \ref QCPDataSelection::enforceType). emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPPolarGraph::setSelection(QCPDataSelection selection) { selection.enforceType(mSelectable); if (mSelection != selection) { mSelection = selection; emit selectionChanged(selected()); emit selectionChanged(mSelection); } } /*! \overload Replaces the current data container with the provided \a data container. Since a QSharedPointer is used, multiple QCPPolarGraphs may share the same data container safely. Modifying the data in the container will then affect all graphs that share the container. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers: \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-1 If you do not wish to share containers, but create a copy from an existing container, rather use the \ref QCPDataContainer::set method on the graph's data container directly: \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-2 \see addData */ void QCPPolarGraph::setData(QSharedPointer data) { mDataContainer = data; } /*! \overload Replaces the current data with the provided points in \a keys and \a values. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you can set \a alreadySorted to true, to improve performance by saving a sorting run. \see addData */ void QCPPolarGraph::setData(const QVector &keys, const QVector &values, bool alreadySorted) { mDataContainer->clear(); addData(keys, values, alreadySorted); } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPPolarGraph::setLineStyle(LineStyle ls) { mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } void QCPPolarGraph::addData(const QVector &keys, const QVector &values, bool alreadySorted) { if (keys.size() != values.size()) qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size(); const int n = qMin(keys.size(), values.size()); QVector tempData(n); QVector::iterator it = tempData.begin(); const QVector::iterator itEnd = tempData.end(); int i = 0; while (it != itEnd) { it->key = keys[i]; it->value = values[i]; ++it; ++i; } mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write } void QCPPolarGraph::addData(double key, double value) { mDataContainer->add(QCPGraphData(key, value)); } /*! Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to customize the visual representation of selected data ranges further than by using the default QCPSelectionDecorator. The plottable takes ownership of the \a decorator. The currently set decorator can be accessed via \ref selectionDecorator. */ /* void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator) { if (decorator) { if (decorator->registerWithPlottable(this)) { if (mSelectionDecorator) // delete old decorator if necessary delete mSelectionDecorator; mSelectionDecorator = decorator; } } else if (mSelectionDecorator) // just clear decorator { delete mSelectionDecorator; mSelectionDecorator = 0; } } */ void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const { if (mValueAxis) { const QPointF point = mValueAxis->coordToPixel(key, value); x = point.x(); y = point.y(); } else { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; } } const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const { if (mValueAxis) { return mValueAxis->coordToPixel(key, value); } else { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } } void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const { if (mValueAxis) { mValueAxis->pixelToCoord(QPointF(x, y), key, value); } else { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; } } void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { if (mValueAxis) { mValueAxis->pixelToCoord(pixelPos, key, value); } else { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; } } void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const { rescaleKeyAxis(onlyEnlarge); rescaleValueAxis(onlyEnlarge); } void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const { QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } bool foundRange; QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth); if (foundRange) { if (onlyEnlarge) newRange.expand(keyAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason newRange.lower = center-keyAxis->range().size()/2.0; newRange.upper = center+keyAxis->range().size()/2.0; } keyAxis->setRange(newRange); } } void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const { QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); QCPPolarAxisRadial *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QCP::SignDomain signDomain = QCP::sdBoth; if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); if (foundRange) { if (onlyEnlarge) newRange.expand(valueAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear) { newRange.lower = center-valueAxis->range().size()/2.0; newRange.upper = center+valueAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); } } valueAxis->setRange(newRange); } } bool QCPPolarGraph::addToLegend(QCPLegend *legend) { if (!legend) { qDebug() << Q_FUNC_INFO << "passed legend is null"; return false; } if (legend->parentPlot() != mParentPlot) { qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; return false; } //if (!legend->hasItemWithPlottable(this)) // TODO //{ legend->addItem(new QCPPolarLegendItem(legend, this)); return true; //} else // return false; } bool QCPPolarGraph::addToLegend() { if (!mParentPlot || !mParentPlot->legend) return false; else return addToLegend(mParentPlot->legend); } bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const { if (!legend) { qDebug() << Q_FUNC_INFO << "passed legend is null"; return false; } QCPPolarLegendItem *removableItem = 0; for (int i=0; iitemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified { if (QCPPolarLegendItem *pli = qobject_cast(legend->item(i))) { if (pli->polarGraph() == this) { removableItem = pli; break; } } } if (removableItem) return legend->removeItem(removableItem); else return false; } bool QCPPolarGraph::removeFromLegend() const { if (!mParentPlot || !mParentPlot->legend) return false; else return removeFromLegend(mParentPlot->legend); } double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; if (mKeyAxis->rect().contains(pos.toPoint())) { QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); double result = pointDistance(pos, closestDataPoint); if (details) { int pointIndex = closestDataPoint-mDataContainer->constBegin(); details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); } return result; } else return -1; } /* inherits documentation from base class */ QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { return mDataContainer->keyRange(foundRange, inSignDomain); } /* inherits documentation from base class */ QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ QRect QCPPolarGraph::clipRect() const { if (mKeyAxis) return mKeyAxis.data()->rect(); else return QRect(); } void QCPPolarGraph::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return; if (mLineStyle == lsNone && mScatterStyle.isNone()) return; painter->setClipRegion(mKeyAxis->exactClipRegion()); QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments // loop over and draw segments of unselected/selected data: QList selectedSegments, unselectedSegments, allSegments; getDataSegments(selectedSegments, unselectedSegments); allSegments << unselectedSegments << selectedSegments; for (int i=0; i= unselectedSegments.size(); // get line pixel points appropriate to line style: QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care) getLines(&lines, lineDataRange); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPGraphDataContainer::const_iterator it; for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) { if (QCP::isInvalidData(it->key, it->value)) qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); } #endif // draw fill of graph: //if (isSelectedSegment && mSelectionDecorator) // mSelectionDecorator->applyBrush(painter); //else painter->setBrush(mBrush); painter->setPen(Qt::NoPen); drawFill(painter, &lines); // draw line: if (mLineStyle != lsNone) { //if (isSelectedSegment && mSelectionDecorator) // mSelectionDecorator->applyPen(painter); //else painter->setPen(mPen); painter->setBrush(Qt::NoBrush); drawLinePlot(painter, lines); } // draw scatters: QCPScatterStyle finalScatterStyle = mScatterStyle; //if (isSelectedSegment && mSelectionDecorator) // finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); if (!finalScatterStyle.isNone()) { getScatters(&scatters, allSegments.at(i)); drawScatterPlot(painter, scatters, finalScatterStyle); } } // draw other selection decoration that isn't just line/scatter pens and brushes: //if (mSelectionDecorator) // mSelectionDecorator->drawDecoration(painter, selection()); } QCP::Interaction QCPPolarGraph::selectionCategory() const { return QCP::iSelectPlottables; } void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /* inherits documentation from base class */ void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) if (mSelectable != QCP::stNone) { QCPDataSelection newSelection = details.value(); QCPDataSelection selectionBefore = mSelection; if (additive) { if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit { if (selected()) setSelection(QCPDataSelection()); else setSelection(newSelection); } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments { if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection setSelection(mSelection-newSelection); else setSelection(mSelection+newSelection); } } else setSelection(newSelection); if (selectionStateChanged) *selectionStateChanged = mSelection != selectionBefore; } } /* inherits documentation from base class */ void QCPPolarGraph::deselectEvent(bool *selectionStateChanged) { if (mSelectable != QCP::stNone) { QCPDataSelection selectionBefore = mSelection; setSelection(QCPDataSelection()); if (selectionStateChanged) *selectionStateChanged = mSelection != selectionBefore; } } /*! \internal Draws lines between the points in \a lines, given in pixel coordinates. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline */ void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector &lines) const { if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); drawPolyline(painter, lines); } } /*! \internal Draws the fill of the graph using the specified \a painter, with the currently set brush. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas), this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN segments of the two involved graphs, before passing the overlapping pairs to \ref getChannelFillPolygon. Pass the points of this graph's line as \a lines, in pixel coordinates. \see drawLinePlot, drawImpulsePlot, drawScatterPlot */ void QCPPolarGraph::drawFill(QCPPainter *painter, QVector *lines) const { applyFillAntialiasingHint(painter); if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) painter->drawPolygon(QPolygonF(*lines)); } /*! \internal Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The scatters will be drawn with \a painter and have the appearance as specified in \a style. \see drawLinePlot, drawImpulsePlot */ void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const { applyScattersAntialiasingHint(painter); style.applyTo(painter, mPen); for (int i=0; ifillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const { closestData = mDataContainer->constEnd(); if (mDataContainer->isEmpty()) return -1.0; if (mLineStyle == lsNone && mScatterStyle.isNone()) return -1.0; // calculate minimum distances to graph data points and find closestData iterator: double minDistSqr = (std::numeric_limits::max)(); // determine which key range comes into question, taking selection tolerance around pos into account: double posKeyMin, posKeyMax, dummy; pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy); pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy); if (posKeyMin > posKeyMax) qSwap(posKeyMin, posKeyMax); // iterate over found data points and then choose the one with the shortest distance to pos: QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true); QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true); for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it) { const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; closestData = it; } } // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): if (mLineStyle != lsNone) { // line displayed, calculate distance to line segments: QVector lineData; getLines(&lineData, QCPDataRange(0, dataCount())); QCPVector2D p(pixelPoint); for (int i=0; isize(); } void QCPPolarGraph::getDataSegments(QList &selectedSegments, QList &unselectedSegments) const { selectedSegments.clear(); unselectedSegments.clear(); if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty { if (selected()) selectedSegments << QCPDataRange(0, dataCount()); else unselectedSegments << QCPDataRange(0, dataCount()); } else { QCPDataSelection sel(selection()); sel.simplify(); selectedSegments = sel.dataRanges(); unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges(); } } void QCPPolarGraph::drawPolyline(QCPPainter *painter, const QVector &lineData) const { // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { int i = 0; bool lastIsNan = false; const int lineDataSize = lineData.size(); while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN ++i; ++i; // because drawing works in 1 point retrospect while (i < lineDataSize) { if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line { if (!lastIsNan) painter->drawLine(lineData.at(i-1), lineData.at(i)); else lastIsNan = false; } else lastIsNan = true; ++i; } } else { int segmentStart = 0; int i = 0; const int lineDataSize = lineData.size(); while (i < lineDataSize) { if (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()) || qIsInf(lineData.at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block { painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point segmentStart = i+1; } ++i; } // draw last segment: painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart); } } void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const { if (rangeRestriction.isEmpty()) { end = mDataContainer->constEnd(); begin = end; } else { QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); QCPPolarAxisRadial *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // get visible data range: if (mPeriodic) { begin = mDataContainer->constBegin(); end = mDataContainer->constEnd(); } else { begin = mDataContainer->findBegin(keyAxis->range().lower); end = mDataContainer->findEnd(keyAxis->range().upper); } // limit lower/upperEnd to rangeRestriction: mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything } } /*! \internal This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc. according to the line style of the graph. \a lines will be filled with points in pixel coordinates, that can be drawn with the according draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines aren't necessarily the original data points. For example, step line styles require additional points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a lines vector will be empty. \a dataRange specifies the beginning and ending data indices that will be taken into account for conversion. In this function, the specified range may exceed the total data bounds without harm: a correspondingly trimmed data range will be used. This takes the burden off the user of this function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref getDataSegments. \see getScatters */ void QCPPolarGraph::getLines(QVector *lines, const QCPDataRange &dataRange) const { if (!lines) return; QCPGraphDataContainer::const_iterator begin, end; getVisibleDataBounds(begin, end, dataRange); if (begin == end) { lines->clear(); return; } QVector lineData; if (mLineStyle != lsNone) getOptimizedLineData(&lineData, begin, end); switch (mLineStyle) { case lsNone: lines->clear(); break; case lsLine: *lines = dataToLines(lineData); break; } } void QCPPolarGraph::getScatters(QVector *scatters, const QCPDataRange &dataRange) const { QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); QCPPolarAxisRadial *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!scatters) return; QCPGraphDataContainer::const_iterator begin, end; getVisibleDataBounds(begin, end, dataRange); if (begin == end) { scatters->clear(); return; } QVector data; getOptimizedScatterData(&data, begin, end); scatters->resize(data.size()); for (int i=0; icoordToPixel(data.at(i).key, data.at(i).value); } } void QCPPolarGraph::getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const { lineData->clear(); // TODO: fix for log axes and thick line style const QCPRange range = mValueAxis->range(); bool reversed = mValueAxis->rangeReversed(); const double clipMargin = range.size()*0.05; // extra distance from visible circle, so optimized outside lines can cover more angle before having to place a dummy point to prevent tangents const double upperClipValue = range.upper + (reversed ? 0 : range.size()*0.05+clipMargin); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle const double lowerClipValue = range.lower - (reversed ? range.size()*0.05+clipMargin : 0); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle const double maxKeySkip = qAsin(qSqrt(clipMargin*(clipMargin+2*range.size()))/(range.size()+clipMargin))/M_PI*mKeyAxis->range().size(); // the maximum angle between two points on outer circle (r=clipValue+clipMargin) before connecting line becomes tangent to inner circle (r=clipValue) double skipBegin = 0; bool belowRange = false; bool aboveRange = false; QCPGraphDataContainer::const_iterator it = begin; while (it != end) { if (it->value < lowerClipValue) { if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct { aboveRange = false; if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point lineData->append(*(it-1)); } if (!belowRange) { skipBegin = it->key; lineData->append(QCPGraphData(it->key, lowerClipValue)); belowRange = true; } if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle) { skipBegin += maxKeySkip; lineData->append(QCPGraphData(skipBegin, lowerClipValue)); } } else if (it->value > upperClipValue) { if (belowRange) // jumped directly from below to above visible range, draw previous point so entry angle is correct (if lower means outer, so if reversed axis) { belowRange = false; if (reversed) lineData->append(*(it-1)); } if (!aboveRange) { skipBegin = it->key; lineData->append(QCPGraphData(it->key, upperClipValue)); aboveRange = true; } if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle) { skipBegin += maxKeySkip; lineData->append(QCPGraphData(skipBegin, upperClipValue)); } } else // value within bounds where we don't optimize away points { if (aboveRange) { aboveRange = false; if (!reversed) lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis) } if (belowRange) { belowRange = false; if (reversed) lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis) } lineData->append(*it); // inside visible circle, add point normally } ++it; } // to make fill not erratic, add last point normally if it was outside visible circle: if (aboveRange) { aboveRange = false; if (!reversed) lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis) } if (belowRange) { belowRange = false; if (reversed) lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis) } } void QCPPolarGraph::getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const { scatterData->clear(); const QCPRange range = mValueAxis->range(); bool reversed = mValueAxis->rangeReversed(); const double clipMargin = range.size()*0.05; const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle QCPGraphDataContainer::const_iterator it = begin; while (it != end) { if (it->value > lowerClipValue && it->value < upperClipValue) scatterData->append(*it); ++it; } } /*! \internal Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel coordinate points which are suitable for drawing the line style \ref lsLine. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot */ QVector QCPPolarGraph::dataToLines(const QVector &data) const { QVector result; QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); QCPPolarAxisRadial *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } // transform data points to pixels: result.resize(data.size()); for (int i=0; icoordToPixel(data.at(i).key, data.at(i).value); return result; } /* end of 'src/polar/polargraph.cpp' */ THELI-3.1.3/src/qcustomplot.h000066400000000000000000011333451417631501300157300ustar00rootroot00000000000000/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2021 Emanuel Eichhammer ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License for more details. ** ** ** ** You should have received a copy of the GNU General Public License ** ** along with this program. If not, see http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 29.03.21 ** ** Version: 2.1.0 ** ****************************************************************************/ #ifndef QCUSTOMPLOT_H #define QCUSTOMPLOT_H #include // some Qt version/configuration dependent macros to include or exclude certain code paths: #ifdef QCUSTOMPLOT_USE_OPENGL # if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) # define QCP_OPENGL_PBUFFER # else # define QCP_OPENGL_FBO # endif # if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0) # define QCP_OPENGL_OFFSCREENSURFACE # endif #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) # define QCP_DEVICEPIXELRATIO_SUPPORTED # if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) # define QCP_DEVICEPIXELRATIO_FLOAT # endif #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef QCP_OPENGL_FBO # include # if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) # include # else # include # include # endif # ifdef QCP_OPENGL_OFFSCREENSURFACE # include # else # include # endif #endif #ifdef QCP_OPENGL_PBUFFER # include #endif #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) # include # include # include # include #else # include # include # include #endif #if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0) # include #endif # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) # include #endif class QCPPainter; class QCustomPlot; class QCPLayerable; class QCPLayoutElement; class QCPLayout; class QCPAxis; class QCPAxisRect; class QCPAxisPainterPrivate; class QCPAbstractPlottable; class QCPGraph; class QCPAbstractItem; class QCPPlottableInterface1D; class QCPLegend; class QCPItemPosition; class QCPLayer; class QCPAbstractLegendItem; class QCPSelectionRect; class QCPColorMap; class QCPColorScale; class QCPBars; class QCPPolarAxisRadial; class QCPPolarAxisAngular; class QCPPolarGrid; class QCPPolarGraph; /* including file 'src/global.h' */ /* modified 2021-03-29T02:30:44, size 16981 */ #define QCUSTOMPLOT_VERSION_STR "2.1.0" #define QCUSTOMPLOT_VERSION 0x020100 // decl definitions for shared library compilation/usage: #if defined(QT_STATIC_BUILD) # define QCP_LIB_DECL #elif defined(QCUSTOMPLOT_COMPILE_LIBRARY) # define QCP_LIB_DECL Q_DECL_EXPORT #elif defined(QCUSTOMPLOT_USE_LIBRARY) # define QCP_LIB_DECL Q_DECL_IMPORT #else # define QCP_LIB_DECL #endif // define empty macro for Q_DECL_OVERRIDE if it doesn't exist (Qt < 5) #ifndef Q_DECL_OVERRIDE # define Q_DECL_OVERRIDE #endif /*! The QCP Namespace contains general enums, QFlags and functions used throughout the QCustomPlot library. It provides QMetaObject-based reflection of its enums and flags via \a QCP::staticMetaObject. */ #ifndef Q_MOC_RUN namespace QCP { #else class QCP { // when in moc-run, make it look like a class, so we get Q_GADGET, Q_ENUMS/Q_FLAGS features in namespace Q_GADGET Q_ENUMS(ExportPen) Q_ENUMS(ResolutionUnit) Q_ENUMS(SignDomain) Q_ENUMS(MarginSide) Q_FLAGS(MarginSides) Q_ENUMS(AntialiasedElement) Q_FLAGS(AntialiasedElements) Q_ENUMS(PlottingHint) Q_FLAGS(PlottingHints) Q_ENUMS(Interaction) Q_FLAGS(Interactions) Q_ENUMS(SelectionRectMode) Q_ENUMS(SelectionType) public: #endif /*! Defines the different units in which the image resolution can be specified in the export functions. \see QCustomPlot::savePng, QCustomPlot::saveJpg, QCustomPlot::saveBmp, QCustomPlot::saveRastered */ enum ResolutionUnit { ruDotsPerMeter ///< Resolution is given in dots per meter (dpm) ,ruDotsPerCentimeter ///< Resolution is given in dots per centimeter (dpcm) ,ruDotsPerInch ///< Resolution is given in dots per inch (DPI/PPI) }; /*! Defines how cosmetic pens (pens with numerical width 0) are handled during export. \see QCustomPlot::savePdf */ enum ExportPen { epNoCosmetic ///< Cosmetic pens are converted to pens with pixel width 1 when exporting ,epAllowCosmetic ///< Cosmetic pens are exported normally (e.g. in PDF exports, cosmetic pens always appear as 1 pixel on screen, independent of viewer zoom level) }; /*! Represents negative and positive sign domain, e.g. for passing to \ref QCPAbstractPlottable::getKeyRange and \ref QCPAbstractPlottable::getValueRange. This is primarily needed when working with logarithmic axis scales, since only one of the sign domains can be visible at a time. */ enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero ,sdBoth ///< Both sign domains, including zero, i.e. all numbers ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero }; /*! Defines the sides of a rectangular entity to which margins can be applied. \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< 0x01 left margin ,msRight = 0x02 ///< 0x02 right margin ,msTop = 0x04 ///< 0x04 top margin ,msBottom = 0x08 ///< 0x08 bottom margin ,msAll = 0xFF ///< 0xFF all margins ,msNone = 0x00 ///< 0x00 no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) /*! Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective element how it is drawn. Typically it provides a \a setAntialiased function for this. \c AntialiasedElements is a flag of or-combined elements of this enum type. \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks ,aeGrid = 0x0002 ///< 0x0002 Grid lines ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines ,aeLegend = 0x0008 ///< 0x0008 Legend box ,aeLegendItems = 0x0010 ///< 0x0010 Legend items ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables ,aeItems = 0x0040 ///< 0x0040 Main lines of items ,aeScatters = 0x0080 ///< 0x0080 Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) ,aeFills = 0x0100 ///< 0x0100 Borders of fills (e.g. under or between graphs) ,aeZeroLine = 0x0200 ///< 0x0200 Zero-lines, see \ref QCPGrid::setZeroLinePen ,aeOther = 0x8000 ///< 0x8000 Other elements that don't fit into any of the existing categories ,aeAll = 0xFFFF ///< 0xFFFF All elements ,aeNone = 0x0000 ///< 0x0000 No elements }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! Defines plotting hints that control various aspects of the quality and speed of plotting. \see QCustomPlot::setPlottingHints */ enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality especially of the line segment ///< joins, thus is most effective for pen sizes larger than 1. It is only used for solid line pens. ,phImmediateRefresh = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpRefreshHint. ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. }; Q_DECLARE_FLAGS(PlottingHints, PlottingHint) /*! Defines the mouse interactions possible with QCustomPlot. \c Interactions is a flag of or-combined elements of this enum type. \see QCustomPlot::setInteractions */ enum Interaction { iNone = 0x000 ///< 0x000 None of the interactions are possible ,iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) ,iSelectAxes = 0x010 ///< 0x010 Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) ,iSelectLegend = 0x020 ///< 0x020 Legends are selectable (or their child items, see QCPLegend::setSelectableParts) ,iSelectItems = 0x040 ///< 0x040 Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, other layout elements,...) ,iSelectPlottablesBeyondAxisRect = 0x100 ///< 0x100 When performing plottable selection/hit tests, this flag extends the sensitive area beyond the axis rect }; Q_DECLARE_FLAGS(Interactions, Interaction) /*! Defines the behaviour of the selection rect. \see QCustomPlot::setSelectionRectMode, QCustomPlot::selectionRect, QCPSelectionRect */ enum SelectionRectMode { srmNone ///< The selection rect is disabled, and all mouse events are forwarded to the underlying objects, e.g. for axis range dragging ,srmZoom ///< When dragging the mouse, a selection rect becomes active. Upon releasing, the axes that are currently set as range zoom axes (\ref QCPAxisRect::setRangeZoomAxes) will have their ranges zoomed accordingly. ,srmSelect ///< When dragging the mouse, a selection rect becomes active. Upon releasing, plottable data points that were within the selection rect are selected, if the plottable's selectability setting permits. (See \ref dataselection "data selection mechanism" for details.) ,srmCustom ///< When dragging the mouse, a selection rect becomes active. It is the programmer's responsibility to connect according slots to the selection rect's signals (e.g. \ref QCPSelectionRect::accepted) in order to process the user interaction. }; /*! Defines the different ways a plottable can be selected. These images show the effect of the different selection types, when the indicated selection rect was dragged:
\image html selectiontype-none.png stNone \image html selectiontype-whole.png stWhole \image html selectiontype-singledata.png stSingleData \image html selectiontype-datarange.png stDataRange \image html selectiontype-multipledataranges.png stMultipleDataRanges
\see QCPAbstractPlottable::setSelectable, QCPDataSelection::enforceType */ enum SelectionType { stNone ///< The plottable is not selectable ,stWhole ///< Selection behaves like \ref stMultipleDataRanges, but if there are any data points selected, the entire plottable is drawn as selected. ,stSingleData ///< One individual data point can be selected at a time ,stDataRange ///< Multiple contiguous data points (a data range) can be selected ,stMultipleDataRanges ///< Any combination of data points/ranges can be selected }; /*! \internal Returns whether the specified \a value is considered an invalid data value for plottables (i.e. is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ inline bool isInvalidData(double value) { return qIsNaN(value) || qIsInf(value); } /*! \internal \overload Checks two arguments instead of one. */ inline bool isInvalidData(double value1, double value2) { return isInvalidData(value1) || isInvalidData(value2); } /*! \internal Sets the specified \a side of \a margins to \a value \see getMarginValue */ inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { switch (side) { case QCP::msLeft: margins.setLeft(value); break; case QCP::msRight: margins.setRight(value); break; case QCP::msTop: margins.setTop(value); break; case QCP::msBottom: margins.setBottom(value); break; case QCP::msAll: margins = QMargins(value, value, value, value); break; default: break; } } /*! \internal Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or \ref QCP::msAll, returns 0. \see setMarginValue */ inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { switch (side) { case QCP::msLeft: return margins.left(); case QCP::msRight: return margins.right(); case QCP::msTop: return margins.top(); case QCP::msBottom: return margins.bottom(); default: break; } return 0; } extern const QMetaObject staticMetaObject; // in moc-run we create a static meta object for QCP "fake" object. This line is the link to it via QCP::staticMetaObject in normal operation as namespace } // end of namespace QCP Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) Q_DECLARE_METATYPE(QCP::ExportPen) Q_DECLARE_METATYPE(QCP::ResolutionUnit) Q_DECLARE_METATYPE(QCP::SignDomain) Q_DECLARE_METATYPE(QCP::MarginSide) Q_DECLARE_METATYPE(QCP::AntialiasedElement) Q_DECLARE_METATYPE(QCP::PlottingHint) Q_DECLARE_METATYPE(QCP::Interaction) Q_DECLARE_METATYPE(QCP::SelectionRectMode) Q_DECLARE_METATYPE(QCP::SelectionType) /* end of 'src/global.h' */ /* including file 'src/vector2d.h' */ /* modified 2021-03-29T02:30:44, size 4988 */ class QCP_LIB_DECL QCPVector2D { public: QCPVector2D(); QCPVector2D(double x, double y); QCPVector2D(const QPoint &point); QCPVector2D(const QPointF &point); // getters: double x() const { return mX; } double y() const { return mY; } double &rx() { return mX; } double &ry() { return mY; } // setters: void setX(double x) { mX = x; } void setY(double y) { mY = y; } // non-virtual methods: double length() const { return qSqrt(mX*mX+mY*mY); } double lengthSquared() const { return mX*mX+mY*mY; } double angle() const { return qAtan2(mY, mX); } QPoint toPoint() const { return QPoint(int(mX), int(mY)); } QPointF toPointF() const { return QPointF(mX, mY); } bool isNull() const { return qIsNull(mX) && qIsNull(mY); } void normalize(); QCPVector2D normalized() const; QCPVector2D perpendicular() const { return QCPVector2D(-mY, mX); } double dot(const QCPVector2D &vec) const { return mX*vec.mX+mY*vec.mY; } double distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const; double distanceSquaredToLine(const QLineF &line) const; double distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const; QCPVector2D &operator*=(double factor); QCPVector2D &operator/=(double divisor); QCPVector2D &operator+=(const QCPVector2D &vector); QCPVector2D &operator-=(const QCPVector2D &vector); private: // property members: double mX, mY; friend inline const QCPVector2D operator*(double factor, const QCPVector2D &vec); friend inline const QCPVector2D operator*(const QCPVector2D &vec, double factor); friend inline const QCPVector2D operator/(const QCPVector2D &vec, double divisor); friend inline const QCPVector2D operator+(const QCPVector2D &vec1, const QCPVector2D &vec2); friend inline const QCPVector2D operator-(const QCPVector2D &vec1, const QCPVector2D &vec2); friend inline const QCPVector2D operator-(const QCPVector2D &vec); }; Q_DECLARE_TYPEINFO(QCPVector2D, Q_MOVABLE_TYPE); inline const QCPVector2D operator*(double factor, const QCPVector2D &vec) { return QCPVector2D(vec.mX*factor, vec.mY*factor); } inline const QCPVector2D operator*(const QCPVector2D &vec, double factor) { return QCPVector2D(vec.mX*factor, vec.mY*factor); } inline const QCPVector2D operator/(const QCPVector2D &vec, double divisor) { return QCPVector2D(vec.mX/divisor, vec.mY/divisor); } inline const QCPVector2D operator+(const QCPVector2D &vec1, const QCPVector2D &vec2) { return QCPVector2D(vec1.mX+vec2.mX, vec1.mY+vec2.mY); } inline const QCPVector2D operator-(const QCPVector2D &vec1, const QCPVector2D &vec2) { return QCPVector2D(vec1.mX-vec2.mX, vec1.mY-vec2.mY); } inline const QCPVector2D operator-(const QCPVector2D &vec) { return QCPVector2D(-vec.mX, -vec.mY); } /*! \relates QCPVector2D Prints \a vec in a human readable format to the qDebug output. */ inline QDebug operator<< (QDebug d, const QCPVector2D &vec) { d.nospace() << "QCPVector2D(" << vec.x() << ", " << vec.y() << ")"; return d.space(); } /* end of 'src/vector2d.h' */ /* including file 'src/painter.h' */ /* modified 2021-03-29T02:30:44, size 4035 */ class QCP_LIB_DECL QCPPainter : public QPainter { Q_GADGET public: /*! Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, depending on whether they are wanted on the respective output device. */ enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. ,pmNoCaching = 0x02 ///< 0x02 Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels ,pmNonCosmetic = 0x04 ///< 0x04 Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) }; Q_ENUMS(PainterMode) Q_FLAGS(PainterModes) Q_DECLARE_FLAGS(PainterModes, PainterMode) QCPPainter(); explicit QCPPainter(QPaintDevice *device); // getters: bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } PainterModes modes() const { return mModes; } // setters: void setAntialiasing(bool enabled); void setMode(PainterMode mode, bool enabled=true); void setModes(PainterModes modes); // methods hiding non-virtual base class functions (QPainter bug workarounds): bool begin(QPaintDevice *device); void setPen(const QPen &pen); void setPen(const QColor &color); void setPen(Qt::PenStyle penStyle); void drawLine(const QLineF &line); void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} void save(); void restore(); // non-virtual methods: void makeNonCosmetic(); protected: // property members: PainterModes mModes; bool mIsAntialiasing; // non-property members: QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) Q_DECLARE_METATYPE(QCPPainter::PainterMode) /* end of 'src/painter.h' */ /* including file 'src/paintbuffer.h' */ /* modified 2021-03-29T02:30:44, size 5006 */ class QCP_LIB_DECL QCPAbstractPaintBuffer { public: explicit QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio); virtual ~QCPAbstractPaintBuffer(); // getters: QSize size() const { return mSize; } bool invalidated() const { return mInvalidated; } double devicePixelRatio() const { return mDevicePixelRatio; } // setters: void setSize(const QSize &size); void setInvalidated(bool invalidated=true); void setDevicePixelRatio(double ratio); // introduced virtual methods: virtual QCPPainter *startPainting() = 0; virtual void donePainting() {} virtual void draw(QCPPainter *painter) const = 0; virtual void clear(const QColor &color) = 0; protected: // property members: QSize mSize; double mDevicePixelRatio; // non-property members: bool mInvalidated; // introduced virtual methods: virtual void reallocateBuffer() = 0; }; class QCP_LIB_DECL QCPPaintBufferPixmap : public QCPAbstractPaintBuffer { public: explicit QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio); virtual ~QCPPaintBufferPixmap() Q_DECL_OVERRIDE; // reimplemented virtual methods: virtual QCPPainter *startPainting() Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE; void clear(const QColor &color) Q_DECL_OVERRIDE; protected: // non-property members: QPixmap mBuffer; // reimplemented virtual methods: virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #ifdef QCP_OPENGL_PBUFFER class QCP_LIB_DECL QCPPaintBufferGlPbuffer : public QCPAbstractPaintBuffer { public: explicit QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples); virtual ~QCPPaintBufferGlPbuffer() Q_DECL_OVERRIDE; // reimplemented virtual methods: virtual QCPPainter *startPainting() Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE; void clear(const QColor &color) Q_DECL_OVERRIDE; protected: // non-property members: QGLPixelBuffer *mGlPBuffer; int mMultisamples; // reimplemented virtual methods: virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_PBUFFER #ifdef QCP_OPENGL_FBO class QCP_LIB_DECL QCPPaintBufferGlFbo : public QCPAbstractPaintBuffer { public: explicit QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice); virtual ~QCPPaintBufferGlFbo() Q_DECL_OVERRIDE; // reimplemented virtual methods: virtual QCPPainter *startPainting() Q_DECL_OVERRIDE; virtual void donePainting() Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE; void clear(const QColor &color) Q_DECL_OVERRIDE; protected: // non-property members: QWeakPointer mGlContext; QWeakPointer mGlPaintDevice; QOpenGLFramebufferObject *mGlFrameBuffer; // reimplemented virtual methods: virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_FBO /* end of 'src/paintbuffer.h' */ /* including file 'src/layer.h' */ /* modified 2021-03-29T02:30:44, size 7038 */ class QCP_LIB_DECL QCPLayer : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QString name READ name) Q_PROPERTY(int index READ index) Q_PROPERTY(QList children READ children) Q_PROPERTY(bool visible READ visible WRITE setVisible) Q_PROPERTY(LayerMode mode READ mode WRITE setMode) /// \endcond public: /*! Defines the different rendering modes of a layer. Depending on the mode, certain layers can be replotted individually, without the need to replot (possibly complex) layerables on other layers. \see setMode */ enum LayerMode { lmLogical ///< Layer is used only for rendering order, and shares paint buffer with all other adjacent logical layers. ,lmBuffered ///< Layer has its own paint buffer and may be replotted individually (see \ref replot). }; Q_ENUMS(LayerMode) QCPLayer(QCustomPlot* parentPlot, const QString &layerName); virtual ~QCPLayer(); // getters: QCustomPlot *parentPlot() const { return mParentPlot; } QString name() const { return mName; } int index() const { return mIndex; } QList children() const { return mChildren; } bool visible() const { return mVisible; } LayerMode mode() const { return mMode; } // setters: void setVisible(bool visible); void setMode(LayerMode mode); // non-virtual methods: void replot(); protected: // property members: QCustomPlot *mParentPlot; QString mName; int mIndex; QList mChildren; bool mVisible; LayerMode mMode; // non-property members: QWeakPointer mPaintBuffer; // non-virtual methods: void draw(QCPPainter *painter); void drawToPaintBuffer(); void addChild(QCPLayerable *layerable, bool prepend); void removeChild(QCPLayerable *layerable); private: Q_DISABLE_COPY(QCPLayer) friend class QCustomPlot; friend class QCPLayerable; }; Q_DECLARE_METATYPE(QCPLayer::LayerMode) class QCP_LIB_DECL QCPLayerable : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) /// \endcond public: QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=nullptr); virtual ~QCPLayerable(); // getters: bool visible() const { return mVisible; } QCustomPlot *parentPlot() const { return mParentPlot; } QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } QCPLayer *layer() const { return mLayer; } bool antialiased() const { return mAntialiased; } // setters: void setVisible(bool on); Q_SLOT bool setLayer(QCPLayer *layer); bool setLayer(const QString &layerName); void setAntialiased(bool enabled); // introduced virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const; // non-property methods: bool realVisibility() const; signals: void layerChanged(QCPLayer *newLayer); protected: // property members: bool mVisible; QCustomPlot *mParentPlot; QPointer mParentLayerable; QCPLayer *mLayer; bool mAntialiased; // introduced virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot); virtual QCP::Interaction selectionCategory() const; virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; virtual void draw(QCPPainter *painter) = 0; // selection events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // low-level mouse events: virtual void mousePressEvent(QMouseEvent *event, const QVariant &details); virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos); virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos); virtual void mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details); virtual void wheelEvent(QWheelEvent *event); // non-property methods: void initializeParentPlot(QCustomPlot *parentPlot); void setParentLayerable(QCPLayerable* parentLayerable); bool moveToLayer(QCPLayer *layer, bool prepend); void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; private: Q_DISABLE_COPY(QCPLayerable) friend class QCustomPlot; friend class QCPLayer; friend class QCPAxisRect; }; /* end of 'src/layer.h' */ /* including file 'src/axis/range.h' */ /* modified 2021-03-29T02:30:44, size 5280 */ class QCP_LIB_DECL QCPRange { public: double lower, upper; QCPRange(); QCPRange(double lower, double upper); bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } bool operator!=(const QCPRange& other) const { return !(*this == other); } QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } friend inline const QCPRange operator+(const QCPRange&, double); friend inline const QCPRange operator+(double, const QCPRange&); friend inline const QCPRange operator-(const QCPRange& range, double value); friend inline const QCPRange operator*(const QCPRange& range, double value); friend inline const QCPRange operator*(double value, const QCPRange& range); friend inline const QCPRange operator/(const QCPRange& range, double value); double size() const { return upper-lower; } double center() const { return (upper+lower)*0.5; } void normalize() { if (lower > upper) qSwap(lower, upper); } void expand(const QCPRange &otherRange); void expand(double includeCoord); QCPRange expanded(const QCPRange &otherRange) const; QCPRange expanded(double includeCoord) const; QCPRange bounded(double lowerBound, double upperBound) const; QCPRange sanitizedForLogScale() const; QCPRange sanitizedForLinScale() const; bool contains(double value) const { return value >= lower && value <= upper; } static bool validRange(double lower, double upper); static bool validRange(const QCPRange &range); static const double minRange; static const double maxRange; }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); /*! \relates QCPRange Prints \a range in a human readable format to the qDebug output. */ inline QDebug operator<< (QDebug d, const QCPRange &range) { d.nospace() << "QCPRange(" << range.lower << ", " << range.upper << ")"; return d.space(); } /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(const QCPRange& range, double value) { QCPRange result(range); result += value; return result; } /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(double value, const QCPRange& range) { QCPRange result(range); result += value; return result; } /*! Subtracts \a value from both boundaries of the range. */ inline const QCPRange operator-(const QCPRange& range, double value) { QCPRange result(range); result -= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(const QCPRange& range, double value) { QCPRange result(range); result *= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(double value, const QCPRange& range) { QCPRange result(range); result *= value; return result; } /*! Divides both boundaries of the range by \a value. */ inline const QCPRange operator/(const QCPRange& range, double value) { QCPRange result(range); result /= value; return result; } /* end of 'src/axis/range.h' */ /* including file 'src/selection.h' */ /* modified 2021-03-29T02:30:44, size 8569 */ class QCP_LIB_DECL QCPDataRange { public: QCPDataRange(); QCPDataRange(int begin, int end); bool operator==(const QCPDataRange& other) const { return mBegin == other.mBegin && mEnd == other.mEnd; } bool operator!=(const QCPDataRange& other) const { return !(*this == other); } // getters: int begin() const { return mBegin; } int end() const { return mEnd; } int size() const { return mEnd-mBegin; } int length() const { return size(); } // setters: void setBegin(int begin) { mBegin = begin; } void setEnd(int end) { mEnd = end; } // non-property methods: bool isValid() const { return (mEnd >= mBegin) && (mBegin >= 0); } bool isEmpty() const { return length() == 0; } QCPDataRange bounded(const QCPDataRange &other) const; QCPDataRange expanded(const QCPDataRange &other) const; QCPDataRange intersection(const QCPDataRange &other) const; QCPDataRange adjusted(int changeBegin, int changeEnd) const { return QCPDataRange(mBegin+changeBegin, mEnd+changeEnd); } bool intersects(const QCPDataRange &other) const; bool contains(const QCPDataRange &other) const; private: // property members: int mBegin, mEnd; }; Q_DECLARE_TYPEINFO(QCPDataRange, Q_MOVABLE_TYPE); class QCP_LIB_DECL QCPDataSelection { public: explicit QCPDataSelection(); explicit QCPDataSelection(const QCPDataRange &range); bool operator==(const QCPDataSelection& other) const; bool operator!=(const QCPDataSelection& other) const { return !(*this == other); } QCPDataSelection &operator+=(const QCPDataSelection& other); QCPDataSelection &operator+=(const QCPDataRange& other); QCPDataSelection &operator-=(const QCPDataSelection& other); QCPDataSelection &operator-=(const QCPDataRange& other); friend inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataSelection& b); friend inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataSelection& b); friend inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataRange& b); friend inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataRange& b); friend inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataSelection& b); friend inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataSelection& b); friend inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataRange& b); friend inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRange& b); // getters: int dataRangeCount() const { return mDataRanges.size(); } int dataPointCount() const; QCPDataRange dataRange(int index=0) const; QList dataRanges() const { return mDataRanges; } QCPDataRange span() const; // non-property methods: void addDataRange(const QCPDataRange &dataRange, bool simplify=true); void clear(); bool isEmpty() const { return mDataRanges.isEmpty(); } void simplify(); void enforceType(QCP::SelectionType type); bool contains(const QCPDataSelection &other) const; QCPDataSelection intersection(const QCPDataRange &other) const; QCPDataSelection intersection(const QCPDataSelection &other) const; QCPDataSelection inverse(const QCPDataRange &outerRange) const; private: // property members: QList mDataRanges; inline static bool lessThanDataRangeBegin(const QCPDataRange &a, const QCPDataRange &b) { return a.begin() < b.begin(); } }; Q_DECLARE_METATYPE(QCPDataSelection) /*! Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). */ inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataSelection& b) { QCPDataSelection result(a); result += b; return result; } /*! Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). */ inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataSelection& b) { QCPDataSelection result(a); result += b; return result; } /*! Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). */ inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataRange& b) { QCPDataSelection result(a); result += b; return result; } /*! Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). */ inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataRange& b) { QCPDataSelection result(a); result += b; return result; } /*! Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. */ inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataSelection& b) { QCPDataSelection result(a); result -= b; return result; } /*! Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. */ inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataSelection& b) { QCPDataSelection result(a); result -= b; return result; } /*! Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. */ inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataRange& b) { QCPDataSelection result(a); result -= b; return result; } /*! Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. */ inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRange& b) { QCPDataSelection result(a); result -= b; return result; } /*! \relates QCPDataRange Prints \a dataRange in a human readable format to the qDebug output. */ inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) { d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")"; return d; } /*! \relates QCPDataSelection Prints \a selection in a human readable format to the qDebug output. */ inline QDebug operator<< (QDebug d, const QCPDataSelection &selection) { d.nospace() << "QCPDataSelection("; for (int i=0; i elements(QCP::MarginSide side) const { return mChildren.value(side); } bool isEmpty() const; void clear(); protected: // non-property members: QCustomPlot *mParentPlot; QHash > mChildren; // introduced virtual methods: virtual int commonMargin(QCP::MarginSide side) const; // non-virtual methods: void addChild(QCP::MarginSide side, QCPLayoutElement *element); void removeChild(QCP::MarginSide side, QCPLayoutElement *element); private: Q_DISABLE_COPY(QCPMarginGroup) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLayout* layout READ layout) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) Q_PROPERTY(QMargins margins READ margins WRITE setMargins) Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect) /// \endcond public: /*! Defines the phases of the update process, that happens just before a replot. At each phase, \ref update is called with the according UpdatePhase value. */ enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout ,upMargins ///< Phase in which the margins are calculated and set ,upLayout ///< Final phase in which the layout system places the rects of the elements }; Q_ENUMS(UpdatePhase) /*! Defines to which rect of a layout element the size constraints that can be set via \ref setMinimumSize and \ref setMaximumSize apply. The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) does not. \see setSizeConstraintRect */ enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect , scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins }; Q_ENUMS(SizeConstraintRect) explicit QCPLayoutElement(QCustomPlot *parentPlot=nullptr); virtual ~QCPLayoutElement() Q_DECL_OVERRIDE; // getters: QCPLayout *layout() const { return mParentLayout; } QRect rect() const { return mRect; } QRect outerRect() const { return mOuterRect; } QMargins margins() const { return mMargins; } QMargins minimumMargins() const { return mMinimumMargins; } QCP::MarginSides autoMargins() const { return mAutoMargins; } QSize minimumSize() const { return mMinimumSize; } QSize maximumSize() const { return mMaximumSize; } SizeConstraintRect sizeConstraintRect() const { return mSizeConstraintRect; } QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, nullptr); } QHash marginGroups() const { return mMarginGroups; } // setters: void setOuterRect(const QRect &rect); void setMargins(const QMargins &margins); void setMinimumMargins(const QMargins &margins); void setAutoMargins(QCP::MarginSides sides); void setMinimumSize(const QSize &size); void setMinimumSize(int width, int height); void setMaximumSize(const QSize &size); void setMaximumSize(int width, int height); void setSizeConstraintRect(SizeConstraintRect constraintRect); void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); // introduced virtual methods: virtual void update(UpdatePhase phase); virtual QSize minimumOuterSizeHint() const; virtual QSize maximumOuterSizeHint() const; virtual QList elements(bool recursive) const; // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; protected: // property members: QCPLayout *mParentLayout; QSize mMinimumSize, mMaximumSize; SizeConstraintRect mSizeConstraintRect; QRect mRect, mOuterRect; QMargins mMargins, mMinimumMargins; QCP::MarginSides mAutoMargins; QHash mMarginGroups; // introduced virtual methods: virtual int calculateAutoMargin(QCP::MarginSide side); virtual void layoutChanged(); // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE { Q_UNUSED(painter) } virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE { Q_UNUSED(painter) } virtual void parentPlotInitialized(QCustomPlot *parentPlot) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QCPLayoutElement) friend class QCustomPlot; friend class QCPLayout; friend class QCPMarginGroup; }; Q_DECLARE_METATYPE(QCPLayoutElement::UpdatePhase) class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { Q_OBJECT public: explicit QCPLayout(); // reimplemented virtual methods: virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; // introduced virtual methods: virtual int elementCount() const = 0; virtual QCPLayoutElement* elementAt(int index) const = 0; virtual QCPLayoutElement* takeAt(int index) = 0; virtual bool take(QCPLayoutElement* element) = 0; virtual void simplify(); // non-virtual methods: bool removeAt(int index); bool remove(QCPLayoutElement* element); void clear(); protected: // introduced virtual methods: virtual void updateLayout(); // non-virtual methods: void sizeConstraintsChanged() const; void adoptElement(QCPLayoutElement *el); void releaseElement(QCPLayoutElement *el); QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el); static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el); private: Q_DISABLE_COPY(QCPLayout) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(int rowCount READ rowCount) Q_PROPERTY(int columnCount READ columnCount) Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) Q_PROPERTY(FillOrder fillOrder READ fillOrder WRITE setFillOrder) Q_PROPERTY(int wrap READ wrap WRITE setWrap) /// \endcond public: /*! Defines in which direction the grid is filled when using \ref addElement(QCPLayoutElement*). The column/row at which wrapping into the next row/column occurs can be specified with \ref setWrap. \see setFillOrder */ enum FillOrder { foRowsFirst ///< Rows are filled first, and a new element is wrapped to the next column if the row count would exceed \ref setWrap. ,foColumnsFirst ///< Columns are filled first, and a new element is wrapped to the next row if the column count would exceed \ref setWrap. }; Q_ENUMS(FillOrder) explicit QCPLayoutGrid(); virtual ~QCPLayoutGrid() Q_DECL_OVERRIDE; // getters: int rowCount() const { return mElements.size(); } int columnCount() const { return mElements.size() > 0 ? mElements.first().size() : 0; } QList columnStretchFactors() const { return mColumnStretchFactors; } QList rowStretchFactors() const { return mRowStretchFactors; } int columnSpacing() const { return mColumnSpacing; } int rowSpacing() const { return mRowSpacing; } int wrap() const { return mWrap; } FillOrder fillOrder() const { return mFillOrder; } // setters: void setColumnStretchFactor(int column, double factor); void setColumnStretchFactors(const QList &factors); void setRowStretchFactor(int row, double factor); void setRowStretchFactors(const QList &factors); void setColumnSpacing(int pixels); void setRowSpacing(int pixels); void setWrap(int count); void setFillOrder(FillOrder order, bool rearrange=true); // reimplemented virtual methods: virtual void updateLayout() Q_DECL_OVERRIDE; virtual int elementCount() const Q_DECL_OVERRIDE { return rowCount()*columnCount(); } virtual QCPLayoutElement* elementAt(int index) const Q_DECL_OVERRIDE; virtual QCPLayoutElement* takeAt(int index) Q_DECL_OVERRIDE; virtual bool take(QCPLayoutElement* element) Q_DECL_OVERRIDE; virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; virtual void simplify() Q_DECL_OVERRIDE; virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; virtual QSize maximumOuterSizeHint() const Q_DECL_OVERRIDE; // non-virtual methods: QCPLayoutElement *element(int row, int column) const; bool addElement(int row, int column, QCPLayoutElement *element); bool addElement(QCPLayoutElement *element); bool hasElement(int row, int column); void expandTo(int newRowCount, int newColumnCount); void insertRow(int newIndex); void insertColumn(int newIndex); int rowColToIndex(int row, int column) const; void indexToRowCol(int index, int &row, int &column) const; protected: // property members: QList > mElements; QList mColumnStretchFactors; QList mRowStretchFactors; int mColumnSpacing, mRowSpacing; int mWrap; FillOrder mFillOrder; // non-virtual methods: void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; private: Q_DISABLE_COPY(QCPLayoutGrid) }; Q_DECLARE_METATYPE(QCPLayoutGrid::FillOrder) class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { Q_OBJECT public: /*! Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. */ enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment }; Q_ENUMS(InsetPlacement) explicit QCPLayoutInset(); virtual ~QCPLayoutInset() Q_DECL_OVERRIDE; // getters: InsetPlacement insetPlacement(int index) const; Qt::Alignment insetAlignment(int index) const; QRectF insetRect(int index) const; // setters: void setInsetPlacement(int index, InsetPlacement placement); void setInsetAlignment(int index, Qt::Alignment alignment); void setInsetRect(int index, const QRectF &rect); // reimplemented virtual methods: virtual void updateLayout() Q_DECL_OVERRIDE; virtual int elementCount() const Q_DECL_OVERRIDE; virtual QCPLayoutElement* elementAt(int index) const Q_DECL_OVERRIDE; virtual QCPLayoutElement* takeAt(int index) Q_DECL_OVERRIDE; virtual bool take(QCPLayoutElement* element) Q_DECL_OVERRIDE; virtual void simplify() Q_DECL_OVERRIDE {} virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; // non-virtual methods: void addElement(QCPLayoutElement *element, Qt::Alignment alignment); void addElement(QCPLayoutElement *element, const QRectF &rect); protected: // property members: QList mElements; QList mInsetPlacement; QList mInsetAlignment; QList mInsetRect; private: Q_DISABLE_COPY(QCPLayoutInset) }; Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) /* end of 'src/layout.h' */ /* including file 'src/lineending.h' */ /* modified 2021-03-29T02:30:44, size 4426 */ class QCP_LIB_DECL QCPLineEnding { Q_GADGET public: /*! Defines the type of ending decoration for line-like items, e.g. an arrow. \image html QCPLineEnding.png The width and length of these decorations can be controlled with the functions \ref setWidth and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only support a width, the length property is ignored. \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding */ enum EndingStyle { esNone ///< No ending decoration ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) ,esSpikeArrow ///< A filled arrow head with an indented back ,esLineArrow ///< A non-filled arrow head with open back ,esDisc ///< A filled circle ,esSquare ///< A filled square ,esDiamond ///< A filled diamond (45 degrees rotated square) ,esBar ///< A bar perpendicular to the line ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) }; Q_ENUMS(EndingStyle) QCPLineEnding(); QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); // getters: EndingStyle style() const { return mStyle; } double width() const { return mWidth; } double length() const { return mLength; } bool inverted() const { return mInverted; } // setters: void setStyle(EndingStyle style); void setWidth(double width); void setLength(double length); void setInverted(bool inverted); // non-property methods: double boundingDistance() const; double realLength() const; void draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const; void draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const; protected: // property members: EndingStyle mStyle; double mWidth, mLength; bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) /* end of 'src/lineending.h' */ /* including file 'src/axis/labelpainter.h' */ /* modified 2021-03-29T02:30:44, size 7086 */ class QCPLabelPainterPrivate { Q_GADGET public: /*! TODO */ enum AnchorMode { amRectangular ///< ,amSkewedUpright ///< ,amSkewedRotated ///< }; Q_ENUMS(AnchorMode) /*! TODO */ enum AnchorReferenceType { artNormal ///< ,artTangent ///< }; Q_ENUMS(AnchorReferenceType) /*! TODO */ enum AnchorSide { asLeft ///< ,asRight ///< ,asTop ///< ,asBottom ///< ,asTopLeft ,asTopRight ,asBottomRight ,asBottomLeft }; Q_ENUMS(AnchorSide) explicit QCPLabelPainterPrivate(QCustomPlot *parentPlot); virtual ~QCPLabelPainterPrivate(); // setters: void setAnchorSide(AnchorSide side); void setAnchorMode(AnchorMode mode); void setAnchorReference(const QPointF &pixelPoint); void setAnchorReferenceType(AnchorReferenceType type); void setFont(const QFont &font); void setColor(const QColor &color); void setPadding(int padding); void setRotation(double rotation); void setSubstituteExponent(bool enabled); void setMultiplicationSymbol(QChar symbol); void setAbbreviateDecimalPowers(bool enabled); void setCacheSize(int labelCount); // getters: AnchorMode anchorMode() const { return mAnchorMode; } AnchorSide anchorSide() const { return mAnchorSide; } QPointF anchorReference() const { return mAnchorReference; } AnchorReferenceType anchorReferenceType() const { return mAnchorReferenceType; } QFont font() const { return mFont; } QColor color() const { return mColor; } int padding() const { return mPadding; } double rotation() const { return mRotation; } bool substituteExponent() const { return mSubstituteExponent; } QChar multiplicationSymbol() const { return mMultiplicationSymbol; } bool abbreviateDecimalPowers() const { return mAbbreviateDecimalPowers; } int cacheSize() const; //virtual int size() const; // non-property methods: void drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text); void clearCache(); // constants that may be used with setMultiplicationSymbol: static const QChar SymbolDot; static const QChar SymbolCross; protected: struct CachedLabel { QPoint offset; QPixmap pixmap; }; struct LabelData { AnchorSide side; double rotation; // angle in degrees QTransform transform; // the transform about the label anchor which is at (0, 0). Does not contain final absolute x/y positioning on the plot/axis QString basePart, expPart, suffixPart; QRect baseBounds, expBounds, suffixBounds; QRect totalBounds; // is in a coordinate system where label top left is at (0, 0) QRect rotatedTotalBounds; // is in a coordinate system where the label anchor is at (0, 0) QFont baseFont, expFont; QColor color; }; // property members: AnchorMode mAnchorMode; AnchorSide mAnchorSide; QPointF mAnchorReference; AnchorReferenceType mAnchorReferenceType; QFont mFont; QColor mColor; int mPadding; double mRotation; // this is the rotation applied uniformly to all labels, not the heterogeneous rotation in amCircularRotated mode bool mSubstituteExponent; QChar mMultiplicationSymbol; bool mAbbreviateDecimalPowers; // non-property members: QCustomPlot *mParentPlot; QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters QCache mLabelCache; QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; int mLetterCapHeight, mLetterDescent; // introduced virtual methods: virtual void drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text); virtual QByteArray generateLabelParameterHash() const; // TODO: get rid of this in favor of invalidation flag upon setters? // non-virtual methods: QPointF getAnchorPos(const QPointF &tickPos); void drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const; LabelData getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const; void applyAnchorTransform(LabelData &labelData) const; //void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; CachedLabel *createCachedLabel(const LabelData &labelData) const; QByteArray cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const; AnchorSide skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const; AnchorSide rotationCorrectedSide(AnchorSide side, double rotation) const; void analyzeFontMetrics(); }; Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorMode) Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorSide) /* end of 'src/axis/labelpainter.h' */ /* including file 'src/axis/axisticker.h' */ /* modified 2021-03-29T02:30:44, size 4230 */ class QCP_LIB_DECL QCPAxisTicker { Q_GADGET public: /*! Defines the strategies that the axis ticker may follow when choosing the size of the tick step. \see setTickStepStrategy */ enum TickStepStrategy { tssReadability ///< A nicely readable tick step is prioritized over matching the requested number of ticks (see \ref setTickCount) ,tssMeetTickCount ///< Less readable tick steps are allowed which in turn facilitates getting closer to the requested tick count }; Q_ENUMS(TickStepStrategy) QCPAxisTicker(); virtual ~QCPAxisTicker(); // getters: TickStepStrategy tickStepStrategy() const { return mTickStepStrategy; } int tickCount() const { return mTickCount; } double tickOrigin() const { return mTickOrigin; } // setters: void setTickStepStrategy(TickStepStrategy strategy); void setTickCount(int count); void setTickOrigin(double origin); // introduced virtual methods: virtual void generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector &ticks, QVector *subTicks, QVector *tickLabels); protected: // property members: TickStepStrategy mTickStepStrategy; int mTickCount; double mTickOrigin; // introduced virtual methods: virtual double getTickStep(const QCPRange &range); virtual int getSubTickCount(double tickStep); virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision); virtual QVector createTickVector(double tickStep, const QCPRange &range); virtual QVector createSubTickVector(int subTickCount, const QVector &ticks); virtual QVector createLabelVector(const QVector &ticks, const QLocale &locale, QChar formatChar, int precision); // non-virtual methods: void trimTicks(const QCPRange &range, QVector &ticks, bool keepOneOutlier) const; double pickClosest(double target, const QVector &candidates) const; double getMantissa(double input, double *magnitude=nullptr) const; double cleanMantissa(double input) const; private: Q_DISABLE_COPY(QCPAxisTicker) }; Q_DECLARE_METATYPE(QCPAxisTicker::TickStepStrategy) Q_DECLARE_METATYPE(QSharedPointer) /* end of 'src/axis/axisticker.h' */ /* including file 'src/axis/axistickerdatetime.h' */ /* modified 2021-03-29T02:30:44, size 3600 */ class QCP_LIB_DECL QCPAxisTickerDateTime : public QCPAxisTicker { public: QCPAxisTickerDateTime(); // getters: QString dateTimeFormat() const { return mDateTimeFormat; } Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) QTimeZone timeZone() const { return mTimeZone; } #endif // setters: void setDateTimeFormat(const QString &format); void setDateTimeSpec(Qt::TimeSpec spec); # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) void setTimeZone(const QTimeZone &zone); # endif void setTickOrigin(double origin); // hides base class method but calls baseclass implementation ("using" throws off IDEs and doxygen) void setTickOrigin(const QDateTime &origin); // static methods: static QDateTime keyToDateTime(double key); static double dateTimeToKey(const QDateTime &dateTime); static double dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec=Qt::LocalTime); protected: // property members: QString mDateTimeFormat; Qt::TimeSpec mDateTimeSpec; # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) QTimeZone mTimeZone; # endif // non-property members: enum DateStrategy {dsNone, dsUniformTimeInDay, dsUniformDayInMonth} mDateStrategy; // reimplemented virtual methods: virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; }; /* end of 'src/axis/axistickerdatetime.h' */ /* including file 'src/axis/axistickertime.h' */ /* modified 2021-03-29T02:30:44, size 3542 */ class QCP_LIB_DECL QCPAxisTickerTime : public QCPAxisTicker { Q_GADGET public: /*! Defines the logical units in which fractions of time spans can be expressed. \see setFieldWidth, setTimeFormat */ enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat) ,tuSeconds ///< Seconds (%%s in \ref setTimeFormat) ,tuMinutes ///< Minutes (%%m in \ref setTimeFormat) ,tuHours ///< Hours (%%h in \ref setTimeFormat) ,tuDays ///< Days (%%d in \ref setTimeFormat) }; Q_ENUMS(TimeUnit) QCPAxisTickerTime(); // getters: QString timeFormat() const { return mTimeFormat; } int fieldWidth(TimeUnit unit) const { return mFieldWidth.value(unit); } // setters: void setTimeFormat(const QString &format); void setFieldWidth(TimeUnit unit, int width); protected: // property members: QString mTimeFormat; QHash mFieldWidth; // non-property members: TimeUnit mSmallestUnit, mBiggestUnit; QHash mFormatPattern; // reimplemented virtual methods: virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; // non-virtual methods: void replaceUnit(QString &text, TimeUnit unit, int value) const; }; Q_DECLARE_METATYPE(QCPAxisTickerTime::TimeUnit) /* end of 'src/axis/axistickertime.h' */ /* including file 'src/axis/axistickerfixed.h' */ /* modified 2021-03-29T02:30:44, size 3308 */ class QCP_LIB_DECL QCPAxisTickerFixed : public QCPAxisTicker { Q_GADGET public: /*! Defines how the axis ticker may modify the specified tick step (\ref setTickStep) in order to control the number of ticks in the axis range. \see setScaleStrategy */ enum ScaleStrategy { ssNone ///< Modifications are not allowed, the specified tick step is absolutely fixed. This might cause a high tick density and overlapping labels if the axis range is zoomed out. ,ssMultiples ///< An integer multiple of the specified tick step is allowed. The used factor follows the base class properties of \ref setTickStepStrategy and \ref setTickCount. ,ssPowers ///< An integer power of the specified tick step is allowed. }; Q_ENUMS(ScaleStrategy) QCPAxisTickerFixed(); // getters: double tickStep() const { return mTickStep; } ScaleStrategy scaleStrategy() const { return mScaleStrategy; } // setters: void setTickStep(double step); void setScaleStrategy(ScaleStrategy strategy); protected: // property members: double mTickStep; ScaleStrategy mScaleStrategy; // reimplemented virtual methods: virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; }; Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) /* end of 'src/axis/axistickerfixed.h' */ /* including file 'src/axis/axistickertext.h' */ /* modified 2021-03-29T02:30:44, size 3090 */ class QCP_LIB_DECL QCPAxisTickerText : public QCPAxisTicker { public: QCPAxisTickerText(); // getters: QMap &ticks() { return mTicks; } int subTickCount() const { return mSubTickCount; } // setters: void setTicks(const QMap &ticks); void setTicks(const QVector &positions, const QVector &labels); void setSubTickCount(int subTicks); // non-virtual methods: void clear(); void addTick(double position, const QString &label); void addTicks(const QMap &ticks); void addTicks(const QVector &positions, const QVector &labels); protected: // property members: QMap mTicks; int mSubTickCount; // reimplemented virtual methods: virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; }; /* end of 'src/axis/axistickertext.h' */ /* including file 'src/axis/axistickerpi.h' */ /* modified 2021-03-29T02:30:44, size 3911 */ class QCP_LIB_DECL QCPAxisTickerPi : public QCPAxisTicker { Q_GADGET public: /*! Defines how fractions should be displayed in tick labels. \see setFractionStyle */ enum FractionStyle { fsFloatingPoint ///< Fractions are displayed as regular decimal floating point numbers, e.g. "0.25" or "0.125". ,fsAsciiFractions ///< Fractions are written as rationals using ASCII characters only, e.g. "1/4" or "1/8" ,fsUnicodeFractions ///< Fractions are written using sub- and superscript UTF-8 digits and the fraction symbol. }; Q_ENUMS(FractionStyle) QCPAxisTickerPi(); // getters: QString piSymbol() const { return mPiSymbol; } double piValue() const { return mPiValue; } bool periodicity() const { return mPeriodicity; } FractionStyle fractionStyle() const { return mFractionStyle; } // setters: void setPiSymbol(QString symbol); void setPiValue(double pi); void setPeriodicity(int multiplesOfPi); void setFractionStyle(FractionStyle style); protected: // property members: QString mPiSymbol; double mPiValue; int mPeriodicity; FractionStyle mFractionStyle; // non-property members: double mPiTickStep; // size of one tick step in units of mPiValue // reimplemented virtual methods: virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; // non-virtual methods: void simplifyFraction(int &numerator, int &denominator) const; QString fractionToString(int numerator, int denominator) const; QString unicodeFraction(int numerator, int denominator) const; QString unicodeSuperscript(int number) const; QString unicodeSubscript(int number) const; }; Q_DECLARE_METATYPE(QCPAxisTickerPi::FractionStyle) /* end of 'src/axis/axistickerpi.h' */ /* including file 'src/axis/axistickerlog.h' */ /* modified 2021-03-29T02:30:44, size 2594 */ class QCP_LIB_DECL QCPAxisTickerLog : public QCPAxisTicker { public: QCPAxisTickerLog(); // getters: double logBase() const { return mLogBase; } int subTickCount() const { return mSubTickCount; } // setters: void setLogBase(double base); void setSubTickCount(int subTicks); protected: // property members: double mLogBase; int mSubTickCount; // non-property members: double mLogBaseLnInv; // reimplemented virtual methods: virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; }; /* end of 'src/axis/axistickerlog.h' */ /* including file 'src/axis/axis.h' */ /* modified 2021-03-29T02:30:44, size 20913 */ class QCP_LIB_DECL QCPGrid :public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) /// \endcond public: explicit QCPGrid(QCPAxis *parentAxis); // getters: bool subGridVisible() const { return mSubGridVisible; } bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } QPen pen() const { return mPen; } QPen subGridPen() const { return mSubGridPen; } QPen zeroLinePen() const { return mZeroLinePen; } // setters: void setSubGridVisible(bool visible); void setAntialiasedSubGrid(bool enabled); void setAntialiasedZeroLine(bool enabled); void setPen(const QPen &pen); void setSubGridPen(const QPen &pen); void setZeroLinePen(const QPen &pen); protected: // property members: bool mSubGridVisible; bool mAntialiasedSubGrid, mAntialiasedZeroLine; QPen mPen, mSubGridPen, mZeroLinePen; // non-property members: QCPAxis *mParentAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: void drawGridLines(QCPPainter *painter) const; void drawSubGridLines(QCPPainter *painter) const; friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(AxisType axisType READ axisType) Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) Q_PROPERTY(QSharedPointer ticker READ ticker WRITE setTicker) Q_PROPERTY(bool ticks READ ticks WRITE setTicks) Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide) Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) Q_PROPERTY(QVector tickVector READ tickVector) Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels) Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) Q_PROPERTY(bool subTicks READ subTicks WRITE setSubTicks) Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) Q_PROPERTY(int padding READ padding WRITE setPadding) Q_PROPERTY(int offset READ offset WRITE setOffset) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) Q_PROPERTY(QCPGrid* grid READ grid) /// \endcond public: /*! Defines at which side of the axis rect the axis will appear. This also affects how the tick marks are drawn, on which side the labels are placed etc. */ enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect ,atTop = 0x04 ///< 0x04 Axis is horizontal and on the top side of the axis rect ,atBottom = 0x08 ///< 0x08 Axis is horizontal and on the bottom side of the axis rect }; Q_ENUMS(AxisType) Q_FLAGS(AxisTypes) Q_DECLARE_FLAGS(AxisTypes, AxisType) /*! Defines on which side of the axis the tick labels (numbers) shall appear. \see setTickLabelSide */ enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect ,lsOutside ///< Tick labels will be displayed outside the axis rect }; Q_ENUMS(LabelSide) /*! Defines the scale of an axis. \see setScaleType */ enum ScaleType { stLinear ///< Linear scaling ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). }; Q_ENUMS(ScaleType) /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts */ enum SelectablePart { spNone = 0 ///< None of the selectable parts ,spAxis = 0x001 ///< The axis backbone and tick marks ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) ,spAxisLabel = 0x004 ///< The axis label }; Q_ENUMS(SelectablePart) Q_FLAGS(SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPAxis(QCPAxisRect *parent, AxisType type); virtual ~QCPAxis() Q_DECL_OVERRIDE; // getters: AxisType axisType() const { return mAxisType; } QCPAxisRect *axisRect() const { return mAxisRect; } ScaleType scaleType() const { return mScaleType; } const QCPRange range() const { return mRange; } bool rangeReversed() const { return mRangeReversed; } QSharedPointer ticker() const { return mTicker; } bool ticks() const { return mTicks; } bool tickLabels() const { return mTickLabels; } int tickLabelPadding() const; QFont tickLabelFont() const { return mTickLabelFont; } QColor tickLabelColor() const { return mTickLabelColor; } double tickLabelRotation() const; LabelSide tickLabelSide() const; QString numberFormat() const; int numberPrecision() const { return mNumberPrecision; } QVector tickVector() const { return mTickVector; } QVector tickVectorLabels() const { return mTickVectorLabels; } int tickLengthIn() const; int tickLengthOut() const; bool subTicks() const { return mSubTicks; } int subTickLengthIn() const; int subTickLengthOut() const; QPen basePen() const { return mBasePen; } QPen tickPen() const { return mTickPen; } QPen subTickPen() const { return mSubTickPen; } QFont labelFont() const { return mLabelFont; } QColor labelColor() const { return mLabelColor; } QString label() const { return mLabel; } int labelPadding() const; int padding() const { return mPadding; } int offset() const; SelectableParts selectedParts() const { return mSelectedParts; } SelectableParts selectableParts() const { return mSelectableParts; } QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } QFont selectedLabelFont() const { return mSelectedLabelFont; } QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } QColor selectedLabelColor() const { return mSelectedLabelColor; } QPen selectedBasePen() const { return mSelectedBasePen; } QPen selectedTickPen() const { return mSelectedTickPen; } QPen selectedSubTickPen() const { return mSelectedSubTickPen; } QCPLineEnding lowerEnding() const; QCPLineEnding upperEnding() const; QCPGrid *grid() const { return mGrid; } // setters: Q_SLOT void setScaleType(QCPAxis::ScaleType type); Q_SLOT void setRange(const QCPRange &range); void setRange(double lower, double upper); void setRange(double position, double size, Qt::AlignmentFlag alignment); void setRangeLower(double lower); void setRangeUpper(double upper); void setRangeReversed(bool reversed); void setTicker(QSharedPointer ticker); void setTicks(bool show); void setTickLabels(bool show); void setTickLabelPadding(int padding); void setTickLabelFont(const QFont &font); void setTickLabelColor(const QColor &color); void setTickLabelRotation(double degrees); void setTickLabelSide(LabelSide side); void setNumberFormat(const QString &formatCode); void setNumberPrecision(int precision); void setTickLength(int inside, int outside=0); void setTickLengthIn(int inside); void setTickLengthOut(int outside); void setSubTicks(bool show); void setSubTickLength(int inside, int outside=0); void setSubTickLengthIn(int inside); void setSubTickLengthOut(int outside); void setBasePen(const QPen &pen); void setTickPen(const QPen &pen); void setSubTickPen(const QPen &pen); void setLabelFont(const QFont &font); void setLabelColor(const QColor &color); void setLabel(const QString &str); void setLabelPadding(int padding); void setPadding(int padding); void setOffset(int offset); void setSelectedTickLabelFont(const QFont &font); void setSelectedLabelFont(const QFont &font); void setSelectedTickLabelColor(const QColor &color); void setSelectedLabelColor(const QColor &color); void setSelectedBasePen(const QPen &pen); void setSelectedTickPen(const QPen &pen); void setSelectedSubTickPen(const QPen &pen); Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); void setLowerEnding(const QCPLineEnding &ending); void setUpperEnding(const QCPLineEnding &ending); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; // non-property methods: Qt::Orientation orientation() const { return mOrientation; } int pixelOrientation() const { return rangeReversed() != (orientation()==Qt::Vertical) ? -1 : 1; } void moveRange(double diff); void scaleRange(double factor); void scaleRange(double factor, double center); void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); void rescale(bool onlyVisiblePlottables=false); double pixelToCoord(double value) const; double coordToPixel(double value) const; SelectablePart getPartAt(const QPointF &pos) const; QList plottables() const; QList graphs() const; QList items() const; static AxisType marginSideToAxisType(QCP::MarginSide side); static Qt::Orientation orientation(AxisType type) { return type==atBottom || type==atTop ? Qt::Horizontal : Qt::Vertical; } static AxisType opposite(AxisType type); signals: void rangeChanged(const QCPRange &newRange); void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); void scaleTypeChanged(QCPAxis::ScaleType scaleType); void selectionChanged(const QCPAxis::SelectableParts &parts); void selectableChanged(const QCPAxis::SelectableParts &parts); protected: // property members: // axis base: AxisType mAxisType; QCPAxisRect *mAxisRect; //int mOffset; // in QCPAxisPainter int mPadding; Qt::Orientation mOrientation; SelectableParts mSelectableParts, mSelectedParts; QPen mBasePen, mSelectedBasePen; //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter // axis label: //int mLabelPadding; // in QCPAxisPainter QString mLabel; QFont mLabelFont, mSelectedLabelFont; QColor mLabelColor, mSelectedLabelColor; // tick labels: //int mTickLabelPadding; // in QCPAxisPainter bool mTickLabels; //double mTickLabelRotation; // in QCPAxisPainter QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; int mNumberPrecision; QLatin1Char mNumberFormatChar; bool mNumberBeautifulPowers; //bool mNumberMultiplyCross; // QCPAxisPainter // ticks and subticks: bool mTicks; bool mSubTicks; //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: QCPRange mRange; bool mRangeReversed; ScaleType mScaleType; // non-property members: QCPGrid *mGrid; QCPAxisPainterPrivate *mAxisPainter; QSharedPointer mTicker; QVector mTickVector; QVector mTickVectorLabels; QVector mSubTickVector; bool mCachedMarginValid; int mCachedMargin; bool mDragging; QCPRange mDragStartRange; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; // introduced virtual methods: virtual int calculateMargin(); // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // mouse events: virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; // non-virtual methods: void setupTickVectors(); QPen getBasePen() const; QPen getTickPen() const; QPen getSubTickPen() const; QFont getTickLabelFont() const; QFont getLabelFont() const; QColor getTickLabelColor() const; QColor getLabelColor() const; private: Q_DISABLE_COPY(QCPAxis) friend class QCustomPlot; friend class QCPGrid; friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) Q_DECLARE_METATYPE(QCPAxis::AxisType) Q_DECLARE_METATYPE(QCPAxis::LabelSide) Q_DECLARE_METATYPE(QCPAxis::ScaleType) Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); virtual ~QCPAxisPainterPrivate(); virtual void draw(QCPPainter *painter); virtual int size(); void clearCache(); QRect axisSelectionBox() const { return mAxisSelectionBox; } QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } QRect labelSelectionBox() const { return mLabelSelectionBox; } // public property members: QCPAxis::AxisType type; QPen basePen; QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters int labelPadding; // directly accessed by QCPAxis setters/getters QFont labelFont; QColor labelColor; QString label; int tickLabelPadding; // directly accessed by QCPAxis setters/getters double tickLabelRotation; // directly accessed by QCPAxis setters/getters QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters bool substituteExponent; bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters QPen tickPen, subTickPen; QFont tickLabelFont; QColor tickLabelColor; QRect axisRect, viewportRect; int offset; // directly accessed by QCPAxis setters/getters bool abbreviateDecimalPowers; bool reversedEndings; QVector subTickPositions; QVector tickPositions; QVector tickLabels; protected: struct CachedLabel { QPointF offset; QPixmap pixmap; }; struct TickLabelData { QString basePart, expPart, suffixPart; QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; QFont baseFont, expFont; }; QCustomPlot *mParentPlot; QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters QCache mLabelCache; QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; virtual QByteArray generateLabelParameterHash() const; virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; /* end of 'src/axis/axis.h' */ /* including file 'src/scatterstyle.h' */ /* modified 2021-03-29T02:30:44, size 7275 */ class QCP_LIB_DECL QCPScatterStyle { Q_GADGET public: /*! Represents the various properties of a scatter style instance. For example, this enum is used to specify which properties of \ref QCPSelectionDecorator::setScatterStyle will be used when highlighting selected data points. Specific scatter properties can be transferred between \ref QCPScatterStyle instances via \ref setFromOther. */ enum ScatterProperty { spNone = 0x00 ///< 0x00 None ,spPen = 0x01 ///< 0x01 The pen property, see \ref setPen ,spBrush = 0x02 ///< 0x02 The brush property, see \ref setBrush ,spSize = 0x04 ///< 0x04 The size property, see \ref setSize ,spShape = 0x08 ///< 0x08 The shape property, see \ref setShape ,spAll = 0xFF ///< 0xFF All properties }; Q_ENUMS(ScatterProperty) Q_FLAGS(ScatterProperties) Q_DECLARE_FLAGS(ScatterProperties, ScatterProperty) /*! Defines the shape used for scatter points. On plottables/items that draw scatters, the sizes of these visualizations (with exception of \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are drawn with the pen and brush specified with \ref setPen and \ref setBrush. */ enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) ,ssCross ///< \enumimage{ssCross.png} a cross ,ssPlus ///< \enumimage{ssPlus.png} a plus ,ssCircle ///< \enumimage{ssCircle.png} a circle ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) ,ssSquare ///< \enumimage{ssSquare.png} a square ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) }; Q_ENUMS(ScatterShape) QCPScatterStyle(); QCPScatterStyle(ScatterShape shape, double size=6); QCPScatterStyle(ScatterShape shape, const QColor &color, double size); QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); QCPScatterStyle(const QPixmap &pixmap); QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); // getters: double size() const { return mSize; } ScatterShape shape() const { return mShape; } QPen pen() const { return mPen; } QBrush brush() const { return mBrush; } QPixmap pixmap() const { return mPixmap; } QPainterPath customPath() const { return mCustomPath; } // setters: void setFromOther(const QCPScatterStyle &other, ScatterProperties properties); void setSize(double size); void setShape(ScatterShape shape); void setPen(const QPen &pen); void setBrush(const QBrush &brush); void setPixmap(const QPixmap &pixmap); void setCustomPath(const QPainterPath &customPath); // non-property methods: bool isNone() const { return mShape == ssNone; } bool isPenDefined() const { return mPenDefined; } void undefinePen(); void applyTo(QCPPainter *painter, const QPen &defaultPen) const; void drawShape(QCPPainter *painter, const QPointF &pos) const; void drawShape(QCPPainter *painter, double x, double y) const; protected: // property members: double mSize; ScatterShape mShape; QPen mPen; QBrush mBrush; QPixmap mPixmap; QPainterPath mCustomPath; // non-property members: bool mPenDefined; }; Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); Q_DECLARE_OPERATORS_FOR_FLAGS(QCPScatterStyle::ScatterProperties) Q_DECLARE_METATYPE(QCPScatterStyle::ScatterProperty) Q_DECLARE_METATYPE(QCPScatterStyle::ScatterShape) /* end of 'src/scatterstyle.h' */ /* including file 'src/datacontainer.h' */ /* modified 2021-03-29T02:30:44, size 34070 */ /*! \relates QCPDataContainer Returns whether the sort key of \a a is less than the sort key of \a b. \see QCPDataContainer::sort */ template inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) { return a.sortKey() < b.sortKey(); } template class QCPDataContainer // no QCP_LIB_DECL, template class ends up in header (cpp included below) { public: typedef typename QVector::const_iterator const_iterator; typedef typename QVector::iterator iterator; QCPDataContainer(); // getters: int size() const { return mData.size()-mPreallocSize; } bool isEmpty() const { return size() == 0; } bool autoSqueeze() const { return mAutoSqueeze; } // setters: void setAutoSqueeze(bool enabled); // non-virtual methods: void set(const QCPDataContainer &data); void set(const QVector &data, bool alreadySorted=false); void add(const QCPDataContainer &data); void add(const QVector &data, bool alreadySorted=false); void add(const DataType &data); void removeBefore(double sortKey); void removeAfter(double sortKey); void remove(double sortKeyFrom, double sortKeyTo); void remove(double sortKey); void clear(); void sort(); void squeeze(bool preAllocation=true, bool postAllocation=true); const_iterator constBegin() const { return mData.constBegin()+mPreallocSize; } const_iterator constEnd() const { return mData.constEnd(); } iterator begin() { return mData.begin()+mPreallocSize; } iterator end() { return mData.end(); } const_iterator findBegin(double sortKey, bool expandedRange=true) const; const_iterator findEnd(double sortKey, bool expandedRange=true) const; const_iterator at(int index) const { return constBegin()+qBound(0, index, size()); } QCPRange keyRange(bool &foundRange, QCP::SignDomain signDomain=QCP::sdBoth); QCPRange valueRange(bool &foundRange, QCP::SignDomain signDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()); QCPDataRange dataRange() const { return QCPDataRange(0, size()); } void limitIteratorsToDataRange(const_iterator &begin, const_iterator &end, const QCPDataRange &dataRange) const; protected: // property members: bool mAutoSqueeze; // non-property memebers: QVector mData; int mPreallocSize; int mPreallocIteration; // non-virtual methods: void preallocateGrow(int minimumPreallocSize); void performAutoSqueeze(); }; // include implementation in header since it is a class template: //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPDataContainer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPDataContainer \brief The generic data container for one-dimensional plottables This class template provides a fast container for data storage of one-dimensional data. The data type is specified as template parameter (called \a DataType in the following) and must provide some methods as described in the \ref qcpdatacontainer-datatype "next section". The data is stored in a sorted fashion, which allows very quick lookups by the sorted key as well as retrieval of ranges (see \ref findBegin, \ref findEnd, \ref keyRange) using binary search. The container uses a preallocation and a postallocation scheme, such that appending and prepending data (with respect to the sort key) is very fast and minimizes reallocations. If data is added which needs to be inserted between existing keys, the merge usually can be done quickly too, using the fact that existing data is always sorted. The user can further improve performance by specifying that added data is already itself sorted by key, if he can guarantee that this is the case (see for example \ref add(const QVector &data, bool alreadySorted)). The data can be accessed with the provided const iterators (\ref constBegin, \ref constEnd). If it is necessary to alter existing data in-place, the non-const iterators can be used (\ref begin, \ref end). Changing data members that are not the sort key (for most data types called \a key) is safe from the container's perspective. Great care must be taken however if the sort key is modified through the non-const iterators. For performance reasons, the iterators don't automatically cause a re-sorting upon their manipulation. It is thus the responsibility of the user to leave the container in a sorted state when finished with the data manipulation, before calling any other methods on the container. A complete re-sort (e.g. after finishing all sort key manipulation) can be done by calling \ref sort. Failing to do so can not be detected by the container efficiently and will cause both rendering artifacts and potential data loss. Implementing one-dimensional plottables that make use of a \ref QCPDataContainer is usually done by subclassing from \ref QCPAbstractPlottable1D "QCPAbstractPlottable1D", which introduces an according \a mDataContainer member and some convenience methods. \section qcpdatacontainer-datatype Requirements for the DataType template parameter The template parameter DataType is the type of the stored data points. It must be trivially copyable and have the following public methods, preferably inline: \li double sortKey() const\n Returns the member variable of this data point that is the sort key, defining the ordering in the container. Often this variable is simply called \a key. \li static DataType fromSortKey(double sortKey)\n Returns a new instance of the data type initialized with its sort key set to \a sortKey. \li static bool sortKeyIsMainKey()\n Returns true if the sort key is equal to the main key (see method \c mainKey below). For most plottables this is the case. It is not the case for example for \ref QCPCurve, which uses \a t as sort key and \a key as main key. This is the reason why QCPCurve unlike QCPGraph can display parametric curves with loops. \li double mainKey() const\n Returns the variable of this data point considered the main key. This is commonly the variable that is used as the coordinate of this data point on the key axis of the plottable. This method is used for example when determining the automatic axis rescaling of key axes (\ref QCPAxis::rescale). \li double mainValue() const\n Returns the variable of this data point considered the main value. This is commonly the variable that is used as the coordinate of this data point on the value axis of the plottable. \li QCPRange valueRange() const\n Returns the range this data point spans in the value axis coordinate. If the data is single-valued (e.g. QCPGraphData), this is simply a range with both lower and upper set to the main data point value. However if the data points can represent multiple values at once (e.g QCPFinancialData with its \a high, \a low, \a open and \a close values at each \a key) this method should return the range those values span. This method is used for example when determining the automatic axis rescaling of value axes (\ref QCPAxis::rescale). */ /* start documentation of inline functions */ /*! \fn int QCPDataContainer::size() const Returns the number of data points in the container. */ /*! \fn bool QCPDataContainer::isEmpty() const Returns whether this container holds no data points. */ /*! \fn QCPDataContainer::const_iterator QCPDataContainer::constBegin() const Returns a const iterator to the first data point in this container. */ /*! \fn QCPDataContainer::const_iterator QCPDataContainer::constEnd() const Returns a const iterator to the element past the last data point in this container. */ /*! \fn QCPDataContainer::iterator QCPDataContainer::begin() const Returns a non-const iterator to the first data point in this container. You can manipulate the data points in-place through the non-const iterators, but great care must be taken when manipulating the sort key of a data point, see \ref sort, or the detailed description of this class. */ /*! \fn QCPDataContainer::iterator QCPDataContainer::end() const Returns a non-const iterator to the element past the last data point in this container. You can manipulate the data points in-place through the non-const iterators, but great care must be taken when manipulating the sort key of a data point, see \ref sort, or the detailed description of this class. */ /*! \fn QCPDataContainer::const_iterator QCPDataContainer::at(int index) const Returns a const iterator to the element with the specified \a index. If \a index points beyond the available elements in this container, returns \ref constEnd, i.e. an iterator past the last valid element. You can use this method to easily obtain iterators from a \ref QCPDataRange, see the \ref dataselection-accessing "data selection page" for an example. */ /*! \fn QCPDataRange QCPDataContainer::dataRange() const Returns a \ref QCPDataRange encompassing the entire data set of this container. This means the begin index of the returned range is 0, and the end index is \ref size. */ /* end documentation of inline functions */ /*! Constructs a QCPDataContainer used for plottable classes that represent a series of key-sorted data */ template QCPDataContainer::QCPDataContainer() : mAutoSqueeze(true), mPreallocSize(0), mPreallocIteration(0) { } /*! Sets whether the container automatically decides when to release memory from its post- and preallocation pools when data points are removed. By default this is enabled and for typical applications shouldn't be changed. If auto squeeze is disabled, you can manually decide when to release pre-/postallocation with \ref squeeze. */ template void QCPDataContainer::setAutoSqueeze(bool enabled) { if (mAutoSqueeze != enabled) { mAutoSqueeze = enabled; if (mAutoSqueeze) performAutoSqueeze(); } } /*! \overload Replaces the current data in this container with the provided \a data. \see add, remove */ template void QCPDataContainer::set(const QCPDataContainer &data) { clear(); add(data); } /*! \overload Replaces the current data in this container with the provided \a data If you can guarantee that the data points in \a data have ascending order with respect to the DataType's sort key, set \a alreadySorted to true to avoid an unnecessary sorting run. \see add, remove */ template void QCPDataContainer::set(const QVector &data, bool alreadySorted) { mData = data; mPreallocSize = 0; mPreallocIteration = 0; if (!alreadySorted) sort(); } /*! \overload Adds the provided \a data to the current data in this container. \see set, remove */ template void QCPDataContainer::add(const QCPDataContainer &data) { if (data.isEmpty()) return; const int n = data.size(); const int oldSize = size(); if (oldSize > 0 && !qcpLessThanSortKey(*constBegin(), *(data.constEnd()-1))) // prepend if new data keys are all smaller than or equal to existing ones { if (mPreallocSize < n) preallocateGrow(n); mPreallocSize -= n; std::copy(data.constBegin(), data.constEnd(), begin()); } else // don't need to prepend, so append and merge if necessary { mData.resize(mData.size()+n); std::copy(data.constBegin(), data.constEnd(), end()-n); if (oldSize > 0 && !qcpLessThanSortKey(*(constEnd()-n-1), *(constEnd()-n))) // if appended range keys aren't all greater than existing ones, merge the two partitions std::inplace_merge(begin(), end()-n, end(), qcpLessThanSortKey); } } /*! Adds the provided data points in \a data to the current data. If you can guarantee that the data points in \a data have ascending order with respect to the DataType's sort key, set \a alreadySorted to true to avoid an unnecessary sorting run. \see set, remove */ template void QCPDataContainer::add(const QVector &data, bool alreadySorted) { if (data.isEmpty()) return; if (isEmpty()) { set(data, alreadySorted); return; } const int n = data.size(); const int oldSize = size(); if (alreadySorted && oldSize > 0 && !qcpLessThanSortKey(*constBegin(), *(data.constEnd()-1))) // prepend if new data is sorted and keys are all smaller than or equal to existing ones { if (mPreallocSize < n) preallocateGrow(n); mPreallocSize -= n; std::copy(data.constBegin(), data.constEnd(), begin()); } else // don't need to prepend, so append and then sort and merge if necessary { mData.resize(mData.size()+n); std::copy(data.constBegin(), data.constEnd(), end()-n); if (!alreadySorted) // sort appended subrange if it wasn't already sorted std::sort(end()-n, end(), qcpLessThanSortKey); if (oldSize > 0 && !qcpLessThanSortKey(*(constEnd()-n-1), *(constEnd()-n))) // if appended range keys aren't all greater than existing ones, merge the two partitions std::inplace_merge(begin(), end()-n, end(), qcpLessThanSortKey); } } /*! \overload Adds the provided single data point to the current data. \see remove */ template void QCPDataContainer::add(const DataType &data) { if (isEmpty() || !qcpLessThanSortKey(data, *(constEnd()-1))) // quickly handle appends if new data key is greater or equal to existing ones { mData.append(data); } else if (qcpLessThanSortKey(data, *constBegin())) // quickly handle prepends using preallocated space { if (mPreallocSize < 1) preallocateGrow(1); --mPreallocSize; *begin() = data; } else // handle inserts, maintaining sorted keys { QCPDataContainer::iterator insertionPoint = std::lower_bound(begin(), end(), data, qcpLessThanSortKey); mData.insert(insertionPoint, data); } } /*! Removes all data points with (sort-)keys smaller than or equal to \a sortKey. \see removeAfter, remove, clear */ template void QCPDataContainer::removeBefore(double sortKey) { QCPDataContainer::iterator it = begin(); QCPDataContainer::iterator itEnd = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); mPreallocSize += int(itEnd-it); // don't actually delete, just add it to the preallocated block (if it gets too large, squeeze will take care of it) if (mAutoSqueeze) performAutoSqueeze(); } /*! Removes all data points with (sort-)keys greater than or equal to \a sortKey. \see removeBefore, remove, clear */ template void QCPDataContainer::removeAfter(double sortKey) { QCPDataContainer::iterator it = std::upper_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); QCPDataContainer::iterator itEnd = end(); mData.erase(it, itEnd); // typically adds it to the postallocated block if (mAutoSqueeze) performAutoSqueeze(); } /*! Removes all data points with (sort-)keys between \a sortKeyFrom and \a sortKeyTo. if \a sortKeyFrom is greater or equal to \a sortKeyTo, the function does nothing. To remove a single data point with known (sort-)key, use \ref remove(double sortKey). \see removeBefore, removeAfter, clear */ template void QCPDataContainer::remove(double sortKeyFrom, double sortKeyTo) { if (sortKeyFrom >= sortKeyTo || isEmpty()) return; QCPDataContainer::iterator it = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKeyFrom), qcpLessThanSortKey); QCPDataContainer::iterator itEnd = std::upper_bound(it, end(), DataType::fromSortKey(sortKeyTo), qcpLessThanSortKey); mData.erase(it, itEnd); if (mAutoSqueeze) performAutoSqueeze(); } /*! \overload Removes a single data point at \a sortKey. If the position is not known with absolute (binary) precision, consider using \ref remove(double sortKeyFrom, double sortKeyTo) with a small fuzziness interval around the suspected position, depeding on the precision with which the (sort-)key is known. \see removeBefore, removeAfter, clear */ template void QCPDataContainer::remove(double sortKey) { QCPDataContainer::iterator it = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); if (it != end() && it->sortKey() == sortKey) { if (it == begin()) ++mPreallocSize; // don't actually delete, just add it to the preallocated block (if it gets too large, squeeze will take care of it) else mData.erase(it); } if (mAutoSqueeze) performAutoSqueeze(); } /*! Removes all data points. \see remove, removeAfter, removeBefore */ template void QCPDataContainer::clear() { mData.clear(); mPreallocIteration = 0; mPreallocSize = 0; } /*! Re-sorts all data points in the container by their sort key. When setting, adding or removing points using the QCPDataContainer interface (\ref set, \ref add, \ref remove, etc.), the container makes sure to always stay in a sorted state such that a full resort is never necessary. However, if you choose to directly manipulate the sort key on data points by accessing and modifying it through the non-const iterators (\ref begin, \ref end), it is your responsibility to bring the container back into a sorted state before any other methods are called on it. This can be achieved by calling this method immediately after finishing the sort key manipulation. */ template void QCPDataContainer::sort() { std::sort(begin(), end(), qcpLessThanSortKey); } /*! Frees all unused memory that is currently in the preallocation and postallocation pools. Note that QCPDataContainer automatically decides whether squeezing is necessary, if \ref setAutoSqueeze is left enabled. It should thus not be necessary to use this method for typical applications. The parameters \a preAllocation and \a postAllocation control whether pre- and/or post allocation should be freed, respectively. */ template void QCPDataContainer::squeeze(bool preAllocation, bool postAllocation) { if (preAllocation) { if (mPreallocSize > 0) { std::copy(begin(), end(), mData.begin()); mData.resize(size()); mPreallocSize = 0; } mPreallocIteration = 0; } if (postAllocation) mData.squeeze(); } /*! Returns an iterator to the data point with a (sort-)key that is equal to, just below, or just above \a sortKey. If \a expandedRange is true, the data point just below \a sortKey will be considered, otherwise the one just above. This can be used in conjunction with \ref findEnd to iterate over data points within a given key range, including or excluding the bounding data points that are just beyond the specified range. If \a expandedRange is true but there are no data points below \a sortKey, \ref constBegin is returned. If the container is empty, returns \ref constEnd. \see findEnd, QCPPlottableInterface1D::findBegin */ template typename QCPDataContainer::const_iterator QCPDataContainer::findBegin(double sortKey, bool expandedRange) const { if (isEmpty()) return constEnd(); QCPDataContainer::const_iterator it = std::lower_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); if (expandedRange && it != constBegin()) // also covers it == constEnd case, and we know --constEnd is valid because mData isn't empty --it; return it; } /*! Returns an iterator to the element after the data point with a (sort-)key that is equal to, just above or just below \a sortKey. If \a expandedRange is true, the data point just above \a sortKey will be considered, otherwise the one just below. This can be used in conjunction with \ref findBegin to iterate over data points within a given key range, including the bounding data points that are just below and above the specified range. If \a expandedRange is true but there are no data points above \a sortKey, \ref constEnd is returned. If the container is empty, \ref constEnd is returned. \see findBegin, QCPPlottableInterface1D::findEnd */ template typename QCPDataContainer::const_iterator QCPDataContainer::findEnd(double sortKey, bool expandedRange) const { if (isEmpty()) return constEnd(); QCPDataContainer::const_iterator it = std::upper_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); if (expandedRange && it != constEnd()) ++it; return it; } /*! Returns the range encompassed by the (main-)key coordinate of all data points. The output parameter \a foundRange indicates whether a sensible range was found. If this is false, you should not use the returned QCPRange (e.g. the data container is empty or all points have the same key). Use \a signDomain to control which sign of the key coordinates should be considered. This is relevant e.g. for logarithmic plots which can mathematically only display one sign domain at a time. If the DataType reports that its main key is equal to the sort key (\a sortKeyIsMainKey), as is the case for most plottables, this method uses this fact and finds the range very quickly. \see valueRange */ template QCPRange QCPDataContainer::keyRange(bool &foundRange, QCP::SignDomain signDomain) { if (isEmpty()) { foundRange = false; return QCPRange(); } QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPDataContainer::const_iterator it = constBegin(); QCPDataContainer::const_iterator itEnd = constEnd(); if (signDomain == QCP::sdBoth) // range may be anywhere { if (DataType::sortKeyIsMainKey()) // if DataType is sorted by main key (e.g. QCPGraph, but not QCPCurve), use faster algorithm by finding just first and last key with non-NaN value { while (it != itEnd) // find first non-nan going up from left { if (!qIsNaN(it->mainValue())) { range.lower = it->mainKey(); haveLower = true; break; } ++it; } it = itEnd; while (it != constBegin()) // find first non-nan going down from right { --it; if (!qIsNaN(it->mainValue())) { range.upper = it->mainKey(); haveUpper = true; break; } } } else // DataType is not sorted by main key, go through all data points and accordingly expand range { while (it != itEnd) { if (!qIsNaN(it->mainValue())) { current = it->mainKey(); if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } } } else if (signDomain == QCP::sdNegative) // range may only be in the negative sign domain { while (it != itEnd) { if (!qIsNaN(it->mainValue())) { current = it->mainKey(); if ((current < range.lower || !haveLower) && current < 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current < 0) { range.upper = current; haveUpper = true; } } ++it; } } else if (signDomain == QCP::sdPositive) // range may only be in the positive sign domain { while (it != itEnd) { if (!qIsNaN(it->mainValue())) { current = it->mainKey(); if ((current < range.lower || !haveLower) && current > 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current > 0) { range.upper = current; haveUpper = true; } } ++it; } } foundRange = haveLower && haveUpper; return range; } /*! Returns the range encompassed by the value coordinates of the data points in the specified key range (\a inKeyRange), using the full \a DataType::valueRange reported by the data points. The output parameter \a foundRange indicates whether a sensible range was found. If this is false, you should not use the returned QCPRange (e.g. the data container is empty or all points have the same value). If \a inKeyRange has both lower and upper bound set to zero (is equal to QCPRange()), all data points are considered, without any restriction on the keys. Use \a signDomain to control which sign of the value coordinates should be considered. This is relevant e.g. for logarithmic plots which can mathematically only display one sign domain at a time. \see keyRange */ template QCPRange QCPDataContainer::valueRange(bool &foundRange, QCP::SignDomain signDomain, const QCPRange &inKeyRange) { if (isEmpty()) { foundRange = false; return QCPRange(); } QCPRange range; const bool restrictKeyRange = inKeyRange != QCPRange(); bool haveLower = false; bool haveUpper = false; QCPRange current; QCPDataContainer::const_iterator itBegin = constBegin(); QCPDataContainer::const_iterator itEnd = constEnd(); if (DataType::sortKeyIsMainKey() && restrictKeyRange) { itBegin = findBegin(inKeyRange.lower, false); itEnd = findEnd(inKeyRange.upper, false); } if (signDomain == QCP::sdBoth) // range may be anywhere { for (QCPDataContainer::const_iterator it = itBegin; it != itEnd; ++it) { if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper)) continue; current = it->valueRange(); if ((current.lower < range.lower || !haveLower) && !qIsNaN(current.lower)) { range.lower = current.lower; haveLower = true; } if ((current.upper > range.upper || !haveUpper) && !qIsNaN(current.upper)) { range.upper = current.upper; haveUpper = true; } } } else if (signDomain == QCP::sdNegative) // range may only be in the negative sign domain { for (QCPDataContainer::const_iterator it = itBegin; it != itEnd; ++it) { if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper)) continue; current = it->valueRange(); if ((current.lower < range.lower || !haveLower) && current.lower < 0 && !qIsNaN(current.lower)) { range.lower = current.lower; haveLower = true; } if ((current.upper > range.upper || !haveUpper) && current.upper < 0 && !qIsNaN(current.upper)) { range.upper = current.upper; haveUpper = true; } } } else if (signDomain == QCP::sdPositive) // range may only be in the positive sign domain { for (QCPDataContainer::const_iterator it = itBegin; it != itEnd; ++it) { if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper)) continue; current = it->valueRange(); if ((current.lower < range.lower || !haveLower) && current.lower > 0 && !qIsNaN(current.lower)) { range.lower = current.lower; haveLower = true; } if ((current.upper > range.upper || !haveUpper) && current.upper > 0 && !qIsNaN(current.upper)) { range.upper = current.upper; haveUpper = true; } } } foundRange = haveLower && haveUpper; return range; } /*! Makes sure \a begin and \a end mark a data range that is both within the bounds of this data container's data, as well as within the specified \a dataRange. The initial range described by the passed iterators \a begin and \a end is never expanded, only contracted if necessary. This function doesn't require for \a dataRange to be within the bounds of this data container's valid range. */ template void QCPDataContainer::limitIteratorsToDataRange(const_iterator &begin, const_iterator &end, const QCPDataRange &dataRange) const { QCPDataRange iteratorRange(int(begin-constBegin()), int(end-constBegin())); iteratorRange = iteratorRange.bounded(dataRange.bounded(this->dataRange())); begin = constBegin()+iteratorRange.begin(); end = constBegin()+iteratorRange.end(); } /*! \internal Increases the preallocation pool to have a size of at least \a minimumPreallocSize. Depending on the preallocation history, the container will grow by more than requested, to speed up future consecutive size increases. if \a minimumPreallocSize is smaller than or equal to the current preallocation pool size, this method does nothing. */ template void QCPDataContainer::preallocateGrow(int minimumPreallocSize) { if (minimumPreallocSize <= mPreallocSize) return; int newPreallocSize = minimumPreallocSize; newPreallocSize += (1u< void QCPDataContainer::performAutoSqueeze() { const int totalAlloc = mData.capacity(); const int postAllocSize = totalAlloc-mData.size(); const int usedSize = size(); bool shrinkPostAllocation = false; bool shrinkPreAllocation = false; if (totalAlloc > 650000) // if allocation is larger, shrink earlier with respect to total used size { shrinkPostAllocation = postAllocSize > usedSize*1.5; // QVector grow strategy is 2^n for static data. Watch out not to oscillate! shrinkPreAllocation = mPreallocSize*10 > usedSize; } else if (totalAlloc > 1000) // below 10 MiB raw data be generous with preallocated memory, below 1k points don't even bother { shrinkPostAllocation = postAllocSize > usedSize*5; shrinkPreAllocation = mPreallocSize > usedSize*1.5; // preallocation can grow into postallocation, so can be smaller } if (shrinkPreAllocation || shrinkPostAllocation) squeeze(shrinkPreAllocation, shrinkPostAllocation); } /* end of 'src/datacontainer.h' */ /* including file 'src/plottable.h' */ /* modified 2021-03-29T02:30:44, size 8461 */ class QCP_LIB_DECL QCPSelectionDecorator { Q_GADGET public: QCPSelectionDecorator(); virtual ~QCPSelectionDecorator(); // getters: QPen pen() const { return mPen; } QBrush brush() const { return mBrush; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } QCPScatterStyle::ScatterProperties usedScatterProperties() const { return mUsedScatterProperties; } // setters: void setPen(const QPen &pen); void setBrush(const QBrush &brush); void setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties=QCPScatterStyle::spPen); void setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties); // non-virtual methods: void applyPen(QCPPainter *painter) const; void applyBrush(QCPPainter *painter) const; QCPScatterStyle getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const; // introduced virtual methods: virtual void copyFrom(const QCPSelectionDecorator *other); virtual void drawDecoration(QCPPainter *painter, QCPDataSelection selection); protected: // property members: QPen mPen; QBrush mBrush; QCPScatterStyle mScatterStyle; QCPScatterStyle::ScatterProperties mUsedScatterProperties; // non-property members: QCPAbstractPlottable *mPlottable; // introduced virtual methods: virtual bool registerWithPlottable(QCPAbstractPlottable *plottable); private: Q_DISABLE_COPY(QCPSelectionDecorator) friend class QCPAbstractPlottable; }; Q_DECLARE_METATYPE(QCPSelectionDecorator*) class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) Q_PROPERTY(QCP::SelectionType selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(QCPDataSelection selection READ selection WRITE setSelection NOTIFY selectionChanged) Q_PROPERTY(QCPSelectionDecorator* selectionDecorator READ selectionDecorator WRITE setSelectionDecorator) /// \endcond public: QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPAbstractPlottable() Q_DECL_OVERRIDE; // getters: QString name() const { return mName; } bool antialiasedFill() const { return mAntialiasedFill; } bool antialiasedScatters() const { return mAntialiasedScatters; } QPen pen() const { return mPen; } QBrush brush() const { return mBrush; } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } QCP::SelectionType selectable() const { return mSelectable; } bool selected() const { return !mSelection.isEmpty(); } QCPDataSelection selection() const { return mSelection; } QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; } // setters: void setName(const QString &name); void setAntialiasedFill(bool enabled); void setAntialiasedScatters(bool enabled); void setPen(const QPen &pen); void setBrush(const QBrush &brush); void setKeyAxis(QCPAxis *axis); void setValueAxis(QCPAxis *axis); Q_SLOT void setSelectable(QCP::SelectionType selectable); Q_SLOT void setSelection(QCPDataSelection selection); void setSelectionDecorator(QCPSelectionDecorator *decorator); // introduced virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables virtual QCPPlottableInterface1D *interface1D() { return nullptr; } virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const = 0; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const = 0; // non-property methods: void coordsToPixels(double key, double value, double &x, double &y) const; const QPointF coordsToPixels(double key, double value) const; void pixelsToCoords(double x, double y, double &key, double &value) const; void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; void rescaleAxes(bool onlyEnlarge=false) const; void rescaleKeyAxis(bool onlyEnlarge=false) const; void rescaleValueAxis(bool onlyEnlarge=false, bool inKeyRange=false) const; bool addToLegend(QCPLegend *legend); bool addToLegend(); bool removeFromLegend(QCPLegend *legend) const; bool removeFromLegend() const; signals: void selectionChanged(bool selected); void selectionChanged(const QCPDataSelection &selection); void selectableChanged(QCP::SelectionType selectable); protected: // property members: QString mName; bool mAntialiasedFill, mAntialiasedScatters; QPen mPen; QBrush mBrush; QPointer mKeyAxis, mValueAxis; QCP::SelectionType mSelectable; QCPDataSelection mSelection; QCPSelectionDecorator *mSelectionDecorator; // reimplemented virtual methods: virtual QRect clipRect() const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0; virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // introduced virtual methods: virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; // non-virtual methods: void applyFillAntialiasingHint(QCPPainter *painter) const; void applyScattersAntialiasingHint(QCPPainter *painter) const; private: Q_DISABLE_COPY(QCPAbstractPlottable) friend class QCustomPlot; friend class QCPAxis; friend class QCPPlottableLegendItem; }; /* end of 'src/plottable.h' */ /* including file 'src/item.h' */ /* modified 2021-03-29T02:30:44, size 9425 */ class QCP_LIB_DECL QCPItemAnchor { Q_GADGET public: QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId=-1); virtual ~QCPItemAnchor(); // getters: QString name() const { return mName; } virtual QPointF pixelPosition() const; protected: // property members: QString mName; // non-property members: QCustomPlot *mParentPlot; QCPAbstractItem *mParentItem; int mAnchorId; QSet mChildrenX, mChildrenY; // introduced virtual methods: virtual QCPItemPosition *toQCPItemPosition() { return nullptr; } // non-virtual methods: void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted private: Q_DISABLE_COPY(QCPItemAnchor) friend class QCPItemPosition; }; class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { Q_GADGET public: /*! Defines the ways an item position can be specified. Thus it defines what the numbers passed to \ref setCoords actually mean. \see setType */ enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the viewport/widget, etc. ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). }; Q_ENUMS(PositionType) QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name); virtual ~QCPItemPosition() Q_DECL_OVERRIDE; // getters: PositionType type() const { return typeX(); } PositionType typeX() const { return mPositionTypeX; } PositionType typeY() const { return mPositionTypeY; } QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } double key() const { return mKey; } double value() const { return mValue; } QPointF coords() const { return QPointF(mKey, mValue); } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } QCPAxisRect *axisRect() const; virtual QPointF pixelPosition() const Q_DECL_OVERRIDE; // setters: void setType(PositionType type); void setTypeX(PositionType type); void setTypeY(PositionType type); bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); void setCoords(double key, double value); void setCoords(const QPointF &pos); void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); void setAxisRect(QCPAxisRect *axisRect); void setPixelPosition(const QPointF &pixelPosition); protected: // property members: PositionType mPositionTypeX, mPositionTypeY; QPointer mKeyAxis, mValueAxis; QPointer mAxisRect; double mKey, mValue; QCPItemAnchor *mParentAnchorX, *mParentAnchorY; // reimplemented virtual methods: virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } private: Q_DISABLE_COPY(QCPItemPosition) }; Q_DECLARE_METATYPE(QCPItemPosition::PositionType) class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: explicit QCPAbstractItem(QCustomPlot *parentPlot); virtual ~QCPAbstractItem() Q_DECL_OVERRIDE; // getters: bool clipToAxisRect() const { return mClipToAxisRect; } QCPAxisRect *clipAxisRect() const; bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setClipToAxisRect(bool clip); void setClipAxisRect(QCPAxisRect *rect); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0; // non-virtual methods: QList positions() const { return mPositions; } QList anchors() const { return mAnchors; } QCPItemPosition *position(const QString &name) const; QCPItemAnchor *anchor(const QString &name) const; bool hasAnchor(const QString &name) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: bool mClipToAxisRect; QPointer mClipAxisRect; QList mPositions; QList mAnchors; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; virtual QRect clipRect() const Q_DECL_OVERRIDE; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // introduced virtual methods: virtual QPointF anchorPixelPosition(int anchorId) const; // non-virtual methods: double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; QCPItemPosition *createPosition(const QString &name); QCPItemAnchor *createAnchor(const QString &name, int anchorId); private: Q_DISABLE_COPY(QCPAbstractItem) friend class QCustomPlot; friend class QCPItemAnchor; }; /* end of 'src/item.h' */ /* including file 'src/core.h' */ /* modified 2021-03-29T02:30:44, size 19304 */ class QCP_LIB_DECL QCustomPlot : public QWidget { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) Q_PROPERTY(bool openGl READ openGl WRITE setOpenGl) /// \endcond public: /*! Defines how a layer should be inserted relative to an other layer. \see addLayer, moveLayer */ enum LayerInsertMode { limBelow ///< Layer is inserted below other layer ,limAbove ///< Layer is inserted above other layer }; Q_ENUMS(LayerInsertMode) /*! Defines with what timing the QCustomPlot surface is refreshed after a replot. \see replot */ enum RefreshPriority { rpImmediateRefresh ///< Replots immediately and repaints the widget immediately by calling QWidget::repaint() after the replot ,rpQueuedRefresh ///< Replots immediately, but queues the widget repaint, by calling QWidget::update() after the replot. This way multiple redundant widget repaints can be avoided. ,rpRefreshHint ///< Whether to use immediate or queued refresh depends on whether the plotting hint \ref QCP::phImmediateRefresh is set, see \ref setPlottingHints. ,rpQueuedReplot ///< Queues the entire replot for the next event loop iteration. This way multiple redundant replots can be avoided. The actual replot is then done with \ref rpRefreshHint priority. }; Q_ENUMS(RefreshPriority) explicit QCustomPlot(QWidget *parent = nullptr); virtual ~QCustomPlot() Q_DECL_OVERRIDE; // getters: QRect viewport() const { return mViewport; } double bufferDevicePixelRatio() const { return mBufferDevicePixelRatio; } QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } QCPLayoutGrid *plotLayout() const { return mPlotLayout; } QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } const QCP::Interactions interactions() const { return mInteractions; } int selectionTolerance() const { return mSelectionTolerance; } bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } QCP::PlottingHints plottingHints() const { return mPlottingHints; } Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } QCP::SelectionRectMode selectionRectMode() const { return mSelectionRectMode; } QCPSelectionRect *selectionRect() const { return mSelectionRect; } bool openGl() const { return mOpenGl; } // setters: void setViewport(const QRect &rect); void setBufferDevicePixelRatio(double ratio); void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); void setAutoAddPlottableToLegend(bool on); void setInteractions(const QCP::Interactions &interactions); void setInteraction(const QCP::Interaction &interaction, bool enabled=true); void setSelectionTolerance(int pixels); void setNoAntialiasingOnDrag(bool enabled); void setPlottingHints(const QCP::PlottingHints &hints); void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); void setMultiSelectModifier(Qt::KeyboardModifier modifier); void setSelectionRectMode(QCP::SelectionRectMode mode); void setSelectionRect(QCPSelectionRect *selectionRect); void setOpenGl(bool enabled, int multisampling=16); // non-property methods: // plottable interface: QCPAbstractPlottable *plottable(int index); QCPAbstractPlottable *plottable(); bool removePlottable(QCPAbstractPlottable *plottable); bool removePlottable(int index); int clearPlottables(); int plottableCount() const; QList selectedPlottables() const; template PlottableType *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const; QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const; bool hasPlottable(QCPAbstractPlottable *plottable) const; // specialized interface for QCPGraph: QCPGraph *graph(int index) const; QCPGraph *graph() const; QCPGraph *addGraph(QCPAxis *keyAxis=nullptr, QCPAxis *valueAxis=nullptr); bool removeGraph(QCPGraph *graph); bool removeGraph(int index); int clearGraphs(); int graphCount() const; QList selectedGraphs() const; // item interface: QCPAbstractItem *item(int index) const; QCPAbstractItem *item() const; bool removeItem(QCPAbstractItem *item); bool removeItem(int index); int clearItems(); int itemCount() const; QList selectedItems() const; template ItemType *itemAt(const QPointF &pos, bool onlySelectable=false) const; QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; bool hasItem(QCPAbstractItem *item) const; // layer interface: QCPLayer *layer(const QString &name) const; QCPLayer *layer(int index) const; QCPLayer *currentLayer() const; bool setCurrentLayer(const QString &name); bool setCurrentLayer(QCPLayer *layer); int layerCount() const; bool addLayer(const QString &name, QCPLayer *otherLayer=nullptr, LayerInsertMode insertMode=limAbove); bool removeLayer(QCPLayer *layer); bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); // axis rect/layout interface: int axisRectCount() const; QCPAxisRect* axisRect(int index=0) const; QList axisRects() const; QCPLayoutElement* layoutElementAt(const QPointF &pos) const; QCPAxisRect* axisRectAt(const QPointF &pos) const; Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); QList selectedAxes() const; QList selectedLegends() const; Q_SLOT void deselectAll(); bool savePdf(const QString &fileName, int width=0, int height=0, QCP::ExportPen exportPen=QCP::epAllowCosmetic, const QString &pdfCreator=QString(), const QString &pdfTitle=QString()); bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); QPixmap toPixmap(int width=0, int height=0, double scale=1.0); void toPainter(QCPPainter *painter, int width=0, int height=0); Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpRefreshHint); double replotTime(bool average=false) const; QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; QCPLegend *legend; signals: void mouseDoubleClick(QMouseEvent *event); void mousePress(QMouseEvent *event); void mouseMove(QMouseEvent *event); void mouseRelease(QMouseEvent *event); void mouseWheel(QWheelEvent *event); void plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event); void plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event); void itemClick(QCPAbstractItem *item, QMouseEvent *event); void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void selectionChangedByUser(); void beforeReplot(); void afterLayout(); void afterReplot(); protected: // property members: QRect mViewport; double mBufferDevicePixelRatio; QCPLayoutGrid *mPlotLayout; bool mAutoAddPlottableToLegend; QList mPlottables; QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph QList mItems; QList mLayers; QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; QCP::Interactions mInteractions; int mSelectionTolerance; bool mNoAntialiasingOnDrag; QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayer *mCurrentLayer; QCP::PlottingHints mPlottingHints; Qt::KeyboardModifier mMultiSelectModifier; QCP::SelectionRectMode mSelectionRectMode; QCPSelectionRect *mSelectionRect; bool mOpenGl; // non-property members: QList > mPaintBuffers; QPoint mMousePressPos; bool mMouseHasMoved; QPointer mMouseEventLayerable; QPointer mMouseSignalLayerable; QVariant mMouseEventLayerableDetails; QVariant mMouseSignalLayerableDetails; bool mReplotting; bool mReplotQueued; double mReplotTime, mReplotTimeAverage; int mOpenGlMultisamples; QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; bool mOpenGlCacheLabelsBackup; #ifdef QCP_OPENGL_FBO QSharedPointer mGlContext; QSharedPointer mGlSurface; QSharedPointer mGlPaintDevice; #endif // reimplemented virtual methods: virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE; virtual QSize sizeHint() const Q_DECL_OVERRIDE; virtual void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; virtual void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; virtual void mouseDoubleClickEvent(QMouseEvent *event) Q_DECL_OVERRIDE; virtual void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; virtual void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; // introduced virtual methods: virtual void draw(QCPPainter *painter); virtual void updateLayout(); virtual void axisRemoved(QCPAxis *axis); virtual void legendRemoved(QCPLegend *legend); Q_SLOT virtual void processRectSelection(QRect rect, QMouseEvent *event); Q_SLOT virtual void processRectZoom(QRect rect, QMouseEvent *event); Q_SLOT virtual void processPointSelection(QMouseEvent *event); // non-virtual methods: bool registerPlottable(QCPAbstractPlottable *plottable); bool registerGraph(QCPGraph *graph); bool registerItem(QCPAbstractItem* item); void updateLayerIndices() const; QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=nullptr) const; QList layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails=nullptr) const; void drawBackground(QCPPainter *painter); void setupPaintBuffers(); QCPAbstractPaintBuffer *createPaintBuffer(); bool hasInvalidatedPaintBuffers(); bool setupOpenGl(); void freeOpenGl(); friend class QCPLegend; friend class QCPAxis; friend class QCPLayer; friend class QCPAxisRect; friend class QCPAbstractPlottable; friend class QCPGraph; friend class QCPAbstractItem; }; Q_DECLARE_METATYPE(QCustomPlot::LayerInsertMode) Q_DECLARE_METATYPE(QCustomPlot::RefreshPriority) // implementation of template functions: /*! Returns the plottable at the pixel position \a pos. The plottable type (a QCPAbstractPlottable subclass) that shall be taken into consideration can be specified via the template parameter. Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. if \a dataIndex is non-null, it is set to the index of the plottable's data point that is closest to \a pos. If there is no plottable of the specified type at \a pos, returns \c nullptr. \see itemAt, layoutElementAt */ template PlottableType *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const { PlottableType *resultPlottable = 0; QVariant resultDetails; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractPlottable *plottable, mPlottables) { PlottableType *currentPlottable = qobject_cast(plottable); if (!currentPlottable || (onlySelectable && !currentPlottable->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractPlottable::selectable continue; if (currentPlottable->clipRect().contains(pos.toPoint())) // only consider clicks where the plottable is actually visible { QVariant details; double currentDistance = currentPlottable->selectTest(pos, false, dataIndex ? &details : nullptr); if (currentDistance >= 0 && currentDistance < resultDistance) { resultPlottable = currentPlottable; resultDetails = details; resultDistance = currentDistance; } } } if (resultPlottable && dataIndex) { QCPDataSelection sel = resultDetails.value(); if (!sel.isEmpty()) *dataIndex = sel.dataRange(0).begin(); } return resultPlottable; } /*! Returns the item at the pixel position \a pos. The item type (a QCPAbstractItem subclass) that shall be taken into consideration can be specified via the template parameter. Items that only consist of single lines (e.g. \ref QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. If there is no item at \a pos, returns \c nullptr. \see plottableAt, layoutElementAt */ template ItemType *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { ItemType *resultItem = 0; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractItem *item, mItems) { ItemType *currentItem = qobject_cast(item); if (!currentItem || (onlySelectable && !currentItem->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable continue; if (!currentItem->clipToAxisRect() || currentItem->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it { double currentDistance = currentItem->selectTest(pos, false); if (currentDistance >= 0 && currentDistance < resultDistance) { resultItem = currentItem; resultDistance = currentDistance; } } } return resultItem; } /* end of 'src/core.h' */ /* including file 'src/plottable1d.h' */ /* modified 2021-03-29T02:30:44, size 25638 */ class QCPPlottableInterface1D { public: virtual ~QCPPlottableInterface1D() = default; // introduced pure virtual methods: virtual int dataCount() const = 0; virtual double dataMainKey(int index) const = 0; virtual double dataSortKey(int index) const = 0; virtual double dataMainValue(int index) const = 0; virtual QCPRange dataValueRange(int index) const = 0; virtual QPointF dataPixelPosition(int index) const = 0; virtual bool sortKeyIsMainKey() const = 0; virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const = 0; virtual int findBegin(double sortKey, bool expandedRange=true) const = 0; virtual int findEnd(double sortKey, bool expandedRange=true) const = 0; }; template class QCPAbstractPlottable1D : public QCPAbstractPlottable, public QCPPlottableInterface1D // no QCP_LIB_DECL, template class ends up in header (cpp included below) { // No Q_OBJECT macro due to template class public: QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPAbstractPlottable1D() Q_DECL_OVERRIDE; // virtual methods of 1d plottable interface: virtual int dataCount() const Q_DECL_OVERRIDE; virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; } protected: // property members: QSharedPointer > mDataContainer; // helpers for subclasses: void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; void drawPolyline(QCPPainter *painter, const QVector &lineData) const; private: Q_DISABLE_COPY(QCPAbstractPlottable1D) }; // include implementation in header since it is a class template: //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlottableInterface1D //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlottableInterface1D \brief Defines an abstract interface for one-dimensional plottables This class contains only pure virtual methods which define a common interface to the data of one-dimensional plottables. For example, it is implemented by the template class \ref QCPAbstractPlottable1D (the preferred base class for one-dimensional plottables). So if you use that template class as base class of your one-dimensional plottable, you won't have to care about implementing the 1d interface yourself. If your plottable doesn't derive from \ref QCPAbstractPlottable1D but still wants to provide a 1d interface (e.g. like \ref QCPErrorBars does), you should inherit from both \ref QCPAbstractPlottable and \ref QCPPlottableInterface1D and accordingly reimplement the pure virtual methods of the 1d interface, matching your data container. Also, reimplement \ref QCPAbstractPlottable::interface1D to return the \c this pointer. If you have a \ref QCPAbstractPlottable pointer, you can check whether it implements this interface by calling \ref QCPAbstractPlottable::interface1D and testing it for a non-zero return value. If it indeed implements this interface, you may use it to access the plottable's data without needing to know the exact type of the plottable or its data point type. */ /* start documentation of pure virtual functions */ /*! \fn virtual int QCPPlottableInterface1D::dataCount() const = 0; Returns the number of data points of the plottable. */ /*! \fn virtual QCPDataSelection QCPPlottableInterface1D::selectTestRect(const QRectF &rect, bool onlySelectable) const = 0; Returns a data selection containing all the data points of this plottable which are contained (or hit by) \a rect. This is used mainly in the selection rect interaction for data selection (\ref dataselection "data selection mechanism"). If \a onlySelectable is true, an empty QCPDataSelection is returned if this plottable is not selectable (i.e. if \ref QCPAbstractPlottable::setSelectable is \ref QCP::stNone). \note \a rect must be a normalized rect (positive or zero width and height). This is especially important when using the rect of \ref QCPSelectionRect::accepted, which is not necessarily normalized. Use QRect::normalized() when passing a rect which might not be normalized. */ /*! \fn virtual double QCPPlottableInterface1D::dataMainKey(int index) const = 0 Returns the main key of the data point at the given \a index. What the main key is, is defined by the plottable's data type. See the \ref qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming convention. */ /*! \fn virtual double QCPPlottableInterface1D::dataSortKey(int index) const = 0 Returns the sort key of the data point at the given \a index. What the sort key is, is defined by the plottable's data type. See the \ref qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming convention. */ /*! \fn virtual double QCPPlottableInterface1D::dataMainValue(int index) const = 0 Returns the main value of the data point at the given \a index. What the main value is, is defined by the plottable's data type. See the \ref qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming convention. */ /*! \fn virtual QCPRange QCPPlottableInterface1D::dataValueRange(int index) const = 0 Returns the value range of the data point at the given \a index. What the value range is, is defined by the plottable's data type. See the \ref qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming convention. */ /*! \fn virtual QPointF QCPPlottableInterface1D::dataPixelPosition(int index) const = 0 Returns the pixel position on the widget surface at which the data point at the given \a index appears. Usually this corresponds to the point of \ref dataMainKey/\ref dataMainValue, in pixel coordinates. However, depending on the plottable, this might be a different apparent position than just a coord-to-pixel transform of those values. For example, \ref QCPBars apparent data values can be shifted depending on their stacking, bar grouping or configured base value. */ /*! \fn virtual bool QCPPlottableInterface1D::sortKeyIsMainKey() const = 0 Returns whether the sort key (\ref dataSortKey) is identical to the main key (\ref dataMainKey). What the sort and main keys are, is defined by the plottable's data type. See the \ref qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming convention. */ /*! \fn virtual int QCPPlottableInterface1D::findBegin(double sortKey, bool expandedRange) const = 0 Returns the index of the data point with a (sort-)key that is equal to, just below, or just above \a sortKey. If \a expandedRange is true, the data point just below \a sortKey will be considered, otherwise the one just above. This can be used in conjunction with \ref findEnd to iterate over data points within a given key range, including or excluding the bounding data points that are just beyond the specified range. If \a expandedRange is true but there are no data points below \a sortKey, 0 is returned. If the container is empty, returns 0 (in that case, \ref findEnd will also return 0, so a loop using these methods will not iterate over the index 0). \see findEnd, QCPDataContainer::findBegin */ /*! \fn virtual int QCPPlottableInterface1D::findEnd(double sortKey, bool expandedRange) const = 0 Returns the index one after the data point with a (sort-)key that is equal to, just above, or just below \a sortKey. If \a expandedRange is true, the data point just above \a sortKey will be considered, otherwise the one just below. This can be used in conjunction with \ref findBegin to iterate over data points within a given key range, including the bounding data points that are just below and above the specified range. If \a expandedRange is true but there are no data points above \a sortKey, the index just above the highest data point is returned. If the container is empty, returns 0. \see findBegin, QCPDataContainer::findEnd */ /* end documentation of pure virtual functions */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractPlottable1D //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractPlottable1D \brief A template base class for plottables with one-dimensional data This template class derives from \ref QCPAbstractPlottable and from the abstract interface \ref QCPPlottableInterface1D. It serves as a base class for all one-dimensional data (i.e. data with one key dimension), such as \ref QCPGraph and QCPCurve. The template parameter \a DataType is the type of the data points of this plottable (e.g. \ref QCPGraphData or \ref QCPCurveData). The main purpose of this base class is to provide the member \a mDataContainer (a shared pointer to a \ref QCPDataContainer "QCPDataContainer") and implement the according virtual methods of the \ref QCPPlottableInterface1D, such that most subclassed plottables don't need to worry about this anymore. Further, it provides a convenience method for retrieving selected/unselected data segments via \ref getDataSegments. This is useful when subclasses implement their \ref draw method and need to draw selected segments with a different pen/brush than unselected segments (also see \ref QCPSelectionDecorator). This class implements basic functionality of \ref QCPAbstractPlottable::selectTest and \ref QCPPlottableInterface1D::selectTestRect, assuming point-like data points, based on the 1D data interface. In spite of that, most plottable subclasses will want to reimplement those methods again, to provide a more accurate hit test based on their specific data visualization geometry. */ /* start documentation of inline functions */ /*! \fn QCPPlottableInterface1D *QCPAbstractPlottable1D::interface1D() Returns a \ref QCPPlottableInterface1D pointer to this plottable, providing access to its 1D interface. \seebaseclassmethod */ /* end documentation of inline functions */ /*! Forwards \a keyAxis and \a valueAxis to the \ref QCPAbstractPlottable::QCPAbstractPlottable "QCPAbstractPlottable" constructor and allocates the \a mDataContainer. */ template QCPAbstractPlottable1D::QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mDataContainer(new QCPDataContainer) { } template QCPAbstractPlottable1D::~QCPAbstractPlottable1D() { } /*! \copydoc QCPPlottableInterface1D::dataCount */ template int QCPAbstractPlottable1D::dataCount() const { return mDataContainer->size(); } /*! \copydoc QCPPlottableInterface1D::dataMainKey */ template double QCPAbstractPlottable1D::dataMainKey(int index) const { if (index >= 0 && index < mDataContainer->size()) { return (mDataContainer->constBegin()+index)->mainKey(); } else { qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; return 0; } } /*! \copydoc QCPPlottableInterface1D::dataSortKey */ template double QCPAbstractPlottable1D::dataSortKey(int index) const { if (index >= 0 && index < mDataContainer->size()) { return (mDataContainer->constBegin()+index)->sortKey(); } else { qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; return 0; } } /*! \copydoc QCPPlottableInterface1D::dataMainValue */ template double QCPAbstractPlottable1D::dataMainValue(int index) const { if (index >= 0 && index < mDataContainer->size()) { return (mDataContainer->constBegin()+index)->mainValue(); } else { qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; return 0; } } /*! \copydoc QCPPlottableInterface1D::dataValueRange */ template QCPRange QCPAbstractPlottable1D::dataValueRange(int index) const { if (index >= 0 && index < mDataContainer->size()) { return (mDataContainer->constBegin()+index)->valueRange(); } else { qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; return QCPRange(0, 0); } } /*! \copydoc QCPPlottableInterface1D::dataPixelPosition */ template QPointF QCPAbstractPlottable1D::dataPixelPosition(int index) const { if (index >= 0 && index < mDataContainer->size()) { const typename QCPDataContainer::const_iterator it = mDataContainer->constBegin()+index; return coordsToPixels(it->mainKey(), it->mainValue()); } else { qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; return QPointF(); } } /*! \copydoc QCPPlottableInterface1D::sortKeyIsMainKey */ template bool QCPAbstractPlottable1D::sortKeyIsMainKey() const { return DataType::sortKeyIsMainKey(); } /*! Implements a rect-selection algorithm assuming the data (accessed via the 1D data interface) is point-like. Most subclasses will want to reimplement this method again, to provide a more accurate hit test based on the true data visualization geometry. \seebaseclassmethod */ template QCPDataSelection QCPAbstractPlottable1D::selectTestRect(const QRectF &rect, bool onlySelectable) const { QCPDataSelection result; if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return result; if (!mKeyAxis || !mValueAxis) return result; // convert rect given in pixels to ranges given in plot coordinates: double key1, value1, key2, value2; pixelsToCoords(rect.topLeft(), key1, value1); pixelsToCoords(rect.bottomRight(), key2, value2); QCPRange keyRange(key1, key2); // QCPRange normalizes internally so we don't have to care about whether key1 < key2 QCPRange valueRange(value1, value2); typename QCPDataContainer::const_iterator begin = mDataContainer->constBegin(); typename QCPDataContainer::const_iterator end = mDataContainer->constEnd(); if (DataType::sortKeyIsMainKey()) // we can assume that data is sorted by main key, so can reduce the searched key interval: { begin = mDataContainer->findBegin(keyRange.lower, false); end = mDataContainer->findEnd(keyRange.upper, false); } if (begin == end) return result; int currentSegmentBegin = -1; // -1 means we're currently not in a segment that's contained in rect for (typename QCPDataContainer::const_iterator it=begin; it!=end; ++it) { if (currentSegmentBegin == -1) { if (valueRange.contains(it->mainValue()) && keyRange.contains(it->mainKey())) // start segment currentSegmentBegin = int(it-mDataContainer->constBegin()); } else if (!valueRange.contains(it->mainValue()) || !keyRange.contains(it->mainKey())) // segment just ended { result.addDataRange(QCPDataRange(currentSegmentBegin, int(it-mDataContainer->constBegin())), false); currentSegmentBegin = -1; } } // process potential last segment: if (currentSegmentBegin != -1) result.addDataRange(QCPDataRange(currentSegmentBegin, int(end-mDataContainer->constBegin())), false); result.simplify(); return result; } /*! \copydoc QCPPlottableInterface1D::findBegin */ template int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRange) const { return int(mDataContainer->findBegin(sortKey, expandedRange)-mDataContainer->constBegin()); } /*! \copydoc QCPPlottableInterface1D::findEnd */ template int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange) const { return int(mDataContainer->findEnd(sortKey, expandedRange)-mDataContainer->constBegin()); } /*! Implements a point-selection algorithm assuming the data (accessed via the 1D data interface) is point-like. Most subclasses will want to reimplement this method again, to provide a more accurate hit test based on the true data visualization geometry. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. \seebaseclassmethod */ template double QCPAbstractPlottable1D::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) return -1; QCPDataSelection selectionResult; double minDistSqr = (std::numeric_limits::max)(); int minDistIndex = mDataContainer->size(); typename QCPDataContainer::const_iterator begin = mDataContainer->constBegin(); typename QCPDataContainer::const_iterator end = mDataContainer->constEnd(); if (DataType::sortKeyIsMainKey()) // we can assume that data is sorted by main key, so can reduce the searched key interval: { // determine which key range comes into question, taking selection tolerance around pos into account: double posKeyMin, posKeyMax, dummy; pixelsToCoords(pos-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy); pixelsToCoords(pos+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy); if (posKeyMin > posKeyMax) qSwap(posKeyMin, posKeyMax); begin = mDataContainer->findBegin(posKeyMin, true); end = mDataContainer->findEnd(posKeyMax, true); } if (begin == end) return -1; QCPRange keyRange(mKeyAxis->range()); QCPRange valueRange(mValueAxis->range()); for (typename QCPDataContainer::const_iterator it=begin; it!=end; ++it) { const double mainKey = it->mainKey(); const double mainValue = it->mainValue(); if (keyRange.contains(mainKey) && valueRange.contains(mainValue)) // make sure data point is inside visible range, for speedup in cases where sort key isn't main key and we iterate over all points { const double currentDistSqr = QCPVector2D(coordsToPixels(mainKey, mainValue)-pos).lengthSquared(); if (currentDistSqr < minDistSqr) { minDistSqr = currentDistSqr; minDistIndex = int(it-mDataContainer->constBegin()); } } } if (minDistIndex != mDataContainer->size()) selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex+1), false); selectionResult.simplify(); if (details) details->setValue(selectionResult); return qSqrt(minDistSqr); } /*! Splits all data into selected and unselected segments and outputs them via \a selectedSegments and \a unselectedSegments, respectively. This is useful when subclasses implement their \ref draw method and need to draw selected segments with a different pen/brush than unselected segments (also see \ref QCPSelectionDecorator). \see setSelection */ template void QCPAbstractPlottable1D::getDataSegments(QList &selectedSegments, QList &unselectedSegments) const { selectedSegments.clear(); unselectedSegments.clear(); if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty { if (selected()) selectedSegments << QCPDataRange(0, dataCount()); else unselectedSegments << QCPDataRange(0, dataCount()); } else { QCPDataSelection sel(selection()); sel.simplify(); selectedSegments = sel.dataRanges(); unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges(); } } /*! A helper method which draws a line with the passed \a painter, according to the pixel data in \a lineData. NaN points create gaps in the line, as expected from QCustomPlot's plottables (this is the main difference to QPainter's regular drawPolyline, which handles NaNs by lagging or crashing). Further it uses a faster line drawing technique based on \ref QCPPainter::drawLine rather than \c QPainter::drawPolyline if the configured \ref QCustomPlot::setPlottingHints() and \a painter style allows. */ template void QCPAbstractPlottable1D::drawPolyline(QCPPainter *painter, const QVector &lineData) const { // if drawing lines in plot (instead of PDF), reduce 1px lines to cosmetic, because at least in // Qt6 drawing of "1px" width lines is much slower even though it has same appearance apart from // High-DPI. In High-DPI cases people must set a pen width slightly larger than 1.0 to get // correct DPI scaling of width, but of course with performance penalty. if (!painter->modes().testFlag(QCPPainter::pmVectorized) && qFuzzyCompare(painter->pen().widthF(), 1.0)) { QPen newPen = painter->pen(); newPen.setWidth(0); painter->setPen(newPen); } // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { int i = 0; bool lastIsNan = false; const int lineDataSize = lineData.size(); while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN ++i; ++i; // because drawing works in 1 point retrospect while (i < lineDataSize) { if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line { if (!lastIsNan) painter->drawLine(lineData.at(i-1), lineData.at(i)); else lastIsNan = false; } else lastIsNan = true; ++i; } } else { int segmentStart = 0; int i = 0; const int lineDataSize = lineData.size(); while (i < lineDataSize) { if (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()) || qIsInf(lineData.at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block { painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point segmentStart = i+1; } ++i; } // draw last segment: painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart); } } /* end of 'src/plottable1d.h' */ /* including file 'src/colorgradient.h' */ /* modified 2021-03-29T02:30:44, size 7262 */ class QCP_LIB_DECL QCPColorGradient { Q_GADGET public: /*! Defines the color spaces in which color interpolation between gradient stops can be performed. \see setColorInterpolation */ enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) }; Q_ENUMS(ColorInterpolation) /*! Defines how NaN data points shall appear in the plot. \see setNanHandling, setNanColor */ enum NanHandling { nhNone ///< NaN data points are not explicitly handled and shouldn't occur in the data (this gives slight performance improvement) ,nhLowestColor ///< NaN data points appear as the lowest color defined in this QCPColorGradient ,nhHighestColor ///< NaN data points appear as the highest color defined in this QCPColorGradient ,nhTransparent ///< NaN data points appear transparent ,nhNanColor ///< NaN data points appear as the color defined with \ref setNanColor }; Q_ENUMS(NanHandling) /*! Defines the available presets that can be loaded with \ref loadPreset. See the documentation there for an image of the presets. */ enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) ,gpCandy ///< Blue over pink to white ,gpGeography ///< Colors suitable to represent different elevations on geographical maps ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) }; Q_ENUMS(GradientPreset) QCPColorGradient(); QCPColorGradient(GradientPreset preset); bool operator==(const QCPColorGradient &other) const; bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } // getters: int levelCount() const { return mLevelCount; } QMap colorStops() const { return mColorStops; } ColorInterpolation colorInterpolation() const { return mColorInterpolation; } NanHandling nanHandling() const { return mNanHandling; } QColor nanColor() const { return mNanColor; } bool periodic() const { return mPeriodic; } // setters: void setLevelCount(int n); void setColorStops(const QMap &colorStops); void setColorStopAt(double position, const QColor &color); void setColorInterpolation(ColorInterpolation interpolation); void setNanHandling(NanHandling handling); void setNanColor(const QColor &color); void setPeriodic(bool enabled); // non-property methods: void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); void colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); QRgb color(double position, const QCPRange &range, bool logarithmic=false); void loadPreset(GradientPreset preset); void clearColorStops(); QCPColorGradient inverted() const; protected: // property members: int mLevelCount; QMap mColorStops; ColorInterpolation mColorInterpolation; NanHandling mNanHandling; QColor mNanColor; bool mPeriodic; // non-property members: QVector mColorBuffer; // have colors premultiplied with alpha (for usage with QImage::Format_ARGB32_Premultiplied) bool mColorBufferInvalidated; // non-virtual methods: bool stopsUseAlpha() const; void updateColorBuffer(); }; Q_DECLARE_METATYPE(QCPColorGradient::ColorInterpolation) Q_DECLARE_METATYPE(QCPColorGradient::NanHandling) Q_DECLARE_METATYPE(QCPColorGradient::GradientPreset) /* end of 'src/colorgradient.h' */ /* including file 'src/selectiondecorator-bracket.h' */ /* modified 2021-03-29T02:30:44, size 4458 */ class QCP_LIB_DECL QCPSelectionDecoratorBracket : public QCPSelectionDecorator { Q_GADGET public: /*! Defines which shape is drawn at the boundaries of selected data ranges. Some of the bracket styles further allow specifying a height and/or width, see \ref setBracketHeight and \ref setBracketWidth. */ enum BracketStyle { bsSquareBracket ///< A square bracket is drawn. ,bsHalfEllipse ///< A half ellipse is drawn. The size of the ellipse is given by the bracket width/height properties. ,bsEllipse ///< An ellipse is drawn. The size of the ellipse is given by the bracket width/height properties. ,bsPlus ///< A plus is drawn. ,bsUserStyle ///< Start custom bracket styles at this index when subclassing and reimplementing \ref drawBracket. }; Q_ENUMS(BracketStyle) QCPSelectionDecoratorBracket(); virtual ~QCPSelectionDecoratorBracket() Q_DECL_OVERRIDE; // getters: QPen bracketPen() const { return mBracketPen; } QBrush bracketBrush() const { return mBracketBrush; } int bracketWidth() const { return mBracketWidth; } int bracketHeight() const { return mBracketHeight; } BracketStyle bracketStyle() const { return mBracketStyle; } bool tangentToData() const { return mTangentToData; } int tangentAverage() const { return mTangentAverage; } // setters: void setBracketPen(const QPen &pen); void setBracketBrush(const QBrush &brush); void setBracketWidth(int width); void setBracketHeight(int height); void setBracketStyle(BracketStyle style); void setTangentToData(bool enabled); void setTangentAverage(int pointCount); // introduced virtual methods: virtual void drawBracket(QCPPainter *painter, int direction) const; // virtual methods: virtual void drawDecoration(QCPPainter *painter, QCPDataSelection selection) Q_DECL_OVERRIDE; protected: // property members: QPen mBracketPen; QBrush mBracketBrush; int mBracketWidth; int mBracketHeight; BracketStyle mBracketStyle; bool mTangentToData; int mTangentAverage; // non-virtual methods: double getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const; QPointF getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const; }; Q_DECLARE_METATYPE(QCPSelectionDecoratorBracket::BracketStyle) /* end of 'src/selectiondecorator-bracket.h' */ /* including file 'src/layoutelements/layoutelement-axisrect.h' */ /* modified 2021-03-29T02:30:44, size 7529 */ class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); virtual ~QCPAxisRect() Q_DECL_OVERRIDE; // getters: QPixmap background() const { return mBackgroundPixmap; } QBrush backgroundBrush() const { return mBackgroundBrush; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } Qt::Orientations rangeDrag() const { return mRangeDrag; } Qt::Orientations rangeZoom() const { return mRangeZoom; } QCPAxis *rangeDragAxis(Qt::Orientation orientation); QCPAxis *rangeZoomAxis(Qt::Orientation orientation); QList rangeDragAxes(Qt::Orientation orientation); QList rangeZoomAxes(Qt::Orientation orientation); double rangeZoomFactor(Qt::Orientation orientation); // setters: void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setRangeDrag(Qt::Orientations orientations); void setRangeZoom(Qt::Orientations orientations); void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeDragAxes(QList axes); void setRangeDragAxes(QList horizontal, QList vertical); void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeZoomAxes(QList axes); void setRangeZoomAxes(QList horizontal, QList vertical); void setRangeZoomFactor(double horizontalFactor, double verticalFactor); void setRangeZoomFactor(double factor); // non-property methods: int axisCount(QCPAxis::AxisType type) const; QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; QList axes(QCPAxis::AxisTypes types) const; QList axes() const; QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=nullptr); QList addAxes(QCPAxis::AxisTypes types); bool removeAxis(QCPAxis *axis); QCPLayoutInset *insetLayout() const { return mInsetLayout; } void zoom(const QRectF &pixelRect); void zoom(const QRectF &pixelRect, const QList &affectedAxes); void setupFullAxesBox(bool connectRanges=false); QList plottables() const; QList graphs() const; QList items() const; // read-only interface imitating a QRect: int left() const { return mRect.left(); } int right() const { return mRect.right(); } int top() const { return mRect.top(); } int bottom() const { return mRect.bottom(); } int width() const { return mRect.width(); } int height() const { return mRect.height(); } QSize size() const { return mRect.size(); } QPoint topLeft() const { return mRect.topLeft(); } QPoint topRight() const { return mRect.topRight(); } QPoint bottomLeft() const { return mRect.bottomLeft(); } QPoint bottomRight() const { return mRect.bottomRight(); } QPoint center() const { return mRect.center(); } // reimplemented virtual methods: virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; protected: // property members: QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayoutInset *mInsetLayout; Qt::Orientations mRangeDrag, mRangeZoom; QList > mRangeDragHorzAxis, mRangeDragVertAxis; QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; double mRangeZoomFactorHorz, mRangeZoomFactorVert; // non-property members: QList mDragStartHorzRange, mDragStartVertRange; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; bool mDragging; QHash > mAxes; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual int calculateAutoMargin(QCP::MarginSide side) Q_DECL_OVERRIDE; virtual void layoutChanged() Q_DECL_OVERRIDE; // events: virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; // non-property methods: void drawBackground(QCPPainter *painter); void updateAxesOffset(QCPAxis::AxisType type); private: Q_DISABLE_COPY(QCPAxisRect) friend class QCustomPlot; }; /* end of 'src/layoutelements/layoutelement-axisrect.h' */ /* including file 'src/layoutelements/layoutelement-legend.h' */ /* modified 2021-03-29T02:30:44, size 10425 */ class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) /// \endcond public: explicit QCPAbstractLegendItem(QCPLegend *parent); // getters: QCPLegend *parentLegend() const { return mParentLegend; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: QCPLegend *mParentLegend; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual QRect clipRect() const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QCPAbstractLegendItem) friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { Q_OBJECT public: QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); // getters: QCPAbstractPlottable *plottable() { return mPlottable; } protected: // property members: QCPAbstractPlottable *mPlottable; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; // non-virtual methods: QPen getIconBorderPen() const; QColor getTextColor() const; QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) /// \endcond public: /*! Defines the selectable parts of a legend \see setSelectedParts, setSelectableParts */ enum SelectablePart { spNone = 0x000 ///< 0x000 None ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) }; Q_ENUMS(SelectablePart) Q_FLAGS(SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPLegend(); virtual ~QCPLegend() Q_DECL_OVERRIDE; // getters: QPen borderPen() const { return mBorderPen; } QBrush brush() const { return mBrush; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QSize iconSize() const { return mIconSize; } int iconTextPadding() const { return mIconTextPadding; } QPen iconBorderPen() const { return mIconBorderPen; } SelectableParts selectableParts() const { return mSelectableParts; } SelectableParts selectedParts() const; QPen selectedBorderPen() const { return mSelectedBorderPen; } QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } QBrush selectedBrush() const { return mSelectedBrush; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } // setters: void setBorderPen(const QPen &pen); void setBrush(const QBrush &brush); void setFont(const QFont &font); void setTextColor(const QColor &color); void setIconSize(const QSize &size); void setIconSize(int width, int height); void setIconTextPadding(int padding); void setIconBorderPen(const QPen &pen); Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); void setSelectedBorderPen(const QPen &pen); void setSelectedIconBorderPen(const QPen &pen); void setSelectedBrush(const QBrush &brush); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; // non-virtual methods: QCPAbstractLegendItem *item(int index) const; QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; int itemCount() const; bool hasItem(QCPAbstractLegendItem *item) const; bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; bool addItem(QCPAbstractLegendItem *item); bool removeItem(int index); bool removeItem(QCPAbstractLegendItem *item); void clearItems(); QList selectedItems() const; signals: void selectionChanged(QCPLegend::SelectableParts parts); void selectableChanged(QCPLegend::SelectableParts parts); protected: // property members: QPen mBorderPen, mIconBorderPen; QBrush mBrush; QFont mFont; QColor mTextColor; QSize mIconSize; int mIconTextPadding; SelectableParts mSelectedParts, mSelectableParts; QPen mSelectedBorderPen, mSelectedIconBorderPen; QBrush mSelectedBrush; QFont mSelectedFont; QColor mSelectedTextColor; // reimplemented virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot) Q_DECL_OVERRIDE; virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // non-virtual methods: QPen getBorderPen() const; QBrush getBrush() const; private: Q_DISABLE_COPY(QCPLegend) friend class QCustomPlot; friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) /* end of 'src/layoutelements/layoutelement-legend.h' */ /* including file 'src/layoutelements/layoutelement-textelement.h' */ /* modified 2021-03-29T02:30:44, size 5359 */ class QCP_LIB_DECL QCPTextElement : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: explicit QCPTextElement(QCustomPlot *parentPlot); QCPTextElement(QCustomPlot *parentPlot, const QString &text); QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize); QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize); QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font); // getters: QString text() const { return mText; } int textFlags() const { return mTextFlags; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setText(const QString &text); void setTextFlags(int flags); void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); void clicked(QMouseEvent *event); void doubleClicked(QMouseEvent *event); protected: // property members: QString mText; int mTextFlags; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; QRect mTextBoundingRect; bool mSelectable, mSelected; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; virtual QSize maximumOuterSizeHint() const Q_DECL_OVERRIDE; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // non-virtual methods: QFont mainFont() const; QColor mainTextColor() const; private: Q_DISABLE_COPY(QCPTextElement) }; /* end of 'src/layoutelements/layoutelement-textelement.h' */ /* including file 'src/layoutelements/layoutelement-colorscale.h' */ /* modified 2021-03-29T02:30:44, size 5939 */ class QCPColorScaleAxisRectPrivate : public QCPAxisRect { Q_OBJECT public: explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: QCPColorScale *mParentColorScale; QImage mGradientImage; bool mGradientImageInvalidated; // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale using QCPAxisRect::calculateAutoMargin; using QCPAxisRect::mousePressEvent; using QCPAxisRect::mouseMoveEvent; using QCPAxisRect::mouseReleaseEvent; using QCPAxisRect::wheelEvent; using QCPAxisRect::update; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; void updateGradientImage(); Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPColorScale(QCustomPlot *parentPlot); virtual ~QCPColorScale() Q_DECL_OVERRIDE; // getters: QCPAxis *axis() const { return mColorAxis.data(); } QCPAxis::AxisType type() const { return mType; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } QCPColorGradient gradient() const { return mGradient; } QString label() const; int barWidth () const { return mBarWidth; } bool rangeDrag() const; bool rangeZoom() const; // setters: void setType(QCPAxis::AxisType type); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setLabel(const QString &str); void setBarWidth(int width); void setRangeDrag(bool enabled); void setRangeZoom(bool enabled); // non-property methods: QList colorMaps() const; void rescaleDataRange(bool onlyVisibleMaps); // reimplemented virtual methods: virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; signals: void dataRangeChanged(const QCPRange &newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(const QCPColorGradient &newGradient); protected: // property members: QCPAxis::AxisType mType; QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorGradient mGradient; int mBarWidth; // non-property members: QPointer mAxisRect; QPointer mColorAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; // events: virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QCPColorScale) friend class QCPColorScaleAxisRectPrivate; }; /* end of 'src/layoutelements/layoutelement-colorscale.h' */ /* including file 'src/plottables/plottable-graph.h' */ /* modified 2021-03-29T02:30:44, size 9316 */ class QCP_LIB_DECL QCPGraphData { public: QCPGraphData(); QCPGraphData(double key, double value); inline double sortKey() const { return key; } inline static QCPGraphData fromSortKey(double sortKey) { return QCPGraphData(sortKey, 0); } inline static bool sortKeyIsMainKey() { return true; } inline double mainKey() const { return key; } inline double mainValue() const { return value; } inline QCPRange valueRange() const { return QCPRange(value, value); } double key, value; }; Q_DECLARE_TYPEINFO(QCPGraphData, Q_PRIMITIVE_TYPE); /*! \typedef QCPGraphDataContainer Container for storing \ref QCPGraphData points. The data is stored sorted by \a key. This template instantiation is the container in which QCPGraph holds its data. For details about the generic container, see the documentation of the class template \ref QCPDataContainer. \see QCPGraphData, QCPGraph::setData */ typedef QCPDataContainer QCPGraphDataContainer; class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(int scatterSkip READ scatterSkip WRITE setScatterSkip) Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) /// \endcond public: /*! Defines how the graph's line is represented visually in the plot. The line is drawn with the current pen of the graph (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented ///< with symbols according to the scatter style, see \ref setScatterStyle) ,lsLine ///< data points are connected by a straight line ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point ,lsStepCenter ///< line is drawn as steps where the step is in between two data points ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line }; Q_ENUMS(LineStyle) explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPGraph() Q_DECL_OVERRIDE; // getters: QSharedPointer data() const { return mDataContainer; } LineStyle lineStyle() const { return mLineStyle; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } int scatterSkip() const { return mScatterSkip; } QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } bool adaptiveSampling() const { return mAdaptiveSampling; } // setters: void setData(QSharedPointer data); void setData(const QVector &keys, const QVector &values, bool alreadySorted=false); void setLineStyle(LineStyle ls); void setScatterStyle(const QCPScatterStyle &style); void setScatterSkip(int skip); void setChannelFillGraph(QCPGraph *targetGraph); void setAdaptiveSampling(bool enabled); // non-property methods: void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); void addData(double key, double value); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; protected: // property members: LineStyle mLineStyle; QCPScatterStyle mScatterStyle; int mScatterSkip; QPointer mChannelFillGraph; bool mAdaptiveSampling; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // introduced virtual methods: virtual void drawFill(QCPPainter *painter, QVector *lines) const; virtual void drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const; virtual void drawLinePlot(QCPPainter *painter, const QVector &lines) const; virtual void drawImpulsePlot(QCPPainter *painter, const QVector &lines) const; virtual void getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const; virtual void getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const; // non-virtual methods: void getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const; void getLines(QVector *lines, const QCPDataRange &dataRange) const; void getScatters(QVector *scatters, const QCPDataRange &dataRange) const; QVector dataToLines(const QVector &data) const; QVector dataToStepLeftLines(const QVector &data) const; QVector dataToStepRightLines(const QVector &data) const; QVector dataToStepCenterLines(const QVector &data) const; QVector dataToImpulseLines(const QVector &data) const; QVector getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const; QVector > getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const; bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const; QPointF getFillBasePoint(QPointF matchingDataPoint) const; const QPolygonF getFillPolygon(const QVector *lineData, QCPDataRange segment) const; const QPolygonF getChannelFillPolygon(const QVector *thisData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) const; int findIndexBelowX(const QVector *data, double x) const; int findIndexAboveX(const QVector *data, double x) const; int findIndexBelowY(const QVector *data, double y) const; int findIndexAboveY(const QVector *data, double y) const; double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const; friend class QCustomPlot; friend class QCPLegend; }; Q_DECLARE_METATYPE(QCPGraph::LineStyle) /* end of 'src/plottables/plottable-graph.h' */ /* including file 'src/plottables/plottable-curve.h' */ /* modified 2021-03-29T02:30:44, size 7434 */ class QCP_LIB_DECL QCPCurveData { public: QCPCurveData(); QCPCurveData(double t, double key, double value); inline double sortKey() const { return t; } inline static QCPCurveData fromSortKey(double sortKey) { return QCPCurveData(sortKey, 0, 0); } inline static bool sortKeyIsMainKey() { return false; } inline double mainKey() const { return key; } inline double mainValue() const { return value; } inline QCPRange valueRange() const { return QCPRange(value, value); } double t, key, value; }; Q_DECLARE_TYPEINFO(QCPCurveData, Q_PRIMITIVE_TYPE); /*! \typedef QCPCurveDataContainer Container for storing \ref QCPCurveData points. The data is stored sorted by \a t, so the \a sortKey() (returning \a t) is different from \a mainKey() (returning \a key). This template instantiation is the container in which QCPCurve holds its data. For details about the generic container, see the documentation of the class template \ref QCPDataContainer. \see QCPCurveData, QCPCurve::setData */ typedef QCPDataContainer QCPCurveDataContainer; class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(int scatterSkip READ scatterSkip WRITE setScatterSkip) Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) /// \endcond public: /*! Defines how the curve's line is represented visually in the plot. The line is drawn with the current pen of the curve (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) ,lsLine ///< Data points are connected with a straight line }; Q_ENUMS(LineStyle) explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPCurve() Q_DECL_OVERRIDE; // getters: QSharedPointer data() const { return mDataContainer; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } int scatterSkip() const { return mScatterSkip; } LineStyle lineStyle() const { return mLineStyle; } // setters: void setData(QSharedPointer data); void setData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted=false); void setData(const QVector &keys, const QVector &values); void setScatterStyle(const QCPScatterStyle &style); void setScatterSkip(int skip); void setLineStyle(LineStyle style); // non-property methods: void addData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted=false); void addData(const QVector &keys, const QVector &values); void addData(double t, double key, double value); void addData(double key, double value); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; protected: // property members: QCPScatterStyle mScatterStyle; int mScatterSkip; LineStyle mLineStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // introduced virtual methods: virtual void drawCurveLine(QCPPainter *painter, const QVector &lines) const; virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; // non-virtual methods: void getCurveLines(QVector *lines, const QCPDataRange &dataRange, double penWidth) const; void getScatters(QVector *scatters, const QCPDataRange &dataRange, double scatterWidth) const; int getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const; QPointF getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const; QVector getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const; bool mayTraverse(int prevRegion, int currentRegion) const; bool getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const; void getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector &beforeTraverse, QVector &afterTraverse) const; double pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const; friend class QCustomPlot; friend class QCPLegend; }; Q_DECLARE_METATYPE(QCPCurve::LineStyle) /* end of 'src/plottables/plottable-curve.h' */ /* including file 'src/plottables/plottable-bars.h' */ /* modified 2021-03-29T02:30:44, size 8955 */ class QCP_LIB_DECL QCPBarsGroup : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) Q_PROPERTY(double spacing READ spacing WRITE setSpacing) /// \endcond public: /*! Defines the ways the spacing between bars in the group can be specified. Thus it defines what the number passed to \ref setSpacing actually means. \see setSpacingType, setSpacing */ enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels ,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size ,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range }; Q_ENUMS(SpacingType) explicit QCPBarsGroup(QCustomPlot *parentPlot); virtual ~QCPBarsGroup(); // getters: SpacingType spacingType() const { return mSpacingType; } double spacing() const { return mSpacing; } // setters: void setSpacingType(SpacingType spacingType); void setSpacing(double spacing); // non-virtual methods: QList bars() const { return mBars; } QCPBars* bars(int index) const; int size() const { return mBars.size(); } bool isEmpty() const { return mBars.isEmpty(); } void clear(); bool contains(QCPBars *bars) const { return mBars.contains(bars); } void append(QCPBars *bars); void insert(int i, QCPBars *bars); void remove(QCPBars *bars); protected: // non-property members: QCustomPlot *mParentPlot; SpacingType mSpacingType; double mSpacing; QList mBars; // non-virtual methods: void registerBars(QCPBars *bars); void unregisterBars(QCPBars *bars); // virtual methods: double keyPixelOffset(const QCPBars *bars, double keyCoord); double getPixelSpacing(const QCPBars *bars, double keyCoord); private: Q_DISABLE_COPY(QCPBarsGroup) friend class QCPBars; }; Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) class QCP_LIB_DECL QCPBarsData { public: QCPBarsData(); QCPBarsData(double key, double value); inline double sortKey() const { return key; } inline static QCPBarsData fromSortKey(double sortKey) { return QCPBarsData(sortKey, 0); } inline static bool sortKeyIsMainKey() { return true; } inline double mainKey() const { return key; } inline double mainValue() const { return value; } inline QCPRange valueRange() const { return QCPRange(value, value); } // note that bar base value isn't held in each QCPBarsData and thus can't/shouldn't be returned here double key, value; }; Q_DECLARE_TYPEINFO(QCPBarsData, Q_PRIMITIVE_TYPE); /*! \typedef QCPBarsDataContainer Container for storing \ref QCPBarsData points. The data is stored sorted by \a key. This template instantiation is the container in which QCPBars holds its data. For details about the generic container, see the documentation of the class template \ref QCPDataContainer. \see QCPBarsData, QCPBars::setData */ typedef QCPDataContainer QCPBarsDataContainer; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup) Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue) Q_PROPERTY(double stackingGap READ stackingGap WRITE setStackingGap) Q_PROPERTY(QCPBars* barBelow READ barBelow) Q_PROPERTY(QCPBars* barAbove READ barAbove) /// \endcond public: /*! Defines the ways the width of the bar can be specified. Thus it defines what the number passed to \ref setWidth actually means. \see setWidthType, setWidth */ enum WidthType { wtAbsolute ///< Bar width is in absolute pixels ,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size ,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range }; Q_ENUMS(WidthType) explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPBars() Q_DECL_OVERRIDE; // getters: double width() const { return mWidth; } WidthType widthType() const { return mWidthType; } QCPBarsGroup *barsGroup() const { return mBarsGroup; } double baseValue() const { return mBaseValue; } double stackingGap() const { return mStackingGap; } QCPBars *barBelow() const { return mBarBelow.data(); } QCPBars *barAbove() const { return mBarAbove.data(); } QSharedPointer data() const { return mDataContainer; } // setters: void setData(QSharedPointer data); void setData(const QVector &keys, const QVector &values, bool alreadySorted=false); void setWidth(double width); void setWidthType(WidthType widthType); void setBarsGroup(QCPBarsGroup *barsGroup); void setBaseValue(double baseValue); void setStackingGap(double pixels); // non-property methods: void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); void addData(double key, double value); void moveBelow(QCPBars *bars); void moveAbove(QCPBars *bars); // reimplemented virtual methods: virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; protected: // property members: double mWidth; WidthType mWidthType; QCPBarsGroup *mBarsGroup; double mBaseValue; double mStackingGap; QPointer mBarBelow, mBarAbove; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // non-virtual methods: void getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const; QRectF getBarRect(double key, double value) const; void getPixelWidth(double key, double &lower, double &upper) const; double getStackedBaseValue(double key, bool positive) const; static void connectBars(QCPBars* lower, QCPBars* upper); friend class QCustomPlot; friend class QCPLegend; friend class QCPBarsGroup; }; Q_DECLARE_METATYPE(QCPBars::WidthType) /* end of 'src/plottables/plottable-bars.h' */ /* including file 'src/plottables/plottable-statisticalbox.h' */ /* modified 2021-03-29T02:30:44, size 7522 */ class QCP_LIB_DECL QCPStatisticalBoxData { public: QCPStatisticalBoxData(); QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector& outliers=QVector()); inline double sortKey() const { return key; } inline static QCPStatisticalBoxData fromSortKey(double sortKey) { return QCPStatisticalBoxData(sortKey, 0, 0, 0, 0, 0); } inline static bool sortKeyIsMainKey() { return true; } inline double mainKey() const { return key; } inline double mainValue() const { return median; } inline QCPRange valueRange() const { QCPRange result(minimum, maximum); for (QVector::const_iterator it = outliers.constBegin(); it != outliers.constEnd(); ++it) result.expand(*it); return result; } double key, minimum, lowerQuartile, median, upperQuartile, maximum; QVector outliers; }; Q_DECLARE_TYPEINFO(QCPStatisticalBoxData, Q_MOVABLE_TYPE); /*! \typedef QCPStatisticalBoxDataContainer Container for storing \ref QCPStatisticalBoxData points. The data is stored sorted by \a key. This template instantiation is the container in which QCPStatisticalBox holds its data. For details about the generic container, see the documentation of the class template \ref QCPDataContainer. \see QCPStatisticalBoxData, QCPStatisticalBox::setData */ typedef QCPDataContainer QCPStatisticalBoxDataContainer; class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) Q_PROPERTY(bool whiskerAntialiased READ whiskerAntialiased WRITE setWhiskerAntialiased) Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) /// \endcond public: explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: QSharedPointer data() const { return mDataContainer; } double width() const { return mWidth; } double whiskerWidth() const { return mWhiskerWidth; } QPen whiskerPen() const { return mWhiskerPen; } QPen whiskerBarPen() const { return mWhiskerBarPen; } bool whiskerAntialiased() const { return mWhiskerAntialiased; } QPen medianPen() const { return mMedianPen; } QCPScatterStyle outlierStyle() const { return mOutlierStyle; } // setters: void setData(QSharedPointer data); void setData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted=false); void setWidth(double width); void setWhiskerWidth(double width); void setWhiskerPen(const QPen &pen); void setWhiskerBarPen(const QPen &pen); void setWhiskerAntialiased(bool enabled); void setMedianPen(const QPen &pen); void setOutlierStyle(const QCPScatterStyle &style); // non-property methods: void addData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted=false); void addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers=QVector()); // reimplemented virtual methods: virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; protected: // property members: double mWidth; double mWhiskerWidth; QPen mWhiskerPen, mWhiskerBarPen; bool mWhiskerAntialiased; QPen mMedianPen; QCPScatterStyle mOutlierStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // introduced virtual methods: virtual void drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const; // non-virtual methods: void getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const; QRectF getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const; QVector getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const; QVector getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const; friend class QCustomPlot; friend class QCPLegend; }; /* end of 'src/plottables/plottable-statisticalbox.h' */ /* including file 'src/plottables/plottable-colormap.h' */ /* modified 2021-03-29T02:30:44, size 7092 */ class QCP_LIB_DECL QCPColorMapData { public: QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); ~QCPColorMapData(); QCPColorMapData(const QCPColorMapData &other); QCPColorMapData &operator=(const QCPColorMapData &other); // getters: int keySize() const { return mKeySize; } int valueSize() const { return mValueSize; } QCPRange keyRange() const { return mKeyRange; } QCPRange valueRange() const { return mValueRange; } QCPRange dataBounds() const { return mDataBounds; } double data(double key, double value); double cell(int keyIndex, int valueIndex); unsigned char alpha(int keyIndex, int valueIndex); // setters: void setSize(int keySize, int valueSize); void setKeySize(int keySize); void setValueSize(int valueSize); void setRange(const QCPRange &keyRange, const QCPRange &valueRange); void setKeyRange(const QCPRange &keyRange); void setValueRange(const QCPRange &valueRange); void setData(double key, double value, double z); void setCell(int keyIndex, int valueIndex, double z); void setAlpha(int keyIndex, int valueIndex, unsigned char alpha); // non-property methods: void recalculateDataBounds(); void clear(); void clearAlpha(); void fill(double z); void fillAlpha(unsigned char alpha); bool isEmpty() const { return mIsEmpty; } void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; protected: // property members: int mKeySize, mValueSize; QCPRange mKeyRange, mValueRange; bool mIsEmpty; // non-property members: double *mData; unsigned char *mAlpha; QCPRange mDataBounds; bool mDataModified; bool createAlpha(bool initializeOpaque=true); friend class QCPColorMap; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) /// \endcond public: explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPColorMap() Q_DECL_OVERRIDE; // getters: QCPColorMapData *data() const { return mMapData; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } bool interpolate() const { return mInterpolate; } bool tightBoundary() const { return mTightBoundary; } QCPColorGradient gradient() const { return mGradient; } QCPColorScale *colorScale() const { return mColorScale.data(); } // setters: void setData(QCPColorMapData *data, bool copy=false); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setInterpolate(bool enabled); void setTightBoundary(bool enabled); void setColorScale(QCPColorScale *colorScale); // non-property methods: void rescaleDataRange(bool recalculateDataBounds=false); Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; signals: void dataRangeChanged(const QCPRange &newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(const QCPColorGradient &newGradient); protected: // property members: QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorMapData *mMapData; QCPColorGradient mGradient; bool mInterpolate; bool mTightBoundary; QPointer mColorScale; // non-property members: QImage mMapImage, mUndersampledMapImage; QPixmap mLegendIcon; bool mMapImageInvalidated; // introduced virtual methods: virtual void updateMapImage(); // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; friend class QCustomPlot; friend class QCPLegend; }; /* end of 'src/plottables/plottable-colormap.h' */ /* including file 'src/plottables/plottable-financial.h' */ /* modified 2021-03-29T02:30:44, size 8644 */ class QCP_LIB_DECL QCPFinancialData { public: QCPFinancialData(); QCPFinancialData(double key, double open, double high, double low, double close); inline double sortKey() const { return key; } inline static QCPFinancialData fromSortKey(double sortKey) { return QCPFinancialData(sortKey, 0, 0, 0, 0); } inline static bool sortKeyIsMainKey() { return true; } inline double mainKey() const { return key; } inline double mainValue() const { return open; } inline QCPRange valueRange() const { return QCPRange(low, high); } // open and close must lie between low and high, so we don't need to check them double key, open, high, low, close; }; Q_DECLARE_TYPEINFO(QCPFinancialData, Q_PRIMITIVE_TYPE); /*! \typedef QCPFinancialDataContainer Container for storing \ref QCPFinancialData points. The data is stored sorted by \a key. This template instantiation is the container in which QCPFinancial holds its data. For details about the generic container, see the documentation of the class template \ref QCPDataContainer. \see QCPFinancialData, QCPFinancial::setData */ typedef QCPDataContainer QCPFinancialDataContainer; class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) /// \endcond public: /*! Defines the ways the width of the financial bar can be specified. Thus it defines what the number passed to \ref setWidth actually means. \see setWidthType, setWidth */ enum WidthType { wtAbsolute ///< width is in absolute pixels ,wtAxisRectRatio ///< width is given by a fraction of the axis rect size ,wtPlotCoords ///< width is in key coordinates and thus scales with the key axis range }; Q_ENUMS(WidthType) /*! Defines the possible representations of OHLC data in the plot. \see setChartStyle */ enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation ,csCandlestick ///< Candlestick representation }; Q_ENUMS(ChartStyle) explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPFinancial() Q_DECL_OVERRIDE; // getters: QSharedPointer data() const { return mDataContainer; } ChartStyle chartStyle() const { return mChartStyle; } double width() const { return mWidth; } WidthType widthType() const { return mWidthType; } bool twoColored() const { return mTwoColored; } QBrush brushPositive() const { return mBrushPositive; } QBrush brushNegative() const { return mBrushNegative; } QPen penPositive() const { return mPenPositive; } QPen penNegative() const { return mPenNegative; } // setters: void setData(QSharedPointer data); void setData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted=false); void setChartStyle(ChartStyle style); void setWidth(double width); void setWidthType(WidthType widthType); void setTwoColored(bool twoColored); void setBrushPositive(const QBrush &brush); void setBrushNegative(const QBrush &brush); void setPenPositive(const QPen &pen); void setPenNegative(const QPen &pen); // non-property methods: void addData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted=false); void addData(double key, double open, double high, double low, double close); // reimplemented virtual methods: virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; // static methods: static QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); protected: // property members: ChartStyle mChartStyle; double mWidth; WidthType mWidthType; bool mTwoColored; QBrush mBrushPositive, mBrushNegative; QPen mPenPositive, mPenNegative; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // non-virtual methods: void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected); void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected); double getPixelWidth(double key, double keyPixel) const; double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const; double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const; void getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const; QRectF selectionHitBox(QCPFinancialDataContainer::const_iterator it) const; friend class QCustomPlot; friend class QCPLegend; }; Q_DECLARE_METATYPE(QCPFinancial::ChartStyle) /* end of 'src/plottables/plottable-financial.h' */ /* including file 'src/plottables/plottable-errorbar.h' */ /* modified 2021-03-29T02:30:44, size 7749 */ class QCP_LIB_DECL QCPErrorBarsData { public: QCPErrorBarsData(); explicit QCPErrorBarsData(double error); QCPErrorBarsData(double errorMinus, double errorPlus); double errorMinus, errorPlus; }; Q_DECLARE_TYPEINFO(QCPErrorBarsData, Q_PRIMITIVE_TYPE); /*! \typedef QCPErrorBarsDataContainer Container for storing \ref QCPErrorBarsData points. It is a typedef for QVector<\ref QCPErrorBarsData>. This is the container in which \ref QCPErrorBars holds its data. Unlike most other data containers for plottables, it is not based on \ref QCPDataContainer. This is because the error bars plottable is special in that it doesn't store its own key and value coordinate per error bar. It adopts the key and value from the plottable to which the error bars shall be applied (\ref QCPErrorBars::setDataPlottable). So the stored \ref QCPErrorBarsData doesn't need a sortable key, but merely an index (as \c QVector provides), which maps one-to-one to the indices of the other plottable's data. \see QCPErrorBarsData, QCPErrorBars::setData */ typedef QVector QCPErrorBarsDataContainer; class QCP_LIB_DECL QCPErrorBars : public QCPAbstractPlottable, public QCPPlottableInterface1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QSharedPointer data READ data WRITE setData) Q_PROPERTY(QCPAbstractPlottable* dataPlottable READ dataPlottable WRITE setDataPlottable) Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) Q_PROPERTY(double symbolGap READ symbolGap WRITE setSymbolGap) /// \endcond public: /*! Defines in which orientation the error bars shall appear. If your data needs both error dimensions, create two \ref QCPErrorBars with different \ref ErrorType. \see setErrorType */ enum ErrorType { etKeyError ///< The errors are for the key dimension (bars appear parallel to the key axis) ,etValueError ///< The errors are for the value dimension (bars appear parallel to the value axis) }; Q_ENUMS(ErrorType) explicit QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPErrorBars() Q_DECL_OVERRIDE; // getters: QSharedPointer data() const { return mDataContainer; } QCPAbstractPlottable *dataPlottable() const { return mDataPlottable.data(); } ErrorType errorType() const { return mErrorType; } double whiskerWidth() const { return mWhiskerWidth; } double symbolGap() const { return mSymbolGap; } // setters: void setData(QSharedPointer data); void setData(const QVector &error); void setData(const QVector &errorMinus, const QVector &errorPlus); void setDataPlottable(QCPAbstractPlottable* plottable); void setErrorType(ErrorType type); void setWhiskerWidth(double pixels); void setSymbolGap(double pixels); // non-property methods: void addData(const QVector &error); void addData(const QVector &errorMinus, const QVector &errorPlus); void addData(double error); void addData(double errorMinus, double errorPlus); // virtual methods of 1d plottable interface: virtual int dataCount() const Q_DECL_OVERRIDE; virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; } protected: // property members: QSharedPointer mDataContainer; QPointer mDataPlottable; ErrorType mErrorType; double mWhiskerWidth; double mSymbolGap; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; // non-virtual methods: void getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector &backbones, QVector &whiskers) const; void getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const; double pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const; // helpers: void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; bool errorBarVisible(int index) const; bool rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const; friend class QCustomPlot; friend class QCPLegend; }; /* end of 'src/plottables/plottable-errorbar.h' */ /* including file 'src/items/item-straightline.h' */ /* modified 2021-03-29T02:30:44, size 3137 */ class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: explicit QCPItemStraightLine(QCustomPlot *parentPlot); virtual ~QCPItemStraightLine() Q_DECL_OVERRIDE; // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const point1; QCPItemPosition * const point2; protected: // property members: QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: QLineF getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const; QPen mainPen() const; }; /* end of 'src/items/item-straightline.h' */ /* including file 'src/items/item-line.h' */ /* modified 2021-03-29T02:30:44, size 3429 */ class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: explicit QCPItemLine(QCustomPlot *parentPlot); virtual ~QCPItemLine() Q_DECL_OVERRIDE; // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const start; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; QPen mainPen() const; }; /* end of 'src/items/item-line.h' */ /* including file 'src/items/item-curve.h' */ /* modified 2021-03-29T02:30:44, size 3401 */ class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: explicit QCPItemCurve(QCustomPlot *parentPlot); virtual ~QCPItemCurve() Q_DECL_OVERRIDE; // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const start; QCPItemPosition * const startDir; QCPItemPosition * const endDir; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; }; /* end of 'src/items/item-curve.h' */ /* including file 'src/items/item-rect.h' */ /* modified 2021-03-29T02:30:44, size 3710 */ class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: explicit QCPItemRect(QCustomPlot *parentPlot); virtual ~QCPItemRect() Q_DECL_OVERRIDE; // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; /* end of 'src/items/item-rect.h' */ /* including file 'src/items/item-text.h' */ /* modified 2021-03-29T02:30:44, size 5576 */ class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) Q_PROPERTY(double rotation READ rotation WRITE setRotation) Q_PROPERTY(QMargins padding READ padding WRITE setPadding) /// \endcond public: explicit QCPItemText(QCustomPlot *parentPlot); virtual ~QCPItemText() Q_DECL_OVERRIDE; // getters: QColor color() const { return mColor; } QColor selectedColor() const { return mSelectedColor; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } QFont font() const { return mFont; } QFont selectedFont() const { return mSelectedFont; } QString text() const { return mText; } Qt::Alignment positionAlignment() const { return mPositionAlignment; } Qt::Alignment textAlignment() const { return mTextAlignment; } double rotation() const { return mRotation; } QMargins padding() const { return mPadding; } // setters; void setColor(const QColor &color); void setSelectedColor(const QColor &color); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setFont(const QFont &font); void setSelectedFont(const QFont &font); void setText(const QString &text); void setPositionAlignment(Qt::Alignment alignment); void setTextAlignment(Qt::Alignment alignment); void setRotation(double degrees); void setPadding(const QMargins &padding); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const position; QCPItemAnchor * const topLeft; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottomRight; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QColor mColor, mSelectedColor; QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; QFont mFont, mSelectedFont; QString mText; Qt::Alignment mPositionAlignment; Qt::Alignment mTextAlignment; double mRotation; QMargins mPadding; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; QFont mainFont() const; QColor mainColor() const; QPen mainPen() const; QBrush mainBrush() const; }; /* end of 'src/items/item-text.h' */ /* including file 'src/items/item-ellipse.h' */ /* modified 2021-03-29T02:30:44, size 3890 */ class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: explicit QCPItemEllipse(QCustomPlot *parentPlot); virtual ~QCPItemEllipse() Q_DECL_OVERRIDE; // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const topLeftRim; QCPItemAnchor * const top; QCPItemAnchor * const topRightRim; QCPItemAnchor * const right; QCPItemAnchor * const bottomRightRim; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeftRim; QCPItemAnchor * const left; QCPItemAnchor * const center; protected: enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; /* end of 'src/items/item-ellipse.h' */ /* including file 'src/items/item-pixmap.h' */ /* modified 2021-03-29T02:30:44, size 4407 */ class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) Q_PROPERTY(bool scaled READ scaled WRITE setScaled) Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: explicit QCPItemPixmap(QCustomPlot *parentPlot); virtual ~QCPItemPixmap() Q_DECL_OVERRIDE; // getters: QPixmap pixmap() const { return mPixmap; } bool scaled() const { return mScaled; } Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } Qt::TransformationMode transformationMode() const { return mTransformationMode; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPixmap(const QPixmap &pixmap); void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPixmap mPixmap; QPixmap mScaledPixmap; bool mScaled; bool mScaledPixmapInvalidated; Qt::AspectRatioMode mAspectRatioMode; Qt::TransformationMode mTransformationMode; QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); QRect getFinalRect(bool *flippedHorz=nullptr, bool *flippedVert=nullptr) const; QPen mainPen() const; }; /* end of 'src/items/item-pixmap.h' */ /* including file 'src/items/item-tracer.h' */ /* modified 2021-03-29T02:30:44, size 4811 */ class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(double size READ size WRITE setSize) Q_PROPERTY(TracerStyle style READ style WRITE setStyle) Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) /// \endcond public: /*! The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. \see setStyle */ enum TracerStyle { tsNone ///< The tracer is not visible ,tsPlus ///< A plus shaped crosshair with limited size ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect ,tsCircle ///< A circle ,tsSquare ///< A square }; Q_ENUMS(TracerStyle) explicit QCPItemTracer(QCustomPlot *parentPlot); virtual ~QCPItemTracer() Q_DECL_OVERRIDE; // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } double size() const { return mSize; } TracerStyle style() const { return mStyle; } QCPGraph *graph() const { return mGraph; } double graphKey() const { return mGraphKey; } bool interpolating() const { return mInterpolating; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setSize(double size); void setStyle(TracerStyle style); void setGraph(QCPGraph *graph); void setGraphKey(double key); void setInterpolating(bool enabled); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; // non-virtual methods: void updatePosition(); QCPItemPosition * const position; protected: // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; double mSize; TracerStyle mStyle; QCPGraph *mGraph; double mGraphKey; bool mInterpolating; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) /* end of 'src/items/item-tracer.h' */ /* including file 'src/items/item-bracket.h' */ /* modified 2021-03-29T02:30:44, size 3991 */ class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(double length READ length WRITE setLength) Q_PROPERTY(BracketStyle style READ style WRITE setStyle) /// \endcond public: /*! Defines the various visual shapes of the bracket item. The appearance can be further modified by \ref setLength and \ref setPen. \see setStyle */ enum BracketStyle { bsSquare ///< A brace with angled edges ,bsRound ///< A brace with round edges ,bsCurly ///< A curly brace ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression }; Q_ENUMS(BracketStyle) explicit QCPItemBracket(QCustomPlot *parentPlot); virtual ~QCPItemBracket() Q_DECL_OVERRIDE; // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } double length() const { return mLength; } BracketStyle style() const { return mStyle; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setLength(double length); void setStyle(BracketStyle style); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; QCPItemPosition * const left; QCPItemPosition * const right; QCPItemAnchor * const center; protected: // property members: enum AnchorIndex {aiCenter}; QPen mPen, mSelectedPen; double mLength; BracketStyle mStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; }; Q_DECLARE_METATYPE(QCPItemBracket::BracketStyle) /* end of 'src/items/item-bracket.h' */ /* including file 'src/polar/radialaxis.h' */ /* modified 2021-03-29T02:30:44, size 12227 */ class QCP_LIB_DECL QCPPolarAxisRadial : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES /// \endcond public: /*! Defines the reference of the angle at which a radial axis is tilted (\ref setAngle). */ enum AngleReference { arAbsolute ///< The axis tilt is given in absolute degrees. The zero is to the right and positive angles are measured counter-clockwise. ,arAngularAxis ///< The axis tilt is measured in the angular coordinate system given by the parent angular axis. }; Q_ENUMS(AngleReference) /*! Defines the scale of an axis. \see setScaleType */ enum ScaleType { stLinear ///< Linear scaling ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). }; Q_ENUMS(ScaleType) /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts */ enum SelectablePart { spNone = 0 ///< None of the selectable parts ,spAxis = 0x001 ///< The axis backbone and tick marks ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) ,spAxisLabel = 0x004 ///< The axis label }; Q_ENUMS(SelectablePart) Q_FLAGS(SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) enum LabelMode { lmUpright ///< ,lmRotated ///< }; Q_ENUMS(LabelMode) explicit QCPPolarAxisRadial(QCPPolarAxisAngular *parent); virtual ~QCPPolarAxisRadial(); // getters: bool rangeDrag() const { return mRangeDrag; } bool rangeZoom() const { return mRangeZoom; } double rangeZoomFactor() const { return mRangeZoomFactor; } QCPPolarAxisAngular *angularAxis() const { return mAngularAxis; } ScaleType scaleType() const { return mScaleType; } const QCPRange range() const { return mRange; } bool rangeReversed() const { return mRangeReversed; } double angle() const { return mAngle; } AngleReference angleReference() const { return mAngleReference; } QSharedPointer ticker() const { return mTicker; } bool ticks() const { return mTicks; } bool tickLabels() const { return mTickLabels; } int tickLabelPadding() const { return mLabelPainter.padding(); } QFont tickLabelFont() const { return mTickLabelFont; } QColor tickLabelColor() const { return mTickLabelColor; } double tickLabelRotation() const { return mLabelPainter.rotation(); } LabelMode tickLabelMode() const; QString numberFormat() const; int numberPrecision() const { return mNumberPrecision; } QVector tickVector() const { return mTickVector; } QVector subTickVector() const { return mSubTickVector; } QVector tickVectorLabels() const { return mTickVectorLabels; } int tickLengthIn() const; int tickLengthOut() const; bool subTicks() const { return mSubTicks; } int subTickLengthIn() const; int subTickLengthOut() const; QPen basePen() const { return mBasePen; } QPen tickPen() const { return mTickPen; } QPen subTickPen() const { return mSubTickPen; } QFont labelFont() const { return mLabelFont; } QColor labelColor() const { return mLabelColor; } QString label() const { return mLabel; } int labelPadding() const; SelectableParts selectedParts() const { return mSelectedParts; } SelectableParts selectableParts() const { return mSelectableParts; } QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } QFont selectedLabelFont() const { return mSelectedLabelFont; } QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } QColor selectedLabelColor() const { return mSelectedLabelColor; } QPen selectedBasePen() const { return mSelectedBasePen; } QPen selectedTickPen() const { return mSelectedTickPen; } QPen selectedSubTickPen() const { return mSelectedSubTickPen; } // setters: void setRangeDrag(bool enabled); void setRangeZoom(bool enabled); void setRangeZoomFactor(double factor); Q_SLOT void setScaleType(QCPPolarAxisRadial::ScaleType type); Q_SLOT void setRange(const QCPRange &range); void setRange(double lower, double upper); void setRange(double position, double size, Qt::AlignmentFlag alignment); void setRangeLower(double lower); void setRangeUpper(double upper); void setRangeReversed(bool reversed); void setAngle(double degrees); void setAngleReference(AngleReference reference); void setTicker(QSharedPointer ticker); void setTicks(bool show); void setTickLabels(bool show); void setTickLabelPadding(int padding); void setTickLabelFont(const QFont &font); void setTickLabelColor(const QColor &color); void setTickLabelRotation(double degrees); void setTickLabelMode(LabelMode mode); void setNumberFormat(const QString &formatCode); void setNumberPrecision(int precision); void setTickLength(int inside, int outside=0); void setTickLengthIn(int inside); void setTickLengthOut(int outside); void setSubTicks(bool show); void setSubTickLength(int inside, int outside=0); void setSubTickLengthIn(int inside); void setSubTickLengthOut(int outside); void setBasePen(const QPen &pen); void setTickPen(const QPen &pen); void setSubTickPen(const QPen &pen); void setLabelFont(const QFont &font); void setLabelColor(const QColor &color); void setLabel(const QString &str); void setLabelPadding(int padding); void setSelectedTickLabelFont(const QFont &font); void setSelectedLabelFont(const QFont &font); void setSelectedTickLabelColor(const QColor &color); void setSelectedLabelColor(const QColor &color); void setSelectedBasePen(const QPen &pen); void setSelectedTickPen(const QPen &pen); void setSelectedSubTickPen(const QPen &pen); Q_SLOT void setSelectableParts(const QCPPolarAxisRadial::SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const QCPPolarAxisRadial::SelectableParts &selectedParts); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; // non-property methods: void moveRange(double diff); void scaleRange(double factor); void scaleRange(double factor, double center); void rescale(bool onlyVisiblePlottables=false); void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; QPointF coordToPixel(double angleCoord, double radiusCoord) const; double coordToRadius(double coord) const; double radiusToCoord(double radius) const; SelectablePart getPartAt(const QPointF &pos) const; signals: void rangeChanged(const QCPRange &newRange); void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); void scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType); void selectionChanged(const QCPPolarAxisRadial::SelectableParts &parts); void selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts); protected: // property members: bool mRangeDrag; bool mRangeZoom; double mRangeZoomFactor; // axis base: QCPPolarAxisAngular *mAngularAxis; double mAngle; AngleReference mAngleReference; SelectableParts mSelectableParts, mSelectedParts; QPen mBasePen, mSelectedBasePen; // axis label: int mLabelPadding; QString mLabel; QFont mLabelFont, mSelectedLabelFont; QColor mLabelColor, mSelectedLabelColor; // tick labels: //int mTickLabelPadding; in label painter bool mTickLabels; //double mTickLabelRotation; in label painter QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; int mNumberPrecision; QLatin1Char mNumberFormatChar; bool mNumberBeautifulPowers; bool mNumberMultiplyCross; // ticks and subticks: bool mTicks; bool mSubTicks; int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: QCPRange mRange; bool mRangeReversed; ScaleType mScaleType; // non-property members: QPointF mCenter; double mRadius; QSharedPointer mTicker; QVector mTickVector; QVector mTickVectorLabels; QVector mSubTickVector; bool mDragging; QCPRange mDragStartRange; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; QCPLabelPainterPrivate mLabelPainter; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // mouse events: virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; // non-virtual methods: void updateGeometry(const QPointF ¢er, double radius); void setupTickVectors(); QPen getBasePen() const; QPen getTickPen() const; QPen getSubTickPen() const; QFont getTickLabelFont() const; QFont getLabelFont() const; QColor getTickLabelColor() const; QColor getLabelColor() const; private: Q_DISABLE_COPY(QCPPolarAxisRadial) friend class QCustomPlot; friend class QCPPolarAxisAngular; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisRadial::SelectableParts) Q_DECLARE_METATYPE(QCPPolarAxisRadial::AngleReference) Q_DECLARE_METATYPE(QCPPolarAxisRadial::ScaleType) Q_DECLARE_METATYPE(QCPPolarAxisRadial::SelectablePart) /* end of 'src/polar/radialaxis.h' */ /* including file 'src/polar/layoutelement-angularaxis.h' */ /* modified 2021-03-29T02:30:44, size 13461 */ class QCP_LIB_DECL QCPPolarAxisAngular : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES /// \endcond public: /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts */ enum SelectablePart { spNone = 0 ///< None of the selectable parts ,spAxis = 0x001 ///< The axis backbone and tick marks ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) ,spAxisLabel = 0x004 ///< The axis label }; Q_ENUMS(SelectablePart) Q_FLAGS(SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) /*! TODO */ enum LabelMode { lmUpright ///< ,lmRotated ///< }; Q_ENUMS(LabelMode) explicit QCPPolarAxisAngular(QCustomPlot *parentPlot); virtual ~QCPPolarAxisAngular(); // getters: QPixmap background() const { return mBackgroundPixmap; } QBrush backgroundBrush() const { return mBackgroundBrush; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } bool rangeDrag() const { return mRangeDrag; } bool rangeZoom() const { return mRangeZoom; } double rangeZoomFactor() const { return mRangeZoomFactor; } const QCPRange range() const { return mRange; } bool rangeReversed() const { return mRangeReversed; } double angle() const { return mAngle; } QSharedPointer ticker() const { return mTicker; } bool ticks() const { return mTicks; } bool tickLabels() const { return mTickLabels; } int tickLabelPadding() const { return mLabelPainter.padding(); } QFont tickLabelFont() const { return mTickLabelFont; } QColor tickLabelColor() const { return mTickLabelColor; } double tickLabelRotation() const { return mLabelPainter.rotation(); } LabelMode tickLabelMode() const; QString numberFormat() const; int numberPrecision() const { return mNumberPrecision; } QVector tickVector() const { return mTickVector; } QVector tickVectorLabels() const { return mTickVectorLabels; } int tickLengthIn() const { return mTickLengthIn; } int tickLengthOut() const { return mTickLengthOut; } bool subTicks() const { return mSubTicks; } int subTickLengthIn() const { return mSubTickLengthIn; } int subTickLengthOut() const { return mSubTickLengthOut; } QPen basePen() const { return mBasePen; } QPen tickPen() const { return mTickPen; } QPen subTickPen() const { return mSubTickPen; } QFont labelFont() const { return mLabelFont; } QColor labelColor() const { return mLabelColor; } QString label() const { return mLabel; } int labelPadding() const { return mLabelPadding; } SelectableParts selectedParts() const { return mSelectedParts; } SelectableParts selectableParts() const { return mSelectableParts; } QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } QFont selectedLabelFont() const { return mSelectedLabelFont; } QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } QColor selectedLabelColor() const { return mSelectedLabelColor; } QPen selectedBasePen() const { return mSelectedBasePen; } QPen selectedTickPen() const { return mSelectedTickPen; } QPen selectedSubTickPen() const { return mSelectedSubTickPen; } QCPPolarGrid *grid() const { return mGrid; } // setters: void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setRangeDrag(bool enabled); void setRangeZoom(bool enabled); void setRangeZoomFactor(double factor); Q_SLOT void setRange(const QCPRange &range); void setRange(double lower, double upper); void setRange(double position, double size, Qt::AlignmentFlag alignment); void setRangeLower(double lower); void setRangeUpper(double upper); void setRangeReversed(bool reversed); void setAngle(double degrees); void setTicker(QSharedPointer ticker); void setTicks(bool show); void setTickLabels(bool show); void setTickLabelPadding(int padding); void setTickLabelFont(const QFont &font); void setTickLabelColor(const QColor &color); void setTickLabelRotation(double degrees); void setTickLabelMode(LabelMode mode); void setNumberFormat(const QString &formatCode); void setNumberPrecision(int precision); void setTickLength(int inside, int outside=0); void setTickLengthIn(int inside); void setTickLengthOut(int outside); void setSubTicks(bool show); void setSubTickLength(int inside, int outside=0); void setSubTickLengthIn(int inside); void setSubTickLengthOut(int outside); void setBasePen(const QPen &pen); void setTickPen(const QPen &pen); void setSubTickPen(const QPen &pen); void setLabelFont(const QFont &font); void setLabelColor(const QColor &color); void setLabel(const QString &str); void setLabelPadding(int padding); void setLabelPosition(Qt::AlignmentFlag position); void setSelectedTickLabelFont(const QFont &font); void setSelectedLabelFont(const QFont &font); void setSelectedTickLabelColor(const QColor &color); void setSelectedLabelColor(const QColor &color); void setSelectedBasePen(const QPen &pen); void setSelectedTickPen(const QPen &pen); void setSelectedSubTickPen(const QPen &pen); Q_SLOT void setSelectableParts(const QCPPolarAxisAngular::SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const QCPPolarAxisAngular::SelectableParts &selectedParts); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; // non-property methods: bool removeGraph(QCPPolarGraph *graph); int radialAxisCount() const; QCPPolarAxisRadial *radialAxis(int index=0) const; QList radialAxes() const; QCPPolarAxisRadial *addRadialAxis(QCPPolarAxisRadial *axis=0); bool removeRadialAxis(QCPPolarAxisRadial *axis); QCPLayoutInset *insetLayout() const { return mInsetLayout; } QRegion exactClipRegion() const; void moveRange(double diff); void scaleRange(double factor); void scaleRange(double factor, double center); void rescale(bool onlyVisiblePlottables=false); double coordToAngleRad(double coord) const { return mAngleRad+(coord-mRange.lower)/mRange.size()*(mRangeReversed ? -2.0*M_PI : 2.0*M_PI); } // mention in doc that return doesn't wrap double angleRadToCoord(double angleRad) const { return mRange.lower+(angleRad-mAngleRad)/(mRangeReversed ? -2.0*M_PI : 2.0*M_PI)*mRange.size(); } void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; QPointF coordToPixel(double angleCoord, double radiusCoord) const; SelectablePart getPartAt(const QPointF &pos) const; // read-only interface imitating a QRect: int left() const { return mRect.left(); } int right() const { return mRect.right(); } int top() const { return mRect.top(); } int bottom() const { return mRect.bottom(); } int width() const { return mRect.width(); } int height() const { return mRect.height(); } QSize size() const { return mRect.size(); } QPoint topLeft() const { return mRect.topLeft(); } QPoint topRight() const { return mRect.topRight(); } QPoint bottomLeft() const { return mRect.bottomLeft(); } QPoint bottomRight() const { return mRect.bottomRight(); } QPointF center() const { return mCenter; } double radius() const { return mRadius; } signals: void rangeChanged(const QCPRange &newRange); void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); void selectionChanged(const QCPPolarAxisAngular::SelectableParts &parts); void selectableChanged(const QCPPolarAxisAngular::SelectableParts &parts); protected: // property members: QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayoutInset *mInsetLayout; bool mRangeDrag; bool mRangeZoom; double mRangeZoomFactor; // axis base: double mAngle, mAngleRad; SelectableParts mSelectableParts, mSelectedParts; QPen mBasePen, mSelectedBasePen; // axis label: int mLabelPadding; QString mLabel; QFont mLabelFont, mSelectedLabelFont; QColor mLabelColor, mSelectedLabelColor; // tick labels: //int mTickLabelPadding; in label painter bool mTickLabels; //double mTickLabelRotation; in label painter QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; int mNumberPrecision; QLatin1Char mNumberFormatChar; bool mNumberBeautifulPowers; bool mNumberMultiplyCross; // ticks and subticks: bool mTicks; bool mSubTicks; int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: QCPRange mRange; bool mRangeReversed; // non-property members: QPointF mCenter; double mRadius; QList mRadialAxes; QCPPolarGrid *mGrid; QList mGraphs; QSharedPointer mTicker; QVector mTickVector; QVector mTickVectorLabels; QVector mTickVectorCosSin; QVector mSubTickVector; QVector mSubTickVectorCosSin; bool mDragging; QCPRange mDragAngularStart; QList mDragRadialStart; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; QCPLabelPainterPrivate mLabelPainter; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; // events: virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; // non-virtual methods: bool registerPolarGraph(QCPPolarGraph *graph); void drawBackground(QCPPainter *painter, const QPointF ¢er, double radius); void setupTickVectors(); QPen getBasePen() const; QPen getTickPen() const; QPen getSubTickPen() const; QFont getTickLabelFont() const; QFont getLabelFont() const; QColor getTickLabelColor() const; QColor getLabelColor() const; private: Q_DISABLE_COPY(QCPPolarAxisAngular) friend class QCustomPlot; friend class QCPPolarGrid; friend class QCPPolarGraph; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisAngular::SelectableParts) Q_DECLARE_METATYPE(QCPPolarAxisAngular::SelectablePart) /* end of 'src/polar/layoutelement-angularaxis.h' */ /* including file 'src/polar/polargrid.h' */ /* modified 2021-03-29T02:30:44, size 4506 */ class QCP_LIB_DECL QCPPolarGrid :public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES /// \endcond public: /*! TODO */ enum GridType { gtAngular = 0x01 ///< ,gtRadial = 0x02 ///< ,gtAll = 0xFF ///< ,gtNone = 0x00 ///< }; Q_ENUMS(GridType) Q_FLAGS(GridTypes) Q_DECLARE_FLAGS(GridTypes, GridType) explicit QCPPolarGrid(QCPPolarAxisAngular *parentAxis); // getters: QCPPolarAxisRadial *radialAxis() const { return mRadialAxis.data(); } GridTypes type() const { return mType; } GridTypes subGridType() const { return mSubGridType; } bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } QPen angularPen() const { return mAngularPen; } QPen angularSubGridPen() const { return mAngularSubGridPen; } QPen radialPen() const { return mRadialPen; } QPen radialSubGridPen() const { return mRadialSubGridPen; } QPen radialZeroLinePen() const { return mRadialZeroLinePen; } // setters: void setRadialAxis(QCPPolarAxisRadial *axis); void setType(GridTypes type); void setSubGridType(GridTypes type); void setAntialiasedSubGrid(bool enabled); void setAntialiasedZeroLine(bool enabled); void setAngularPen(const QPen &pen); void setAngularSubGridPen(const QPen &pen); void setRadialPen(const QPen &pen); void setRadialSubGridPen(const QPen &pen); void setRadialZeroLinePen(const QPen &pen); protected: // property members: GridTypes mType; GridTypes mSubGridType; bool mAntialiasedSubGrid, mAntialiasedZeroLine; QPen mAngularPen, mAngularSubGridPen; QPen mRadialPen, mRadialSubGridPen, mRadialZeroLinePen; // non-property members: QCPPolarAxisAngular *mParentAxis; QPointer mRadialAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: void drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector &coords, const QPen &pen, const QPen &zeroPen=Qt::NoPen); void drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector &ticksCosSin, const QPen &pen); private: Q_DISABLE_COPY(QCPPolarGrid) }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarGrid::GridTypes) Q_DECLARE_METATYPE(QCPPolarGrid::GridType) /* end of 'src/polar/polargrid.h' */ /* including file 'src/polar/polargraph.h' */ /* modified 2021-03-29T02:30:44, size 9606 */ class QCP_LIB_DECL QCPPolarLegendItem : public QCPAbstractLegendItem { Q_OBJECT public: QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph); // getters: QCPPolarGraph *polarGraph() { return mPolarGraph; } protected: // property members: QCPPolarGraph *mPolarGraph; // reimplemented virtual methods: virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; // non-virtual methods: QPen getIconBorderPen() const; QColor getTextColor() const; QFont getFont() const; }; class QCP_LIB_DECL QCPPolarGraph : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES /// \endcond public: /*! Defines how the graph's line is represented visually in the plot. The line is drawn with the current pen of the graph (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented ///< with symbols according to the scatter style, see \ref setScatterStyle) ,lsLine ///< data points are connected by a straight line }; Q_ENUMS(LineStyle) QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis); virtual ~QCPPolarGraph(); // getters: QString name() const { return mName; } bool antialiasedFill() const { return mAntialiasedFill; } bool antialiasedScatters() const { return mAntialiasedScatters; } QPen pen() const { return mPen; } QBrush brush() const { return mBrush; } bool periodic() const { return mPeriodic; } QCPPolarAxisAngular *keyAxis() const { return mKeyAxis.data(); } QCPPolarAxisRadial *valueAxis() const { return mValueAxis.data(); } QCP::SelectionType selectable() const { return mSelectable; } bool selected() const { return !mSelection.isEmpty(); } QCPDataSelection selection() const { return mSelection; } //QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; } QSharedPointer data() const { return mDataContainer; } LineStyle lineStyle() const { return mLineStyle; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } // setters: void setName(const QString &name); void setAntialiasedFill(bool enabled); void setAntialiasedScatters(bool enabled); void setPen(const QPen &pen); void setBrush(const QBrush &brush); void setPeriodic(bool enabled); void setKeyAxis(QCPPolarAxisAngular *axis); void setValueAxis(QCPPolarAxisRadial *axis); Q_SLOT void setSelectable(QCP::SelectionType selectable); Q_SLOT void setSelection(QCPDataSelection selection); //void setSelectionDecorator(QCPSelectionDecorator *decorator); void setData(QSharedPointer data); void setData(const QVector &keys, const QVector &values, bool alreadySorted=false); void setLineStyle(LineStyle ls); void setScatterStyle(const QCPScatterStyle &style); // non-property methods: void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); void addData(double key, double value); void coordsToPixels(double key, double value, double &x, double &y) const; const QPointF coordsToPixels(double key, double value) const; void pixelsToCoords(double x, double y, double &key, double &value) const; void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; void rescaleAxes(bool onlyEnlarge=false) const; void rescaleKeyAxis(bool onlyEnlarge=false) const; void rescaleValueAxis(bool onlyEnlarge=false, bool inKeyRange=false) const; bool addToLegend(QCPLegend *legend); bool addToLegend(); bool removeFromLegend(QCPLegend *legend) const; bool removeFromLegend() const; // introduced virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables virtual QCPPlottableInterface1D *interface1D() { return 0; } // TODO: return this later, when QCPAbstractPolarPlottable is created virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const; signals: void selectionChanged(bool selected); void selectionChanged(const QCPDataSelection &selection); void selectableChanged(QCP::SelectionType selectable); protected: // property members: QSharedPointer mDataContainer; LineStyle mLineStyle; QCPScatterStyle mScatterStyle; QString mName; bool mAntialiasedFill, mAntialiasedScatters; QPen mPen; QBrush mBrush; bool mPeriodic; QPointer mKeyAxis; QPointer mValueAxis; QCP::SelectionType mSelectable; QCPDataSelection mSelection; //QCPSelectionDecorator *mSelectionDecorator; // introduced virtual methods (later reimplemented TODO from QCPAbstractPolarPlottable): virtual QRect clipRect() const; virtual void draw(QCPPainter *painter); virtual QCP::Interaction selectionCategory() const; void applyDefaultAntialiasingHint(QCPPainter *painter) const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // virtual drawing helpers: virtual void drawLinePlot(QCPPainter *painter, const QVector &lines) const; virtual void drawFill(QCPPainter *painter, QVector *lines) const; virtual void drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const; // introduced virtual methods: virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; // non-virtual methods: void applyFillAntialiasingHint(QCPPainter *painter) const; void applyScattersAntialiasingHint(QCPPainter *painter) const; double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const; // drawing helpers: virtual int dataCount() const; void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; void drawPolyline(QCPPainter *painter, const QVector &lineData) const; void getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const; void getLines(QVector *lines, const QCPDataRange &dataRange) const; void getScatters(QVector *scatters, const QCPDataRange &dataRange) const; void getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const; void getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const; QVector dataToLines(const QVector &data) const; private: Q_DISABLE_COPY(QCPPolarGraph) friend class QCPPolarLegendItem; }; /* end of 'src/polar/polargraph.h' */ #endif // QCUSTOMPLOT_H THELI-3.1.3/src/qss/000077500000000000000000000000001417631501300137615ustar00rootroot00000000000000THELI-3.1.3/src/qss/default.qss000066400000000000000000000023271417631501300161410ustar00rootroot00000000000000QPushButton:hover { background-color: #bbccff; } QRadioButton:hover, QCheckBox:hover { background-color: #eeffff; } QComboBox:hover { background-color: #99ccff; } QStatusBar { border: 1px solid #555555; background: #bbbbbb; } QDockWidget > QWidget { border-top: none; border-bottom: none; border-right: 1px solid #555555; border-left: 1px solid #555555; background: #dadadd } QDockWidget::title { text-align: left; background: #ffe5ce; border-top: 1px solid #555555; border-bottom: none; border-right: 1px solid #555555; border-left: 1px solid #555555; background: qlineargradient(x0:1, y2:1, x0:1, y2:1, stop:0 #eec3aa, stop:1 #faf9d7); } QMenuBar { border-bottom: 1px solid #555555; border-top: none; border-right: 1px solid #555555; border-left: 1px solid #555555; background: qlineargradient(x0:1, y2:1, x0:1, y2:1, stop:0 #5588dd, stop:1 #99ccff); } QStatusBar { background: qlineargradient(x0:1, y1:2, x0:1, y1:2, stop:0 #4477cc, stop:1 white) } /* background: qlineargradient(x1:0, y1:0.5, x2:0, y2:1, stop:0 #ffe5ce, stop:1 white); */ THELI-3.1.3/src/query/000077500000000000000000000000001417631501300143205ustar00rootroot00000000000000THELI-3.1.3/src/query/query.cc000066400000000000000000001522351417631501300160040ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "query.h" #include "../functions.h" #include "../tools/tools.h" #include "../myimage/myimage.h" #include "../processingInternal/data.h" #include "../tools/cfitsioerrorcodes.h" #include "wcs.h" #include "wcshdr.h" #include #include #include // #include #include #include Query::Query(int *verbose) { // Initialization initEnvironment(thelidir, userdir); // QSettings settings("THELI", "PREFERENCES"); // QString server = settings.value("prefServerComboBox").toString(); // downloadServer = translateServer(server); pythonExecutable = findExecutableName("python"); // reserve 1MB for the downloaded catalog byteArray.reserve(1e6); verbosity = verbose; } Query::~Query() { } void Query::doBrightStarQueryFromWeb() { initAstromQuery(); getMedianEpoch(); buildQuerySyntaxAstrom(); runCommand(queryCommand); processBrightStarCatalog(); } void Query::doAstromQueryFromWeb() { initAstromQuery(); getMedianEpoch(); buildQuerySyntaxAstrom(); runCommand(queryCommand); processAstromCatalog(); } // Used for image quality, a pure stellar catalog void Query::doGaiaQuery() { initGaiaQuery(); getMedianEpoch(); buildQuerySyntaxGaia(); runCommand(queryCommand); processGaiaCatalog(); } void Query::doPhotomQueryFromWeb() { initPhotomQuery(); // getMedianEpoch(); buildQuerySyntaxPhotom(); runCommand(queryCommand); processPhotomCatalog(); } void Query::doColorCalibQueryFromWeb() { initColorCalibQuery(); buildQuerySyntaxColorCalib(); runCommand(queryCommand); processColorCalibCatalog(); } void Query::getCatalogSearchLocationAstrom() { if (!successProcessing) return; QVector crval1 = scienceData->getKeyFromAllImages("CRVAL1"); QVector crval2 = scienceData->getKeyFromAllImages("CRVAL2"); if (crval1.isEmpty() || crval2.isEmpty()) { emit messageAvailable("Query::getCatalogSearchLocationAstrom(): CRVAL vectors are empty", "error"); emit critical(); successProcessing = false; return; } // Use median to calculate field center (avoiding issues with RA=0|360 deg boundary) // Do not average central two elements if number of data points is even alpha = straightMedian_T(crval1, 0, false); delta = straightMedian_T(crval2, 0, false); // Convert to string (because we pass this to 'vizquery' alpha_string = QString::number(alpha, 'f', 6); delta_string = QString::number(delta, 'f', 6); } void Query::getCatalogSearchRadiusAstrom() { if (!successProcessing) return; QVector corners_crval1 = scienceData->getKeyFromAllImages("CORNERS_CRVAL1"); QVector corners_crval2 = scienceData->getKeyFromAllImages("CORNERS_CRVAL2"); if (corners_crval1.isEmpty() || corners_crval2.isEmpty()) { emit messageAvailable("Query::getCatalogSearchRadiusAstrom(): Corner vectors are empty", "error"); emit critical(); successProcessing = false; return; } // Search radius in DEC in arcmin double crval2_min = minVec_T(corners_crval2); double crval2_max = maxVec_T(corners_crval2); double crval2_radius = 60.*(crval2_max - crval2_min)*0.5; // Search radius in RA in arcmin, take into account possible pass over 0|360 deg boundary double crval1_min = minVec_T(corners_crval1); double crval1_max = maxVec_T(corners_crval1); if (crval1_max - crval1_min > 180.) { for (auto &ra : corners_crval1) { if (ra > 180.) ra -= 360.; } // Calculate min / max once more crval1_min = minVec_T(corners_crval1); crval1_max = maxVec_T(corners_crval1); } double crval1_radius = 60. * (crval1_max - crval1_min) * 0.5 * cos(delta*rad); // in [arcmin] if (!radius_manual.isEmpty()) radius_string = radius_manual; else { // Include a 10% safety margin in the search radius radius = 1.1*sqrt(crval1_radius*crval1_radius + crval2_radius*crval2_radius); // safeguarding against a potential threading issue with wcslib: if (radius > 5.*scienceData->instData->radius*60) { radius = 2.*scienceData->instData->radius*60; // TODO: this is probably not necessary anymore because of the wcslock in MyImage::initWCS() and the corresponding critical sections emit messageAvailable("Truncating the search radius to "+QString::number(radius, 'f', 1) + " arcmin", "warning"); emit messageAvailable("Do you have different targets collected in the same directory?", "warning"); qDebug() << "RA corner vertices" << corners_crval1; qDebug() << "DEC corner vertices" << corners_crval2; } radius_string = QString::number(radius, 'f', 3); } } void Query::getCatalogSearchLocationPhotom() { if (!successProcessing) return; // Calculate RA/DEC of image center photomImage = new MyImage(photomDir, photomImageName, "", 1, QVector(), verbosity); photomImage->loadHeader(); naxis1 = photomImage->naxis1; naxis2 = photomImage->naxis2; radius = 1.1 * sqrt(naxis1*naxis1+naxis2*naxis2) / 2. * photomImage->plateScale / 60.; // Convert to string (because we pass this to 'vizquery' alpha_string = QString::number(photomImage->alpha_ctr, 'f', 6); delta_string = QString::number(photomImage->delta_ctr, 'f', 6); radius_string = QString::number(radius, 'f', 3); } void Query::getCatalogSearchLocationColorCalib() { if (!successProcessing) return; // Calculate RA/DEC of image center photomImage->loadHeader(); naxis1 = photomImage->naxis1; naxis2 = photomImage->naxis2; radius = 1.1 * sqrt(naxis1*naxis1+naxis2*naxis2) / 2. * photomImage->plateScale / 60.; // Convert to string (because we pass this to 'vizquery' alpha_string = QString::number(photomImage->alpha_ctr, 'f', 6); delta_string = QString::number(photomImage->delta_ctr, 'f', 6); radius_string = QString::number(radius, 'f', 3); } void Query::getMedianEpoch() { if (!successProcessing) return; // Get median observation epoch (for GAIA) QVector epochs = scienceData->getKeyFromAllImages("DATE-OBS"); if (epochs.isEmpty() && refcatName.contains("GAIA")) { emit messageAvailable("Query::getMedianEpoch():
The DATE-OBS keyword was not found in the FITS headers, but is required for the GAIA reference catalog.
You must choose a different reference catalog.", "error"); emit critical(); successProcessing = false; return; } epoch = straightMedian_T(epochs); } void Query::initAstromQuery() { if (!successProcessing) return; // Reformat if necessary if (alpha_manual.contains(":")) alpha_manual = hmsToDecimal(alpha_manual); if (delta_manual.contains(":")) delta_manual = dmsToDecimal(delta_manual); // Get location. Manual or automatic mode if (magLimit_string.isEmpty()) magLimit_string = "25"; if (alpha_manual.isEmpty() || delta_manual.isEmpty()) { getCatalogSearchLocationAstrom(); } else { alpha_string = alpha_manual; delta_string = delta_manual; } // Get search radius getCatalogSearchRadiusAstrom(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); // Vizier does not deal correctly with integer coords if (!alpha_string.contains(".")) alpha_string.append(".0"); if (!delta_string.contains(".")) delta_string.append(".0"); } void Query::initGaiaQuery() { if (!successProcessing) return; getCatalogSearchLocationAstrom(); // search radius is provided explicitly only by the coaddition. Otherwise, we have to determine it if (radius_string.isEmpty()) getCatalogSearchRadiusAstrom(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); // Vizier does not deal correctly with integer coords if (!alpha_string.contains(".")) alpha_string.append(".0"); if (!delta_string.contains(".")) delta_string.append(".0"); } void Query::initPhotomQuery() { if (!successProcessing) return; getCatalogSearchLocationPhotom(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); } void Query::initColorCalibQuery() { if (!successProcessing) return; getCatalogSearchLocationColorCalib(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); } void Query::buildQuerySyntaxAstrom() { if (!successProcessing) return; // Vizier queries queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=170000 "); // TODO: More than ~170000 crashes writeAstromScamp(), for unknown reasons // queryCommand.append("-site="+downloadServer+" "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); if (refcatName.contains("ASCC")) queryCommand.append("-out=_RAJ -out=_DEJ -source=I/280B -out=Vmag Vmag=0.."+magLimit_string); else if (refcatName.contains("TYC")) queryCommand.append("-out=_RAJ -out=_DEJ -source=TYC/tyc_main -out=Vmag Vmag=0.."+magLimit_string); else if (refcatName.contains("2MASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=2MASS-PSC -out='Jmag,Hmag,Kmag' Hmag=0.."+magLimit_string); else if (refcatName.contains("UCAC")) queryCommand.append("-out=RAgaia -out=DEgaia -source=I/340 -out='Gmag,RMag' -out=pmRA -out=pmDE Rmag=0.."+magLimit_string); else if (refcatName.contains("GAIA")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=I/350/gaiaedr3 -out=Gmag -out=pmRA -out=pmDE Gmag=0.."+magLimit_string); else if (refcatName.contains("SDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=V/147 -out=gmag,rmag,imag rmag=0.."+magLimit_string); else if (refcatName.contains("PANSTARRS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=II/349/ps1 -out=gmag,rmag,imag rmag=0.."+magLimit_string); else if (refcatName.contains("VHS")) queryCommand.append("-out=RAJ2000 -out=DEJ2000 -source=II/359/vhs_dr4 -out=Jap4,Hap4,Ksap4 Jap4=0.."+magLimit_string); else if (refcatName.contains("SKYMAPPER")) queryCommand.append("-out=RAICRS -out=DEICRS -source=II/358/smss -out=gPSF,rPSF,iPSF rPSF=0.."+magLimit_string); } void Query::buildQuerySyntaxGaia() { if (!successProcessing) return; // Vizier query for GAIA point sources. Point sources are identified by means of proper motion, in extractRaDecGaia(); queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=1000000 "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=I/350/gaiaedr3 -out=Gmag -out=pmRA -out=pmDE -out=e_pmRA -out=e_pmDE"); } void Query::buildQuerySyntaxPhotom() { if (!successProcessing) return; // Vizier queries queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=1000000 "); // queryCommand.append("-site="+downloadServer+" "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); QString filter1 = filterStringToVizierName(refcatFilter1); QString filter2 = filterStringToVizierName(refcatFilter2); if (refcatName.contains("2MASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=2MASS-PSC "); else if (refcatName.contains("VHS")) queryCommand.append("-out=RAJ2000 -out=DEJ2000 -source=II/359/vhs_dr4 "); else if (refcatName.contains("APASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=II/336 "); else if (refcatName.contains("UKIDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=II/319 "); else if (refcatName.contains("SDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=V/147 "); else if (refcatName.contains("PANSTARRS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=II/349/ps1 "); else if (refcatName.contains("SKYMAPPER")) queryCommand.append("-out=RAICRS -out=DEICRS -source=II/358/smss "); else if (refcatName.contains("ATLAS-REFCAT2")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=J/ApJ/867/105 "); queryCommand.append("-out=" + filter1 + " -out=" + filter2 + " -out=e_" + filter1 + " -out=e_" + filter2); // mags and their errors } void Query::buildQuerySyntaxColorCalib() { if (!successProcessing) return; // Vizier queries queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=1000000 "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); // Using max 5 filters to identify G2 type stars QString filter1; QString filter2; QString filter3; QString filter4; QString filter5; if (refcatName.contains("SDSS")) { filter1 = filterStringToVizierName("u"); filter2 = filterStringToVizierName("g"); filter3 = filterStringToVizierName("r"); filter4 = filterStringToVizierName("i"); filter5 = filterStringToVizierName("z"); } if (refcatName.contains("SKYMAPPER")) { // ignoring v-band filter filter1 = filterStringToVizierName("u"); filter2 = filterStringToVizierName("g"); filter3 = filterStringToVizierName("r"); filter4 = filterStringToVizierName("i"); filter5 = filterStringToVizierName("z"); } if (refcatName.contains("APASS")) { filter1 = filterStringToVizierName("B"); filter2 = filterStringToVizierName("V"); filter3 = filterStringToVizierName("g"); filter4 = filterStringToVizierName("r"); filter5 = filterStringToVizierName("i"); } if (refcatName.contains("PANSTARRS")) { filter1 = filterStringToVizierName("g"); filter2 = filterStringToVizierName("r"); filter3 = filterStringToVizierName("i"); filter4 = filterStringToVizierName("z"); filter5 = ""; } if (refcatName.contains("ATLAS-REFCAT2")) { filter1 = filterStringToVizierName("g"); filter2 = filterStringToVizierName("r"); filter3 = filterStringToVizierName("i"); filter4 = filterStringToVizierName("z"); filter5 = ""; } if (refcatName.contains("APASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=II/336 "); else if (refcatName.contains("SDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=V/147 "); else if (refcatName.contains("PANSTARRS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=II/349/ps1 "); else if (refcatName.contains("SKYMAPPER")) queryCommand.append("-out=RAICRS -out=DEICRS -source=II/358/smss "); else if (refcatName.contains("ATLAS-REFCAT2")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=J/ApJ/867/105 "); queryCommand.append("-out=" + filter1 + " -out=" + filter2 + " -out=" + filter3 + " -out=" + filter4 + " -out=" + filter5); } QString Query::filterStringToVizierName(QString filter) { if (!successProcessing) return ""; if (refcatName.contains("APASS") && filter == "B") return "Bmag"; if (refcatName.contains("APASS") && filter == "V") return "Vmag"; if (refcatName.contains("APASS") && filter == "g") return "g\\'mag"; if (refcatName.contains("APASS") && filter == "r") return "r\\'mag"; if (refcatName.contains("APASS") && filter == "i") return "i\\'mag"; if (refcatName.contains("SDSS") && filter == "u") return "umag"; if (refcatName.contains("SDSS") && filter == "g") return "gmag"; if (refcatName.contains("SDSS") && filter == "r") return "rmag"; if (refcatName.contains("SDSS") && filter == "i") return "imag"; if (refcatName.contains("SDSS") && filter == "z") return "zmag"; if (refcatName.contains("SKYMAPPER") && filter == "u") return "uPSF"; if (refcatName.contains("SKYMAPPER") && filter == "v") return "vPSF"; if (refcatName.contains("SKYMAPPER") && filter == "g") return "gPSF"; if (refcatName.contains("SKYMAPPER") && filter == "r") return "rPSF"; if (refcatName.contains("SKYMAPPER") && filter == "i") return "iPSF"; if (refcatName.contains("SKYMAPPER") && filter == "z") return "zPSF"; if (refcatName.contains("PANSTARRS") && filter == "g") return "gmag"; if (refcatName.contains("PANSTARRS") && filter == "r") return "rmag"; if (refcatName.contains("PANSTARRS") && filter == "i") return "imag"; if (refcatName.contains("PANSTARRS") && filter == "z") return "zmag"; if (refcatName.contains("PANSTARRS") && filter == "y") return "ymag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "g") return "gmag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "r") return "rmag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "i") return "imag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "z") return "zmag"; if (refcatName.contains("2MASS") && filter == "J") return "Jmag"; if (refcatName.contains("2MASS") && filter == "H") return "Hmag"; if (refcatName.contains("2MASS") && filter == "Ks") return "Kmag"; if (refcatName.contains("VHS") && filter == "Y") return "Yap4"; // using 2.8 " aperture magnitudes if (refcatName.contains("VHS") && filter == "J") return "Jap4"; if (refcatName.contains("VHS") && filter == "H") return "Hap4"; if (refcatName.contains("VHS") && filter == "Ks") return "Ksap4"; if (refcatName.contains("UKIDSS") && filter == "") return "Ymag"; if (refcatName.contains("UKIDSS") && filter == "") return "Jmag1"; if (refcatName.contains("UKIDSS") && filter == "") return "Hmag"; if (refcatName.contains("UKIDSS") && filter == "") return "Kmag"; return ""; } QString Query::resolveTargetSidereal(QString target) { if (!successProcessing) return "Unresolved"; queryCommand = pythonExecutable + " " + thelidir+"/python/resolvetargets.py "+target; runCommand(queryCommand); QTextStream stream(&byteArray, QIODevice::ReadOnly); QString line; while (stream.readLineInto(&line)) { line = line.simplified(); if (line.contains("Traceback")) return "Unresolved"; else { // DEPRECATED. GUI will not launch if python3 cannot be found. The following is kept for reference only. // In case python2 is used instead of python3, we have to remove parentheses and commas from the output line = line.remove("("); line = line.remove(")"); line = line.replace(",", " "); line = line.simplified(); QStringList coordList = line.split(' '); targetAlpha = coordList[0]; targetDelta = coordList[1]; // Convert to HHMMSS and DDMMSS if (!targetAlpha.contains(":")) targetAlpha = decimalToHms(targetAlpha.toDouble()); if (!targetDelta.contains(":")) targetDelta = decimalToDms(targetDelta.toDouble()); return "Resolved"; } } return "Unresolved"; } QString Query::resolveTargetNonsidereal(QString target, QString dateobs, float geoLon, float geoLat) { if (!successProcessing) return "Unresolved"; QString geolonString = QString::number(geoLon, 'f', 4)+"d"; QString geolatString = QString::number(geoLat, 'f', 4)+"d"; queryCommand = pythonExecutable + " " + thelidir+"/python/mpc_query.py "+target + " " + dateobs + " " + geolonString + " " + geolatString; runCommand(queryCommand); QTextStream stream(&byteArray, QIODevice::ReadOnly); QString line; while (stream.readLineInto(&line)) { line = line.simplified(); if (line.contains("Traceback")) return "Unresolved"; else { // DEPRECATED. GUI will not launch if python3 cannot be found. The following is kept for reference only. // In case python2 is used instead of python3, we have to remove parentheses and commas from the output line = line.remove("("); line = line.remove(")"); line = line.replace(",", " "); line = line.simplified(); QStringList coordList = line.split(' '); targetAlpha = coordList[0]; targetDelta = coordList[1]; // Convert to HHMMSS and DDMMSS if (!targetAlpha.contains(":")) targetAlpha = decimalToHms(targetAlpha.toDouble()); if (!targetDelta.contains(":")) targetDelta = decimalToDms(targetDelta.toDouble()); return "Resolved"; } } return "Unresolved"; } /* // Extract 'value' in a line value QString Query::parseXML(QString &line, const QString &tag) { line.remove("<"+tag+">"); line.remove(""); return line.simplified(); } // Extract 'value' in a line value void Query::parseXML2(QString &line, const QString &tag, QString &val1, QString &val2) { line.remove("<"+tag+">"); line.remove(""); QStringList list = line.simplified().split(" "); val1 = list[0]; val2 = list[1]; } */ void Query::clearAstrom() { raMotions.clear(); deMotions.clear(); numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); } void Query::clearGaia() { raMotions.clear(); deMotions.clear(); raMotions_err.clear(); deMotions_err.clear(); numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); } void Query::clearPhotom() { numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); mag2_out.clear(); mag1err_out.clear(); mag2err_out.clear(); } void Query::clearColorCalib() { numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); mag2_out.clear(); mag3_out.clear(); mag4_out.clear(); mag5_out.clear(); } void Query::processAstromCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearAstrom(); // The iView catalog (ASCII) QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile outcat_iview(outpath+"/theli_mystd.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processAstromCatalog(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog, prepare scamp and anet QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("---")) continue; QString result = extractRaDecMagAstrom(line); // also prepares scamp and anet if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); measureBulkMotion(); // display mean bulk motion in that field pushNumberOfSources(); // display number of refcat sources writeAstromScamp(); writeAstromANET(); // Can be lengthy if 100000 sources or more are retrieved. dumpRefcatID(); // writes refcat/.refcatID, used to check whether the catalog needs to be recreated } void Query::processGaiaCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearGaia(); // The iView catalog (ASCII) QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile outcat_iview(outpath+"/theli_pointsources.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processGaiaCatalog(): "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("---")) continue; QString result = extractRaDecGaia(line); // includes point source filtering if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); // pushNumberOfSources(); // display number of refcat sources dumpRefcatID(); // writes refcat/.refcatID, used to check whether the catalog needs to be recreated } // used externally when modeling the background. // difference: does not dump catalogs to drive void Query::processBrightStarCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearAstrom(); // Process the stream QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("---")) continue; QString result = extractRaDecMagAstrom(line); if (!result.isEmpty()) ++numSources; ++i; } } void Query::processPhotomCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearPhotom(); // The iView catalog (ASCII) QString outpath = photomDir+"/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); QFile outcat_iview(outpath+"/refcatPhotom.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processPhotomCatalog(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("---")) continue; QString result = extractRaDecMagPhotom(line); if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Query::processColorCalibCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearColorCalib(); // The iView catalog (ASCII) QString outpath = photomDir+"/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); QFile outcat_iview(outpath+"/PHOTCAT_calibration/PHOTCAT_sources_"+refcatName+".iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processPhotomCatalog(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("---")) continue; QString result = extractRaDecMagColorCalib(line); if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Query::pushNumberOfSources() { QString messageString = ""; if (numSources > 0) { if (!fromImage) { messageString = QString::number(numSources) + " " + refcatName + " reference sources retrieved at this location:" // + "
RA = " + QString::number(alpha, 'f', 5) // + "
DEC = " + QString::number(delta, 'f', 5) + "
RA = " + alpha_string + "
DEC = " + delta_string + "
radius = " + radius_string + "'"; emit messageAvailable(messageString, "ignore"); } else { messageString = QString::number(numSources) + " " + refcatName + " reference sources detected in the image."; emit messageAvailable(messageString, "ignore"); } } else { if (!successfulDataBaseAccess) { emit messageAvailable("Query:: The CDS database is currently not reachable", "stop"); emit critical(); successfulDataBaseAccess = true; } if (!suppressCatalogWarning) { messageString = "WARNING: No reference sources retrieved!
" "-- try a different catalog
" "-- check your internet connection
" "-- do not run THELI from a console with active conda/astroconda environment
" "-- adjust mag limit and radius"; emit messageAvailable(messageString, "stop"); emit critical(); } } } void Query::identifySolarTypeStars() { if (!successProcessing) return; if (refcatName.contains("SDSS")) { c1min = sunUG; c1max = sunUG; c2min = sunGR; c2max = sunGR; c3min = sunRI; c3max = sunRI; c1tol = sunUGtol; c2tol = sunGRtol; c3tol = sunRItol; } if (refcatName.contains("SKYMAPPER")) { c1min = sunUG; c1max = sunUG; c2min = sunGR; c2max = sunGR; c3min = sunRI; c3max = sunRI; c1tol = sunUGtol; c2tol = sunGRtol; c3tol = sunRItol; } if (refcatName.contains("APASS")) { c1min = sunBV; c1max = sunBV; c2min = sunGR; c2max = sunGR; c3min = sunRI; c3max = sunRI; c1tol = sunBVtol; c2tol = sunGRtol; c3tol = sunRItol; } if (refcatName.contains("PANSTARRS")) { c1min = sunGR; c1max = sunGR; c2min = sunRI; c2max = sunRI; c3min = sunIZ; c3max = sunIZ; c1tol = sunGRtol; c2tol = sunRItol; c3tol = sunIZtol; } if (refcatName.contains("ATLAS-REFCAT2")) { c1min = sunGR; c1max = sunGR; c2min = sunRI; c2max = sunRI; c3min = sunIZ; c3max = sunIZ; c1tol = sunGRtol; c2tol = sunRItol; c3tol = sunIZtol; } QVector tolerances = {1.0, 1.5, 2.0}; // We use the first three colors, only // SDSS: u-g, g-r, r-i // SKYMAPPER: u-g, g-r, r-i // APASS: B-V, g-r, r-i // PANSTARRS: g-r, r-i, i-z // ATLAS-REFCAT2: g-r, r-i, i-z for (auto &tol : tolerances) { G2type.fill(false, mag1_out.length()); int nmatch = 0; float c1min0 = c1min - tol*c1tol; float c1max0 = c1max + tol*c1tol; float c2min0 = c2min - tol*c2tol; float c2max0 = c2max + tol*c2tol; float c3min0 = c3min - tol*c3tol; float c3max0 = c3max + tol*c3tol; for (long k=0; k= c1min0 && col1 <= c1max0 && col2 >= c2min0 && col2 <= c2max0 && col3 >= c3min0 && col3 <= c3max0) { G2type[k] = true; ++nmatch; } } if (nmatch > 0) { numG2sources = nmatch; break; } } } void Query::measureBulkMotion() { if (!successProcessing) return; if (!refcatName.contains("GAIA") && !refcatName.contains("UCAC5")) return; raBulkMotion = straightMedian_T(raMotions); deBulkMotion = straightMedian_T(deMotions); if (raMotions.length() > 1) { raErrBulkMotion = rmsMask_T(raMotions) / sqrt(raMotions.length()); deErrBulkMotion = rmsMask_T(deMotions) / sqrt(deMotions.length()); } else { raErrBulkMotion = 0.; deErrBulkMotion = 0.; } QString pmRA_GUI = QString::number(raBulkMotion, 'f', 3) + " +/- " + QString::number(raErrBulkMotion, 'f', 3); QString pmDE_GUI = QString::number(deBulkMotion, 'f', 3) + " +/- " + QString::number(deErrBulkMotion, 'f', 3); emit bulkMotionObtained(pmRA_GUI, pmDE_GUI); } QString Query::extractRaDecMagAstrom(QString &line) { if (!successProcessing) return ""; // 'line' contains RA, DEC, and an arbitrary number of magnitudes (which we average) // Fields are separated by semi-colons QString result = ""; // line = line.simplified(); QStringList list = line.split('\t'); int length = list.length(); if (refcatName.contains("GAIA") && length < 5) return result; if (!refcatName.contains("GAIA") && length < 3) return result; QString ra = list[0].simplified(); QString dec = list[1].simplified(); if (ra.isEmpty()) return ""; QVector magnitudes; magLimit = magLimit_string.toFloat(); // without proper motions if (!refcatName.contains("GAIA") && !refcatName.contains("UCAC")) { for (int i=2; i 1) { if (command.contains("vizquery")) emit messageAvailable("vizquery command:
"+queryCommand, "ignore"); if (command.contains("resolvetargets")) emit messageAvailable("resolve targets command:
"+queryCommand, "ignore"); } byteArray.clear(); QProcess process; process.start("/bin/sh -c \""+command+"\""); process.waitForFinished(-1); byteArray = process.readAllStandardOutput(); } /* // needed if the data isn't in memory yet (e.g. immediately after starting the main GUI) void Query::provideHeaderInfo() { for (int chip=0; chipinstData->numChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { it->loadHeader(); } } } */ void Query::writeAstromScamp() { if (!successProcessing) return; // Don't write an empty catalog (so that tasks checking for failure (non-existence of the catalog) can succeed) if (ra_out.length() == 0) return; char xworld[100] = "X_WORLD"; char yworld[100] = "Y_WORLD"; char mag[100] = "MAG"; char magerr[100] = "MAGERR"; char erra[100] = "ERRA_WORLD"; char errb[100] = "ERRB_WORLD"; char errt[100] = "ERRTHETA_WORLD"; // scamp does not complain if this key is absent char flags[100] = "FLAGS"; char obsdate[100] = "OBSDATE"; // char field[100] = "FIELD_POS"; char *ttype[9] = {xworld, yworld, mag, magerr, erra, errb, errt, flags, obsdate}; // char *ttype[8] = {"X_WORLD", "Y_WORLD", "MAG", "MAGERR", "ERRA_WORLD", "ERRB_WORLD", "ERRTHETA_WORLD", "FIELD_POS"}; // invalid in C++ char tf1[10] = "1D"; char tf2[10] = "1D"; char tf3[10] = "1E"; char tf4[10] = "1E"; char tf5[10] = "1E"; char tf6[10] = "1E"; char tf7[10] = "1E"; char tf8[10] = "1I"; char tf9[10] = "1E"; // char tf10[10] = "1I"; char *tform[9] = {tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9}; // Init numSources if called from outside Query if (numSources == 0) numSources = ra_out.length(); double ra_arr[numSources]; double de_arr[numSources]; float mag_arr[numSources]; float magErr_arr[numSources]; float aErr_arr[numSources]; float bErr_arr[numSources]; float thetaErr_arr[numSources]; int flags_arr[numSources]; float obsdate_arr[numSources]; // short fieldpos[numSources]; float dateobs = 2000.0; // dummy, for most catalogs if (refcatName.contains("GAIA")) dateobs = epochReference; for (long i=0; isubDirName+"/cat/refcat/"; mkAbsDir(outpath); QString filename = outpath + "/theli_mystd.scamp"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype, tform, nullptr, "LDAC_OBJECTS", &status); fits_write_col(fptr, TDOUBLE, 1, firstrow, firstelem, nrows, ra_arr, &status); fits_write_col(fptr, TDOUBLE, 2, firstrow, firstelem, nrows, de_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, mag_arr, &status); fits_write_col(fptr, TFLOAT, 4, firstrow, firstelem, nrows, magErr_arr, &status); fits_write_col(fptr, TFLOAT, 5, firstrow, firstelem, nrows, aErr_arr, &status); fits_write_col(fptr, TFLOAT, 6, firstrow, firstelem, nrows, bErr_arr, &status); fits_write_col(fptr, TFLOAT, 7, firstrow, firstelem, nrows, thetaErr_arr, &status); fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, flags_arr, &status); fits_write_col(fptr, TFLOAT, 9, firstrow, firstelem, nrows, obsdate_arr, &status); // fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, fieldpos, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); QFile file(filename); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Query::writeAstromANET() { if (!successProcessing) return; // STEP 1: write a FITS table char xworld[100] = "RA"; char yworld[100] = "DEC"; char mag[100] = "MAG"; char *ttype[3] = {xworld, yworld, mag}; char tf1[10] = "1D"; char tf2[10] = "1D"; char tf3[10] = "1E"; char *tform[3] = {tf1, tf2, tf3}; // Init numSources if called from outside Query if (numSources == 0) numSources = ra_out.length(); double ra_arr[numSources]; double de_arr[numSources]; float mag_arr[numSources]; for (long i=0; i 150000) { QString messageString = "NOTE: More than 1cd ../TEST350000 sources were retrieved.\n" "The astrometry.net index is not being built as it is very time consuming.\n" "If you want to use astrometry.net, reduce the catalog size by imposing\n" "a (tighter) magnitude limit."; emit messageAvailable(messageString, "warning"); return; } QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QString filename1 = outpath+"/theli_mystd_anet.cat"; filename1 = "!"+filename1; fits_create_file(&fptr, filename1.toUtf8().data(), &status); fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype, tform, nullptr, "OBJECTS", &status); fits_write_col(fptr, TDOUBLE, 1, firstrow, firstelem, nrows, ra_arr, &status); fits_write_col(fptr, TDOUBLE, 2, firstrow, firstelem, nrows, de_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, mag_arr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); // STEP 2: build the anet index // The diameter of one chip in arcmin float diameter = sqrt(naxis1*naxis1+naxis2*naxis2)*pixscale/60.; // The anet scale number float x = 2./log(2.)*log(diameter/6.); int scaleNumber; if (x-int(x) < 0.5) scaleNumber = int(x); else scaleNumber = int(x) + 1; if (scaleNumber<0) scaleNumber = 0; if (scaleNumber>19) scaleNumber = 19; filename1 = outpath+"/theli_mystd_anet.cat"; // without the exclamation mark QString filename2 = outpath + "/theli_mystd.index"; QString buildIndexCommand = "build-astrometry-index "; QString anetCheck = QStandardPaths::findExecutable("build-astrometry-index"); if (anetCheck.isEmpty()) return; buildIndexCommand.append("-i "+filename1+" "); buildIndexCommand.append("-o "+filename2+" "); buildIndexCommand.append("-E -M -S MAG -j 0.1 -I 1 "); buildIndexCommand.append("-t "+outpath+" "); buildIndexCommand.append("-P "+QString::number(scaleNumber)); runCommand(buildIndexCommand); QFile file(filename2); file.setPermissions(QFile::ReadUser | QFile::WriteUser); QFile file1(filename1); file1.remove(); } void Query::writeAstromIview() { if (!successProcessing) return; // The iView catalog (ASCII) QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile outcat_iview(outpath+"/theli_mystd.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::writeRefCatxxx(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog long dim = ra_out.length(); stream_iview.setRealNumberPrecision(9); for (long i=0; isubDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile file(outpath+"/.refcatID"); QTextStream stream(&file); if( !file.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::dumpRefcatID(): ERROR writing "+outpath+file.fileName()+" : "+file.errorString(), "error"); emit critical(); return; } if (!refcatName.contains("GAIA")) { stream << refcatName+"_"+alpha_manual+"_"+delta_manual+"_"+magLimit_string+"_"+radius_manual << "\n"; } else { stream << refcatName+"_"+alpha_manual+"_"+delta_manual+"_"+magLimit_string+"_"+radius_manual+"_"+maxProperMotion_string << "\n"; } file.close(); } void Query::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("Query::"+funcName+":
" + errorCodes->errorKeyMap.value(status), "error"); emit critical(); successProcessing = false; } } THELI-3.1.3/src/query/query.h000066400000000000000000000143461417631501300156460ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef QUERY_H #define QUERY_H #include "../processingInternal/data.h" #include "../myimage/myimage.h" #include "fitsio2.h" #include #include #include #include #include #include class Data; // circular include directives triggered by myworker class Query : public QObject { Q_OBJECT public: explicit Query(int *verbose); ~Query(); Data *scienceData = nullptr; MyImage *photomImage = nullptr; QString photomDir = ""; QString photomImageName = ""; bool suppressCatalogWarning = false; int numChips = 1; QString mainDirName; QString refcatName = ""; QString alpha_manual = ""; QString delta_manual = ""; QString radius_manual = ""; QString magLimit_string = ""; QString maxProperMotion_string = ""; QString targetAlpha = ""; QString targetDelta = ""; QString refcatFilter1 = ""; QString refcatFilter2 = ""; QString refcatFilter3 = ""; QString refcatFilter4 = ""; QString refcatFilter5 = ""; long numSources = 0; int numG2sources = 0; float naxis1 = 0.; // needed for building the anet index float naxis2 = 0.; // needed for building the anet index float pixscale = 0.; // needed for building the anet index float radius = 0.; QString radius_string = ""; bool fromImage = false; QVector ra_out; QVector de_out; QVector mag1_out; QVector mag2_out; QVector mag3_out; QVector mag4_out; QVector mag5_out; QVector G2type; QVector mag1err_out; QVector mag2err_out; void initAstromQuery(); void doBrightStarQueryFromWeb(); void doAstromQueryFromWeb(); void doPhotomQueryFromWeb(); void doColorCalibQueryFromWeb(); void doGaiaQuery(); QString resolveTargetSidereal(QString target); QString resolveTargetNonsidereal(QString target, QString dateobs, float geoLon, float geoLat); void writeAstromScamp(); void writeAstromANET(); void writeAstromIview(); void pushNumberOfSources(); void identifySolarTypeStars(); signals: void bulkMotionObtained(QString pmRA_GUI, QString pmDE_GUI); void messageAvailable(QString messageString, QString code); void critical(); private: QString path; QString thelidir; QString userdir; QString instrument_dir; QString pythonExecutable = ""; // The location and radius for the search, and their string representations double alpha = 0.; double delta = 0.; float magLimit = 25.; float maxProperMotion = 1.e9; QString alpha_string = ""; QString delta_string = ""; double rad = 3.1415926535 / 180.; int *verbosity; bool successProcessing = true; QVector raMotions; // Contains the proper motions in RA QVector deMotions; // Contains the proper motions in DEC QVector raMotions_err; // Contains the proper motion errors in RA QVector deMotions_err; // Contains the proper motion errors in DEC double raBulkMotion = 0.; double deBulkMotion = 0.; double raErrBulkMotion = 0.; double deErrBulkMotion = 0.; double epoch = 0; double epochReference = 2016.0; // Reference epoch for GAIA-EDR3. WARNING: might change with newer GAIA releases! // QString downloadServer = ""; QString queryCommand = ""; QByteArray byteArray; bool successfulDataBaseAccess = true; int firstUsableRow = 0; // The first line in the downloaded catalog that contains usable data (not counting #-ed lines) // G2 references. These ranges roughly span G0V - G5V const float sunUG = 1.43; // u-g const float sunGR = 0.44; // g-r const float sunRI = 0.11; // r-i const float sunIZ = 0.03; // i-z const float sunBV = 0.65; // B-V const float sunVR = 0.36; // V-R const float sunUGtol = 0.08; // tolerance const float sunGRtol = 0.05; // tolerance const float sunRItol = 0.05; // tolerance const float sunIZtol = 0.05; // tolerance const float sunBVtol = 0.05; // tolerance float c1min = 0.; float c1max = 0.; float c2min = 0.; float c2max = 0.; float c3min = 0.; float c3max = 0.; float c1tol = 0.; float c2tol = 0.; float c3tol = 0.; void getCatalogSearchLocationAstrom(); void getCatalogSearchLocationPhotom(); void getCatalogSearchRadiusAstrom(); void getCatalogSearchLocationColorCalib(); void buildQuerySyntaxAstrom(); void buildQuerySyntaxGaia(); void buildQuerySyntaxPhotom(); void buildQuerySyntaxColorCalib(); QString extractRaDecMagAstrom(QString &line); void processAstromCatalog(); void processGaiaCatalog(); void processPhotomCatalog(); void processColorCalibCatalog(); void processBrightStarCatalog(); void getMedianEpoch(); // void provideHeaderInfo(); void measureBulkMotion(); void clearAstrom(); void clearPhotom(); void clearColorCalib(); void clearGaia(); void runCommand(QString command); void dumpRefcatID(); void initPhotomQuery(); void initGaiaQuery(); void initColorCalibQuery(); QString filterStringToVizierName(QString filter); QString extractRaDecMagPhotom(QString &line); QString extractRaDecGaia(QString &line); // QString parseXML(QString &line, const QString &tag); // void parseXML2(QString &line, const QString &tag, QString &val1, QString &val2); QString extractRaDecMagColorCalib(QString &line); void printCfitsioError(QString funcName, int status); }; #endif // QUERY_H THELI-3.1.3/src/readmes/000077500000000000000000000000001417631501300145735ustar00rootroot00000000000000THELI-3.1.3/src/readmes/acknowledging.cc000066400000000000000000000016221417631501300177170ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "acknowledging.h" #include "ui_acknowledging.h" Acknowledging::Acknowledging(QWidget *parent) : QDialog(parent), ui(new Ui::Acknowledging) { ui->setupUi(this); } Acknowledging::~Acknowledging() { delete ui; } THELI-3.1.3/src/readmes/acknowledging.h000066400000000000000000000017311417631501300175620ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef ACKNOWLEDGING_H #define ACKNOWLEDGING_H #include namespace Ui { class Acknowledging; } class Acknowledging : public QDialog { Q_OBJECT public: explicit Acknowledging(QWidget *parent = 0); ~Acknowledging(); private: Ui::Acknowledging *ui; }; #endif // ACKNOWLEDGING_H THELI-3.1.3/src/readmes/acknowledging.ui000066400000000000000000000202171417631501300177500ustar00rootroot00000000000000 Acknowledging 0 0 598 683 Acknowledging THELI Qt::Horizontal 491 20 OK <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600;">Acknowledgements</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-weight:600;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">THELI v3 is written in C++, making extensive use of the Qt library, available from <a href="https://www.qt.io/"><span style=" text-decoration: underline; color:#2980b9;">https://www.qt.io/</span></a> .</p> <p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src=":/icons/qt5_logo.png" /></p> <p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600;">Acknowledging THELI in scientific publications</span></p> <p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt; font-weight:600;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">In scientific publications, you must mention the exact version number of THELI used to process your data, together with a reference to this paper: </p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://iopscience.iop.org/article/10.1088/0067-0049/209/2/21"><span style=" text-decoration: underline; color:#2980b9;">Schirmer, M. 2013, ApJS, 209, 21</span></a> <a href="https://ui.adsabs.harvard.edu/abs/2013ApJS..209...21S/abstract"><span style=" text-decoration: underline; color:#2980b9;">(ADS)</span></a></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; text-decoration: underline; color:#2980b9;"><br /></p> <p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600;">Acknowledging 3rd party tools used by THELI</span></p> <p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt; font-weight:600;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">THELI v3 makes use of third-party tools and data products, which must be acknowledged accordingly:</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://ui.adsabs.harvard.edu/abs/2002ASPC..281..228B/abstract"><span style=" text-decoration: underline; color:#2980b9;">Bertin et al. 2002, ASPC, 281, 228</span></a>, (Swarp)</p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://ui.adsabs.harvard.edu/abs/2006ASPC..351..112B/abstract"><span style=" text-decoration: underline; color:#2980b9;">Bertin 2006, ASPC, 351, 112</span></a> (Scamp)</p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://ui.adsabs.harvard.edu/abs/1996A%26AS..117..393B/abstract"><span style=" text-decoration: underline; color:#2980b9;">Bertin &amp; Arnouts 1996, A&amp;AS, 117, 393</span></a> (Source Extractor; optional)</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The use of Source Extractor is optional; by default, THELI uses its own detection method. You must also include astrometric and photometric reference catalogs and their online retrieval tool. If not discussed in the main text, the minimum text snippet for your acknowledgements is this (adjust as needed):</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:italic;">&quot;THELI made use of the following tools and data products: Source Extractor (Bertin &amp; Arnouts, 1996), Scamp (Bertin 2006), Swarp (Bertin et al. 2002), the XXX catalog (&lt;author, year&gt;) and the VizieR catalogue access tool, CDS, Strasbourg, France.”</span></p></body></html> true pushButton clicked() Acknowledging close() 540 687 423 686 THELI-3.1.3/src/readmes/imstatsreadme.cc000066400000000000000000000016221417631501300177450ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imstatsreadme.h" #include "ui_imstatsreadme.h" ImstatsReadme::ImstatsReadme(QWidget *parent) : QDialog(parent), ui(new Ui::ImstatsReadme) { ui->setupUi(this); } ImstatsReadme::~ImstatsReadme() { delete ui; } THELI-3.1.3/src/readmes/imstatsreadme.h000066400000000000000000000017571417631501300176200ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IMSTATSREADME_H #define IMSTATSREADME_H #include namespace Ui { class ImstatsReadme; } class ImstatsReadme : public QDialog { Q_OBJECT public: explicit ImstatsReadme(QWidget *parent = nullptr); ~ImstatsReadme(); private slots: private: Ui::ImstatsReadme *ui; }; #endif // IMSTATSREADME_H THELI-3.1.3/src/readmes/imstatsreadme.ui000066400000000000000000000310531417631501300177760ustar00rootroot00000000000000 ImstatsReadme 0 0 938 797 252 252 252 219 219 220 252 252 252 219 219 220 219 219 220 219 219 220 Mouse and keyboard interactions in the image statistics dialog true true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">The statistics module should be invoked after source catalogs and astrometry have been created. It displays the following parameters: </span><span style=" font-size:12pt; color:#ff007f;">Sky background</span><span style=" font-size:12pt;">, </span><span style=" font-size:12pt; color:#ff007f;">airmass</span><span style=" font-size:12pt;">, </span><span style=" font-size:12pt; color:#ff007f;">seeing</span><span style=" font-size:12pt;">, </span><span style=" font-size:12pt; color:#ff007f;">relative transparency</span><span style=" font-size:12pt;"> (if astrometry was run), </span><span style=" font-size:12pt; color:#ff007f;">PSF ellipticity</span><span style=" font-size:12pt;">.</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">Selecting images using name filters</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">Use a filter such as </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">*.fits</span><span style=" font-size:12pt;"> to obtain statistics for all images. Narrow down the selection as you would do on the command line, e.g. </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">*_3AB.fits</span><span style=" font-size:12pt;"> would select the third chip of a multi-chip camera, only.</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">Selecting images using sky coordinates</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">If both RA and DEC coordinates are provided, then only images containing these coordinates will be shown (if they also fulfil the filter criterion). Useful if you want to check the quality at the location of a particular source in multi-chip data (source appearing in different detectors with varying image quality).</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">Zooming and panning</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">Left-click-drag in a plot or on the axes to pan around. Scroll in a plot or on the axes to zoom. </span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">Browsing images in iView</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">Select an image by clicking on a data point. The image will be displayed in </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">iView</span><span style=" font-size:12pt;"> if the </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">Show image</span><span style=" font-size:12pt;"> button is selected</span><span style=" font-size:12pt; font-weight:600; font-style:italic;">. </span><span style=" font-size:12pt;">Use the </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">&lt;left&gt; </span><span style=" font-size:12pt;">or </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">&lt;right&gt; arrow keys</span><span style=" font-size:12pt;"> to step through the data. You can also use the yellow selector buttons in</span><span style=" font-size:12pt; font-weight:600; font-style:italic;"> iView</span><span style=" font-size:12pt;">. </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">iView</span><span style=" font-size:12pt;"> will display the same selection as the statistics module (unless an RA/DEC filter is used).</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">Interactively rejecting and restoring images</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; font-style:italic;">Left-click </span><span style=" font-size:12pt;">a data point to select / deselect a single image. Consecutively </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">right-click</span><span style=" font-size:12pt;"> to select / deselect multiple images. If you </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">right-clicked </span><span style=" font-size:12pt;">a data point, then subsequent </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">&lt;left&gt; </span><span style=" font-size:12pt;">and</span><span style=" font-size:12pt; font-weight:600; font-style:italic;"> &lt;right&gt; </span><span style=" font-size:12pt;">key strokes can be used to quickly include more data points in the vicinity. Following a left-click, the same keys will select single images only.<br />Press </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">&lt;Delete&gt;</span><span style=" font-size:12pt;"> to </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">park</span><span style=" font-size:12pt;"> the selected images (single chips) in a </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">inactive/badStatistics// </span><span style=" font-size:12pt;">subdirectory. Press the </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">&lt;A&gt; key</span><span style=" font-size:12pt;"> (not &lt;ALT&gt;) to park </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">all</span><span style=" font-size:12pt;"> selected images (all chips) from the associated multi-chip exposure. The graphics will update immediately.<br />Clicking on </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">Restore data</span><span style=" font-size:12pt;"> will move the images back to their original place. You might have to replot the graphics to reflect the change after restoring the data.</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">Numerically rejecting images</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">In addition to mouse-clicks, you can provide lower and upper limits to all parameters (y-axis) and also to the number of images (x-axis). Make the selective active by hitting </span><span style=" font-size:12pt; font-weight:600; font-style:italic;">&lt;return&gt;</span><span style=" font-size:12pt;">.</span></p></body></html> Qt::Horizontal 832 20 Close closePushButton clicked() ImstatsReadme close() 817 756 765 745 THELI-3.1.3/src/readmes/license.cc000066400000000000000000000015501417631501300165250ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "license.h" #include "ui_license.h" License::License(QWidget *parent) : QDialog(parent), ui(new Ui::License) { ui->setupUi(this); } License::~License() { delete ui; } THELI-3.1.3/src/readmes/license.h000066400000000000000000000016511417631501300163710ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef LICENSE_H #define LICENSE_H #include namespace Ui { class License; } class License : public QDialog { Q_OBJECT public: explicit License(QWidget *parent = 0); ~License(); private: Ui::License *ui; }; #endif // LICENSE_H THELI-3.1.3/src/readmes/license.ui000066400000000000000000000135641417631501300165650ustar00rootroot00000000000000 License 0 0 561 579 GPL License Qt::Horizontal 454 20 OK <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">THELI - A Pipeline To Process Astronomical Images</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <table border="0" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;" cellspacing="2" cellpadding="0"> <tr> <td> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a name="LC635"></a>Copyright (C) 2019 Mischa Schirmer</p></td></tr> <tr> <td></td></tr></table> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">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 any later version. </p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">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. </p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see <a href="https://www.gnu.org/licenses/"><span style=" text-decoration: underline; color:#2980b9;">https://www.gnu.org/licenses/</span></a> .</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src=":/icons/gpl.png" /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Mischa Schirmer (schirmer@mpia.de)</p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Max Planck Institute for Astronomy<br />Königstuhl 17</p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">62117 Heidelberg, Germany</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> true pushButton clicked() License close() 494 552 426 545 THELI-3.1.3/src/readmes/multidirreadme.cc000066400000000000000000000016311417631501300201120ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "multidirreadme.h" #include "ui_multidirreadme.h" MultidirReadme::MultidirReadme(QWidget *parent) : QDialog(parent), ui(new Ui::MultidirReadme) { ui->setupUi(this); } MultidirReadme::~MultidirReadme() { delete ui; } THELI-3.1.3/src/readmes/multidirreadme.h000066400000000000000000000017471417631501300177640ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MULTIDIRREADME_H #define MULTIDIRREADME_H #include namespace Ui { class MultidirReadme; } class MultidirReadme : public QDialog { Q_OBJECT public: explicit MultidirReadme(QWidget *parent = nullptr); ~MultidirReadme(); private: Ui::MultidirReadme *ui; }; #endif // MULTIDIRREADME_H THELI-3.1.3/src/readmes/multidirreadme.ui000066400000000000000000000337171417631501300201540ustar00rootroot00000000000000 MultidirReadme 0 0 734 661 The THELI data directory tree 75 true Multiple science and calibration directories 10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">To facilitate multi-color processing, more than one directory can be specified for the various data types. Comma- or blank-separated lists are allowed. The entries must be relative to the absolute <span style=" font-style:italic;">MAIN </span>directory path. The following rules apply:</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; text-decoration: underline; color:#00007f;">(1) HDU reformatting, processing of BIASes, DARKs and FLAT OFF/DARKs</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Any number of entries is allowed.</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; text-decoration: underline; color:#00007f;">(2) Processing of FLATs</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-weight:600; text-decoration: underline; color:#5500ff;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#00007f;">(2.1) </span><span style=" color:#ff007f;">One CALIB dir</span> (can be BIAS or FLAT OFF/DARK). In this case, the same CALIB dir will be applied to all FLATs. Example:</p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">CALIB = BIAS</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">FLAT = FLAT_B, FLAT_V, FLAT_R</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#00007f;">(2.2)</span><span style=" color:#000000;"> </span><span style=" color:#ff007f;">Equal number of CALIB dirs</span><span style=" color:#000000;">. The first FLAT entry will be processed by the first CALIB entry, and so on. Example:</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">CALIB = FLATOFF_J, FLATOFF_H, FLATOFF_K</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">FLAT = FLAT_J, FLAT_H, FLAT_K</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; text-decoration: underline; color:#00007f;">(3) Processing of SCIENCEs</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#00007f;">(3.1)</span><span style=" color:#000000;"> </span><span style=" color:#ff007f;">One FLAT and one BIAS</span><span style=" color:#000000;"> (assuming SCIENCEs and FLAT were taken in the same filter). Example:</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">BIAS = BIAS</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">FLAT = FLAT</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">SCIENCE = TARGET_1, TARGET_2, TARGET_3</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#00007f;">(3.2)</span><span style=" color:#00007f;"> </span><span style=" color:#ff007f;">Equal number of FLATs and SCIENCE, and one BIAS</span><span style=" color:#000000;">, e.g. when the same target was observed in three filters:</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">BIAS = BIAS</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">FLAT = FLAT_g, FLAT_r, FLAT_i</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">SCIENCE = TARGET_g, TARGET_r, TARGET_i</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#00007f;">(3.3)</span><span style=" color:#00007f;"> </span><span style=" color:#ff007f;">Equal number of CALIB dirs</span><span style=" color:#000000;">, e.g. when a target was observed multiple times at different dates. First science entry is corrected by first calib entries, etc:</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">DARK = DARK_2016, DARK_2017, DARK_2018</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">FLAT = FLAT_2016, FLAT_2017, FLAT_2018</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">SCIENCE = TARGET_2016, TARGET_2017, TARGET_2018</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#00007f;">(3.4)</span><span style=" color:#00007f;"> </span><span style=" color:#ff007f;">Equal number but different types of CALIB dirs</span><span style=" color:#000000;">. For example, a target was observed in J- and K-band. For J-band, you have a FLAT OFF (e.g. a dome flat with lamp off), but in K-band the dark flat is not possible because you are dominated by the dome's thermal emission; you want to subtract a real DARK. In this case, you can pretend the true DARK to be a FLAT OFF, like this:</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">FLATOFF = FLATOFF_J, DARK_K</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">FLAT = FLAT_J, FLAT_K</span></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000; background-color:#ccffee;">SCIENCE = TARGET_J, TARGET_K</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000;">If neither of these combinations apply, the SCIENCEs and CALIBs must be processed one by one.</span></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; color:#000000;"><br /></p></body></html> Qt::Horizontal 40 20 Close closePushButton clicked() MultidirReadme close() 625 611 523 613 THELI-3.1.3/src/readmes/scampreadme.cc000066400000000000000000000016041417631501300173640ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "scampreadme.h" #include "ui_scampreadme.h" ScampReadme::ScampReadme(QWidget *parent) : QDialog(parent), ui(new Ui::ScampReadme) { ui->setupUi(this); } ScampReadme::~ScampReadme() { delete ui; } THELI-3.1.3/src/readmes/scampreadme.h000066400000000000000000000017371417631501300172350ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef SCAMPREADME_H #define SCAMPREADME_H #include namespace Ui { class ScampReadme; } class ScampReadme : public QDialog { Q_OBJECT public: explicit ScampReadme(QWidget *parent = nullptr); ~ScampReadme(); private slots: private: Ui::ScampReadme *ui; }; #endif // SCAMPREADME_H THELI-3.1.3/src/readmes/scampreadme.ui000066400000000000000000000136771417631501300174310ustar00rootroot00000000000000 ScampReadme 0 0 794 895 Explanation of Scamp MOSAIC_TYPEs Qt::Horizontal 626 20 Close true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">From the SCAMP user manual: </span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt;">SCAMP can manipulate mosaics in a number of ways to perform the matching of sources on the sky, and the astrometric calibration itself. </span><span style=" font-size:12pt; font-weight:600;">For single-chip cameras only the UNCHANGED mode makes sense!</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">UNCHANGED</span><span style=" font-size:12pt;">:<br />The relative positioning of detectors on the focal plane, as recorded in the WCS keywords of the FITS headers, is assumed to be correct and constant from exposure to exposure. Matching with the reference catalogue will be done for all the detectors at once.</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">SHARE PROJAXIS</span><span style=" font-size:12pt;">: <br />The relative positioning of detectors is assumed to be constant and correct, but the different extensions within the same catalogue file do not share the same projection axis (the CRVAL FITS WCS keywords are different): although this does not prevent SCAMP to derive an accurate solution, this is generally not an efficient astrometric description of the focal plane. This option brings all extensions to the same centered projection axis while compensating with other WCS parameters.</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">SAME CRVAL</span><span style=" font-size:12pt;">: <br />Like SHARE PROJAXIS above, brings all extensions to the same centered projection axis (CRVAL parameters), but does not compensate by changing other WCS parameters. This option is useful when the CRPIX and CD WCS parameters are overridden by some focal plane model stored in a global .ahead file.</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">FIX FOCALPLANE</span><span style=" font-size:12pt;">: <br />Applies first a SHARE PROJAXIS correction to the headers and then attempts to derive a common, median relative positioning of detectors within the focal plane. This mode is useful to fix the positions of detectors when these have been derived independently at each exposure in an earlier not-so-robust calibration. A minimum of 5 exposures per astrometric instrument is recommended.</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600; color:#00007f;">LOOSE</span><span style=" font-size:12pt;">: <br />Makes all detector positions to be considered as independent between exposures. Contrary to other modes, matching with the reference catalogue will be conducted separately for each extension. The LOOSE mode is generally used for totally uncalibrated mosaics in a first SCAMP pass before doing a FIX FOCALPLANE.</span></p></body></html> pushButton clicked() ScampReadme close() 784 858 617 779 THELI-3.1.3/src/readmes/swarpreadme.cc000066400000000000000000000021511417631501300174130ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "swarpreadme.h" #include "ui_swarpreadme.h" SwarpReadme::SwarpReadme(long openfiles, long maxopenfiles, QWidget *parent) : QDialog(parent), ui(new Ui::SwarpReadme) { ui->setupUi(this); openFiles = openfiles; maxOpenFiles = maxopenfiles; ui->maxOpenFileLineEdit->setText(QString::number(maxOpenFiles)); ui->openFileLineEdit->setText(QString::number(openFiles)); } SwarpReadme::~SwarpReadme() { delete ui; } THELI-3.1.3/src/readmes/swarpreadme.h000066400000000000000000000020401417631501300172520ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef SWARPREADME_H #define SWARPREADME_H #include namespace Ui { class SwarpReadme; } class SwarpReadme : public QDialog { Q_OBJECT public: explicit SwarpReadme(long openfiles, long maxopenfiles, QWidget *parent = 0); ~SwarpReadme(); private: Ui::SwarpReadme *ui; long openFiles = 0; long maxOpenFiles = 0; }; #endif // SWARPREADME_H THELI-3.1.3/src/readmes/swarpreadme.ui000066400000000000000000000202201417631501300174400ustar00rootroot00000000000000 SwarpReadme 0 0 442 550 Dialog 221 0 0 255 0 0 221 0 0 255 0 0 168 169 169 241 241 241 75 true true <html><head/><body><p><span style=" color:#dd0000;">Critical: Incompatible system configuration</span></p></body></html> Max allowed number of open files on your system: true Number of files that will be opened by Swarp: true Qt::Vertical QSizePolicy::Fixed 20 13 Qt::Horizontal 335 20 OK 0 0 false true <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The following steps are needed to permanently change the upper limit of simultaneously opened files on a <span style=" font-weight:600;">Debian/Ubuntu</span> system. Other Linuxes are hopefully similar. On Mac you have to figure it out yourself.</p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">In <span style=" font-weight:600;">/etc/security/limits.conf</span>, add/set the following two lines to increase the number of open files to 100000:</p> <p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Hack';">* soft nofile 100000</span></p> <p style=" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Hack';">* hard nofile 100000</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">In <span style=" font-weight:600;">/etc/pam.d/su</span> and <span style=" font-weight:600;">/etc/pam.d/common-session</span>, add (or uncomment) the following line:</p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Hack';">session required pam_limits.so</span></p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Afterwards, logout and login again, and verify in a console that the <span style=" font-style:italic;">open files</span> parameter is set to 100000:</p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">$ ulimit -a</p> <p style="-qt-paragraph-type:empty; margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> pushButton clicked() SwarpReadme close() 420 550 344 546 THELI-3.1.3/src/readmes/tutorials.cc000066400000000000000000000004121417631501300171250ustar00rootroot00000000000000#include "tutorials.h" #include "ui_tutorials.h" Tutorials::Tutorials(QWidget *parent) : QDialog(parent), ui(new Ui::Tutorials) { ui->setupUi(this); } Tutorials::~Tutorials() { delete ui; } void Tutorials::on_pushButton_clicked() { close(); } THELI-3.1.3/src/readmes/tutorials.h000066400000000000000000000005051417631501300167720ustar00rootroot00000000000000#ifndef TUTORIALS_H #define TUTORIALS_H #include namespace Ui { class Tutorials; } class Tutorials : public QDialog { Q_OBJECT public: explicit Tutorials(QWidget *parent = 0); ~Tutorials(); private slots: void on_pushButton_clicked(); private: Ui::Tutorials *ui; }; #endif // TUTORIALS_H THELI-3.1.3/src/readmes/tutorials.ui000066400000000000000000000103021417631501300171540ustar00rootroot00000000000000 Tutorials 0 0 465 348 Links to THELI video tutorials Qt::Horizontal 358 20 Close <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The following tutorials are available on the <a href="https://www.youtube.com/channel/UCg-9wvqQ5XpT1ph22feth9w"><span style=" text-decoration: underline; color:#2980b9;">THELI youtube channel</span></a> :</p> <ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"> <a href="https://www.youtube.com/watch?v=LUwIxouJoXs"><span style=" text-decoration: underline; color:#2980b9;">1. Introduction to THELI v3</span></a><br />A general overview of how data processing is done in THELI.</li> <li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"> <a href="https://www.youtube.com/watch?v=pCtqc26ibp0"><span style=" text-decoration: underline; color:#2980b9;">2. Data model, and hybrid RAM/drive memory model</span></a><br />How THELI keeps data in memory and on drive, and how much influence you have about it in case of swapping.</li> <li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://www.youtube.com/watch?v=q4eWMIv4cx8"><span style=" text-decoration: underline; color:#2980b9;">3. Interaction with data in memory and FITS files</span></a><br />Visualizing different processing stages; activating and deactivating images; restoring previous processing stages.</li> <li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://www.youtube.com/watch?v=9tqfmRtu1Qc"><span style=" text-decoration: underline; color:#2980b9;">4. Image statistics and data quality</span></a><br />Overview of data quality; visualization of associated images and data subsets; deactivate inferior images so they don't contribute to the coadded image.</li></ul> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> true THELI-3.1.3/src/resources.qrc000066400000000000000000000045521417631501300157020ustar00rootroot00000000000000 icons/collapse.png icons/collapse_x.png icons/collapse_xxxx.png icons/collapse_xy.png icons/collapse_xyyx.png icons/collapse_y.png icons/collapse_yxxy.png icons/collapse_yyyy.png icons/icon_start.png icons/icon_previous.png icons/icon_back.png icons/icon_forward.png icons/icon_next.png icons/icon_end.png icons/key.png icons/redoarrow.png icons/magnifyer.png icons/bayer_bggr.png icons/bayer_gbrg.png icons/bayer_grbg.png icons/bayer_rggb.png icons/abszp.png icons/color.png icons/sigma.png icons/iview.png icons/addInst.png icons/xtalk_col_1x2.png icons/xtalk_col_2x1.png icons/xtalk_col_2x2.png icons/xtalk_nor_1x2.png icons/xtalk_nor_2x1.png icons/xtalk_nor_2x2.png icons/xtalk_row_1x2.png icons/xtalk_row_2x1.png icons/xtalk_row_2x2.png icons/hand.png icons/pipette.png icons/upload.png icons/download.png icons/gear.png icons/bones_final.png icons/gpl.png icons/qt5_logo.png icons/wcs.png icons/db-restart-icon.png icons/db-reset.png icons/parameter-reset.png icons/open_project.png icons/Actions-process-stop-icon.png icons/Signal-yield-icon.png icons/settings-icon.png qss/default.qss icons/satellite-icon.png icons/asteroid_icon.png icons/star_icon.png icons/spec.png THELI-3.1.3/src/settings.cc000066400000000000000000001327521417631501300153340ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include #include "mainwindow.h" #include "ui_mainwindow.h" #include "ui_confdockwidget.h" int MainWindow::writePreferenceSettings() { QSettings settings("THELI", "PREFERENCES"); settings.setValue("setupProjectLineEdit", ui->setupProjectLineEdit->text()); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); settings.sync(); return settings.status(); } int MainWindow::readPreferenceSettings(QString &projectname) { QSettings settings("THELI", "PREFERENCES"); projectname = settings.value("setupProjectLineEdit","").toString(); diskwarnPreference = settings.value("prefDiskspacewarnSpinBox",100).toInt(); switchProcessMonitorPreference = settings.value("prefSwitchProcessMonitorCheckBox", true).toBool(); numCPU = settings.value("prefCPUSpinBox", QThread::idealThreadCount()).toInt(); restoreGeometry(settings.value("myWidget/geometry").toByteArray()); restoreState(settings.value("myWidget/windowState").toByteArray()); return settings.status(); } QString MainWindow::getStatusForSettings() { QString statusString = ""; for (auto &it : status.listHistory) { if (it) statusString.append("1"); else statusString.append("0"); } return statusString; } void MainWindow::setStatusFromSettings(QString statusString) { // Enforce that the status string is no longer than the maximum string // (this is in case I change the number of task checkboxes at some point) statusString.truncate(19); QStringList list = statusString.split(""); // The call above results in empty strings at the first and last place of the list. // We need to remove them: list.removeFirst(); list.removeLast(); int i = 0; for (auto &it : list) { if (it == "0") status.listHistory.operator[](i) = false; else status.listHistory.operator[](i) = true; ++i; } status.updateStatus(); } int MainWindow::writeGUISettings() { // We have to suppress write GUI settings while GUI settings are loaded. // For example, this would be triggered by the updates of several setupDataDir LineEdits // below. A writeGUI() would e.g. overwrite the instrument in the settings file before // it can be read. if (preventLoop_WriteSettings) return QSettings::NoError; // Likewise, settings must not be written anytime during init if (doingInitialLaunch) return QSettings::NoError; // I don't like empty chars at the beginning. Not that they hurt so far, but nonetheless for (auto &it: status.listDataDirs) { QString text = it->text(); if (!text.isEmpty() && text.operator[](0) == ' ') text.remove(0,1); it->setText(text); } QSettings settings("THELI", ui->setupProjectLineEdit->text()); settings.beginGroup("MainWindow"); QString statusString = getStatusForSettings(); settings.setValue("statusString", statusString); // CONF DOCK WIDGET settings.setValue("APDfilterComboBox", cdw->ui->APDfilterComboBox->currentIndex()); settings.setValue("APDmaxphoterrorLineEdit", cdw->ui->APDmaxphoterrorLineEdit->text()); settings.setValue("APDrefcatComboBox", cdw->ui->APDrefcatComboBox->currentIndex()); settings.setValue("APIWCSCheckBox", cdw->ui->APIWCSCheckBox->isChecked()); settings.setValue("APIWCSLineEdit", cdw->ui->APIWCSLineEdit->text()); settings.setValue("APIapertureLineEdit", cdw->ui->APIapertureLineEdit->text()); settings.setValue("APIcalibrationmodeComboBox", cdw->ui->APIcalibrationmodeComboBox->currentIndex()); settings.setValue("APIcolorComboBox", cdw->ui->APIcolorComboBox->currentIndex()); settings.setValue("APIcolortermLineEdit", cdw->ui->APIcolortermLineEdit->text()); settings.setValue("APIconvergenceLineEdit", cdw->ui->APIconvergenceLineEdit->text()); settings.setValue("APIextinctionLineEdit", cdw->ui->APIextinctionLineEdit->text()); settings.setValue("APIfilterComboBox", cdw->ui->APIfilterComboBox->currentIndex()); settings.setValue("APIfilterkeywordLineEdit", cdw->ui->APIfilterkeywordLineEdit->text()); settings.setValue("APIkappaLineEdit", cdw->ui->APIkappaLineEdit->text()); settings.setValue("APIminmagLineEdit", cdw->ui->APIminmagLineEdit->text()); settings.setValue("APInight1ComboBox", cdw->ui->APInight1ComboBox->currentIndex()); settings.setValue("APInight2ComboBox", cdw->ui->APInight2ComboBox->currentIndex()); settings.setValue("APInight3ComboBox", cdw->ui->APInight3ComboBox->currentIndex()); settings.setValue("APInight4ComboBox", cdw->ui->APInight4ComboBox->currentIndex()); settings.setValue("APInight5ComboBox", cdw->ui->APInight5ComboBox->currentIndex()); settings.setValue("APInight6ComboBox", cdw->ui->APInight6ComboBox->currentIndex()); settings.setValue("APInight7ComboBox", cdw->ui->APInight7ComboBox->currentIndex()); settings.setValue("APInight8ComboBox", cdw->ui->APInight8ComboBox->currentIndex()); settings.setValue("APInight9ComboBox", cdw->ui->APInight9ComboBox->currentIndex()); settings.setValue("APIrefcatComboBox", cdw->ui->APIrefcatComboBox->currentIndex()); settings.setValue("APIthresholdLineEdit", cdw->ui->APIthresholdLineEdit->text()); settings.setValue("APIzpmaxLineEdit", cdw->ui->APIzpmaxLineEdit->text()); settings.setValue("APIzpminLineEdit", cdw->ui->APIzpminLineEdit->text()); settings.setValue("ARCDMINLineEdit", cdw->ui->ARCDMINLineEdit->text()); settings.setValue("ARCDTLineEdit", cdw->ui->ARCDTLineEdit->text()); settings.setValue("ARCcatalogComboBox", cdw->ui->ARCcatalogComboBox->currentIndex()); settings.setValue("ARCdecLineEdit", cdw->ui->ARCdecLineEdit->text()); settings.setValue("ARCimageRadioButton", cdw->ui->ARCimageRadioButton->isChecked()); settings.setValue("ARCmaxpmLineEdit", cdw->ui->ARCmaxpmLineEdit->text()); settings.setValue("ARCpmRALineEdit", cdw->ui->ARCpmRALineEdit->text()); settings.setValue("ARCpmDECLineEdit", cdw->ui->ARCpmDECLineEdit->text()); settings.setValue("ARCminmagLineEdit", cdw->ui->ARCminmagLineEdit->text()); settings.setValue("ARCraLineEdit", cdw->ui->ARCraLineEdit->text()); settings.setValue("ARCradiusLineEdit", cdw->ui->ARCradiusLineEdit->text()); settings.setValue("ARCselectimageLineEdit", cdw->ui->ARCselectimageLineEdit->text()); settings.setValue("ARCtargetresolverLineEdit", cdw->ui->ARCtargetresolverLineEdit->text()); settings.setValue("ARCwebRadioButton", cdw->ui->ARCwebRadioButton->isChecked()); settings.setValue("ASTastrefweightLineEdit", cdw->ui->ASTastrefweightLineEdit->text()); settings.setValue("ASTastrinstrukeyLineEdit", cdw->ui->ASTastrinstrukeyLineEdit->text()); settings.setValue("ASTcrossidLineEdit", cdw->ui->ASTcrossidLineEdit->text()); settings.setValue("ASTdistortLineEdit", cdw->ui->ASTdistortLineEdit->text()); settings.setValue("ASTdistortgroupsLineEdit", cdw->ui->ASTdistortgroupsLineEdit->text()); settings.setValue("ASTdistortkeysLineEdit", cdw->ui->ASTdistortkeysLineEdit->text()); settings.setValue("ASTfocalplaneComboBox", cdw->ui->ASTfocalplaneComboBox->currentIndex()); settings.setValue("ASTmatchMethodComboBox", cdw->ui->ASTmatchMethodComboBox->currentIndex()); settings.setValue("ASTmatchflippedCheckBox", cdw->ui->ASTmatchflippedCheckBox->isChecked()); settings.setValue("ASTmethodComboBox", cdw->ui->ASTmethodComboBox->currentIndex()); settings.setValue("ASTmosaictypeComboBox", cdw->ui->ASTmosaictypeComboBox->currentIndex()); settings.setValue("ASTphotinstrukeyLineEdit", cdw->ui->ASTphotinstrukeyLineEdit->text()); settings.setValue("ASTpixscaleLineEdit", cdw->ui->ASTpixscaleLineEdit->text()); settings.setValue("ASTposangleLineEdit", cdw->ui->ASTposangleLineEdit->text()); settings.setValue("ASTpositionLineEdit", cdw->ui->ASTpositionLineEdit->text()); settings.setValue("ASTresolutionLineEdit", cdw->ui->ASTresolutionLineEdit->text()); settings.setValue("ASTsnthreshLineEdit", cdw->ui->ASTsnthreshLineEdit->text()); settings.setValue("ASTstabilityComboBox", cdw->ui->ASTstabilityComboBox->currentIndex()); settings.setValue("ASTxcorrDTLineEdit", cdw->ui->ASTxcorrDTLineEdit->text()); settings.setValue("ASTxcorrDMINLineEdit", cdw->ui->ASTxcorrDMINLineEdit->text()); settings.setValue("BAC1nhighLineEdit", cdw->ui->BAC1nhighLineEdit->text()); settings.setValue("BAC1nlowLineEdit", cdw->ui->BAC1nlowLineEdit->text()); settings.setValue("BAC2nhighLineEdit", cdw->ui->BAC2nhighLineEdit->text()); settings.setValue("BAC2nlowLineEdit", cdw->ui->BAC2nlowLineEdit->text()); settings.setValue("BAC2passCheckBox", cdw->ui->BAC2passCheckBox->isChecked()); settings.setValue("BACDMINLineEdit", cdw->ui->BACDMINLineEdit->text()); settings.setValue("BACDTLineEdit", cdw->ui->BACDTLineEdit->text()); settings.setValue("BACapplyComboBox", cdw->ui->BACapplyComboBox->currentIndex()); settings.setValue("BACbacksmoothscaleLineEdit", cdw->ui->BACbacksmoothscaleLineEdit->text()); settings.setValue("BACconvolutionCheckBox", cdw->ui->BACconvolutionCheckBox->isChecked()); settings.setValue("BACdistLineEdit", cdw->ui->BACdistLineEdit->text()); settings.setValue("BACgapsizeLineEdit", cdw->ui->BACgapsizeLineEdit->text()); settings.setValue("BACmagLineEdit", cdw->ui->BACmagLineEdit->text()); settings.setValue("BACmefLineEdit", cdw->ui->BACmefLineEdit->text()); settings.setValue("BACmethodComboBox", cdw->ui->BACmethodComboBox->currentIndex()); settings.setValue("BACrescaleCheckBox", cdw->ui->BACrescaleCheckBox->isChecked()); settings.setValue("BACwindowLineEdit", cdw->ui->BACwindowLineEdit->text()); settings.setValue("BACminWindowLineEdit", cdw->ui->BACminWindowLineEdit->text()); settings.setValue("BIPSpinBox", cdw->ui->BIPSpinBox->value()); settings.setValue("BIPrejectCheckBox", cdw->ui->BIPrejectCheckBox->isChecked()); settings.setValue("CGWbackclustolLineEdit", cdw->ui->CGWbackclustolLineEdit->text()); settings.setValue("CGWbackcoltolLineEdit", cdw->ui->CGWbackcoltolLineEdit->text()); settings.setValue("CGWbackmaxLineEdit", cdw->ui->CGWbackmaxLineEdit->text()); settings.setValue("CGWbackminLineEdit", cdw->ui->CGWbackminLineEdit->text()); settings.setValue("CGWbackrowtolLineEdit", cdw->ui->CGWbackrowtolLineEdit->text()); settings.setValue("CGWbacksmoothLineEdit", cdw->ui->CGWbacksmoothLineEdit->text()); settings.setValue("CGWdarkmaxLineEdit", cdw->ui->CGWdarkmaxLineEdit->text()); settings.setValue("CGWdarkminLineEdit", cdw->ui->CGWdarkminLineEdit->text()); settings.setValue("CGWflatclustolLineEdit", cdw->ui->CGWflatclustolLineEdit->text()); settings.setValue("CGWflatcoltolLineEdit", cdw->ui->CGWflatcoltolLineEdit->text()); settings.setValue("CGWflatmaxLineEdit", cdw->ui->CGWflatmaxLineEdit->text()); settings.setValue("CGWflatminLineEdit", cdw->ui->CGWflatminLineEdit->text()); settings.setValue("CGWflatrowtolLineEdit", cdw->ui->CGWflatrowtolLineEdit->text()); settings.setValue("CGWflatsmoothLineEdit", cdw->ui->CGWflatsmoothLineEdit->text()); settings.setValue("CGWsameweightCheckBox", cdw->ui->CGWsameweightCheckBox->isChecked()); settings.setValue("CIWsaturationLineEdit", cdw->ui->CIWsaturationLineEdit->text()); settings.setValue("CIWbloomRangeLineEdit", cdw->ui->CIWbloomRangeLineEdit->text()); settings.setValue("CIWbloomMinaduLineEdit", cdw->ui->CIWbloomMinaduLineEdit->text()); settings.setValue("CIWaggressivenessLineEdit", cdw->ui->CIWaggressivenessLineEdit->text()); settings.setValue("CIWmaskbloomingCheckBox", cdw->ui->CIWmaskbloomingCheckBox->isChecked()); settings.setValue("CIWmasksaturationCheckBox", cdw->ui->CIWmasksaturationCheckBox->isChecked()); settings.setValue("CIWmaxaduLineEdit", cdw->ui->CIWmaxaduLineEdit->text()); settings.setValue("CIWminaduLineEdit", cdw->ui->CIWminaduLineEdit->text()); settings.setValue("COAcelestialtypeComboBox", cdw->ui->COAcelestialtypeComboBox->currentIndex()); settings.setValue("COAchipsLineEdit", cdw->ui->COAchipsLineEdit->text()); settings.setValue("COAcombinetypeComboBox", cdw->ui->COAcombinetypeComboBox->currentIndex()); settings.setValue("COAdecLineEdit", cdw->ui->COAdecLineEdit->text()); settings.setValue("COAedgesmoothingLineEdit", cdw->ui->COAedgesmoothingLineEdit->text()); settings.setValue("COAfluxcalibCheckBox", cdw->ui->COAfluxcalibCheckBox->isChecked()); settings.setValue("COAkernelComboBox", cdw->ui->COAkernelComboBox->currentIndex()); settings.setValue("COAoutborderLineEdit", cdw->ui->COAoutborderLineEdit->text()); settings.setValue("COAoutsizeLineEdit", cdw->ui->COAoutsizeLineEdit->text()); settings.setValue("COAoutthreshLineEdit", cdw->ui->COAoutthreshLineEdit->text()); settings.setValue("COApixscaleLineEdit", cdw->ui->COApixscaleLineEdit->text()); settings.setValue("COApmComboBox", cdw->ui->COApmComboBox->currentIndex()); settings.setValue("COApmdecLineEdit", cdw->ui->COApmdecLineEdit->text()); settings.setValue("COApmraLineEdit", cdw->ui->COApmraLineEdit->text()); settings.setValue("COAprojectionComboBox", cdw->ui->COAprojectionComboBox->currentIndex()); settings.setValue("COAraLineEdit", cdw->ui->COAraLineEdit->text()); settings.setValue("COArescaleweightsCheckBox", cdw->ui->COArescaleweightsCheckBox->isChecked()); settings.setValue("COAsizexLineEdit", cdw->ui->COAsizexLineEdit->text()); settings.setValue("COAsizeyLineEdit", cdw->ui->COAsizeyLineEdit->text()); settings.setValue("COAskypaLineEdit", cdw->ui->COAskypaLineEdit->text()); settings.setValue("COAuniqueidLineEdit", cdw->ui->COAuniqueidLineEdit->text()); settings.setValue("COCDMINLineEdit", cdw->ui->COCDMINLineEdit->text()); settings.setValue("COCDTLineEdit", cdw->ui->COCDTLineEdit->text()); settings.setValue("COCdirectionComboBox", cdw->ui->COCdirectionComboBox->currentIndex()); settings.setValue("COCmefLineEdit", cdw->ui->COCmefLineEdit->text()); settings.setValue("COCrejectLineEdit", cdw->ui->COCrejectLineEdit->text()); settings.setValue("COCxmaxLineEdit", cdw->ui->COCxmaxLineEdit->text()); settings.setValue("COCxminLineEdit", cdw->ui->COCxminLineEdit->text()); settings.setValue("COCymaxLineEdit", cdw->ui->COCymaxLineEdit->text()); settings.setValue("COCyminLineEdit", cdw->ui->COCyminLineEdit->text()); settings.setValue("CSCDMINLineEdit", cdw->ui->CSCDMINLineEdit->text()); settings.setValue("CSCDTLineEdit", cdw->ui->CSCDTLineEdit->text()); settings.setValue("CSCFWHMLineEdit", cdw->ui->CSCFWHMLineEdit->text()); settings.setValue("CSCbackgroundLineEdit", cdw->ui->CSCbackgroundLineEdit->text()); settings.setValue("CSCmaxflagLineEdit", cdw->ui->CSCmaxflagLineEdit->text()); settings.setValue("CSCmincontLineEdit", cdw->ui->CSCmincontLineEdit->text()); settings.setValue("CSCrejectExposureLineEdit", cdw->ui->CSCrejectExposureLineEdit->text()); settings.setValue("CSCconvolutionCheckBox", cdw->ui->CSCconvolutionCheckBox->isChecked()); settings.setValue("CSCsamplingCheckBox", cdw->ui->CSCsamplingCheckBox->isChecked()); settings.setValue("CSCsaturationLineEdit", cdw->ui->CSCsaturationLineEdit->text()); settings.setValue("CSCMethodComboBox", cdw->ui->CSCMethodComboBox->currentIndex()); settings.setValue("SPSlengthLineEdit", cdw->ui->SPSlengthLineEdit->text()); settings.setValue("SPSexcludeLineEdit", cdw->ui->SPSexcludeLineEdit->text()); settings.setValue("SPSnumbergroupsLineEdit", cdw->ui->SPSnumbergroupsLineEdit->text()); settings.setValue("biasMaxLineEdit", cdw->ui->biasMaxLineEdit->text()); settings.setValue("biasMinLineEdit", cdw->ui->biasMinLineEdit->text()); settings.setValue("biasNhighLineEdit", cdw->ui->biasNhighLineEdit->text()); settings.setValue("biasNlowLineEdit", cdw->ui->biasNlowLineEdit->text()); settings.setValue("biasMethodComboBox", cdw->ui->biasMethodComboBox->currentIndex()); settings.setValue("chopnodComboBox", cdw->ui->chopnodComboBox->currentIndex()); settings.setValue("chopnodInvertCheckBox", cdw->ui->chopnodInvertCheckBox->isChecked()); settings.setValue("confStackedWidget", cdw->ui->confStackedWidget->currentIndex()); settings.setValue("darkMaxLineEdit", cdw->ui->darkMaxLineEdit->text()); settings.setValue("darkMinLineEdit", cdw->ui->darkMinLineEdit->text()); settings.setValue("darkNhighLineEdit", cdw->ui->darkNhighLineEdit->text()); settings.setValue("darkNlowLineEdit", cdw->ui->darkNlowLineEdit->text()); settings.setValue("darkMethodComboBox", cdw->ui->darkMethodComboBox->currentIndex()); settings.setValue("excludeDetectorsLineEdit", cdw->ui->excludeDetectorsLineEdit->text()); settings.setValue("flatMaxLineEdit", cdw->ui->flatMaxLineEdit->text()); settings.setValue("flatMinLineEdit", cdw->ui->flatMinLineEdit->text()); settings.setValue("flatNhighLineEdit", cdw->ui->flatNhighLineEdit->text()); settings.setValue("flatNlowLineEdit", cdw->ui->flatNlowLineEdit->text()); settings.setValue("flatMethodComboBox", cdw->ui->flatMethodComboBox->currentIndex()); settings.setValue("flatoffMaxLineEdit", cdw->ui->flatoffMaxLineEdit->text()); settings.setValue("flatoffMinLineEdit", cdw->ui->flatoffMinLineEdit->text()); settings.setValue("flatoffNhighLineEdit", cdw->ui->flatoffNhighLineEdit->text()); settings.setValue("flatoffNlowLineEdit", cdw->ui->flatoffNlowLineEdit->text()); settings.setValue("flatoffMethodComboBox", cdw->ui->flatoffMethodComboBox->currentIndex()); settings.setValue("overscanCheckBox", cdw->ui->overscanCheckBox->isChecked()); settings.setValue("theliRenamingCheckBox", cdw->ui->theliRenamingCheckBox->isChecked()); settings.setValue("nonlinearityCheckBox", cdw->ui->nonlinearityCheckBox->isChecked()); settings.setValue("normalxtalkAmplitudeLineEdit", cdw->ui->normalxtalkAmplitudeLineEdit->text()); settings.setValue("normalxtalkCheckBox", cdw->ui->normalxtalkCheckBox->isChecked()); settings.setValue("overscanMethodComboBox", cdw->ui->overscanMethodComboBox->currentIndex()); settings.setValue("rowxtalkAmplitudeLineEdit", cdw->ui->rowxtalkAmplitudeLineEdit->text()); settings.setValue("rowxtalkCheckBox", cdw->ui->rowxtalkCheckBox->isChecked()); settings.setValue("saturationLineEdit", cdw->ui->saturationLineEdit->text()); settings.setValue("separateTargetLineEdit", cdw->ui->separateTargetLineEdit->text()); settings.setValue("skyAreaComboBox", cdw->ui->skyAreaComboBox->currentIndex()); settings.setValue("skyConstsubRadioButton", cdw->ui->skyConstsubRadioButton->isChecked()); settings.setValue("skyDMINLineEdit", cdw->ui->skyDMINLineEdit->text()); settings.setValue("skyDTLineEdit", cdw->ui->skyDTLineEdit->text()); settings.setValue("skyKernelLineEdit", cdw->ui->skyKernelLineEdit->text()); settings.setValue("skyMefLineEdit", cdw->ui->skyMefLineEdit->text()); settings.setValue("skyModelRadioButton", cdw->ui->skyModelRadioButton->isChecked()); settings.setValue("skyPolynomialRadioButton", cdw->ui->skyPolynomialRadioButton->isChecked()); settings.setValue("skyPolynomialSpinBox", cdw->ui->skyPolynomialSpinBox->value()); settings.setValue("skySavemodelCheckBox", cdw->ui->skySavemodelCheckBox->isChecked()); settings.setValue("splitMIRcubeCheckBox", cdw->ui->splitMIRcubeCheckBox->isChecked()); settings.setValue("xtalk_col_1x2ToolButton", cdw->ui->xtalk_col_1x2ToolButton->isChecked()); settings.setValue("xtalk_col_2x1ToolButton", cdw->ui->xtalk_col_2x1ToolButton->isChecked()); settings.setValue("xtalk_col_2x2ToolButton", cdw->ui->xtalk_col_2x2ToolButton->isChecked()); settings.setValue("xtalk_nor_1x2ToolButton", cdw->ui->xtalk_nor_1x2ToolButton->isChecked()); settings.setValue("xtalk_nor_2x1ToolButton", cdw->ui->xtalk_nor_2x1ToolButton->isChecked()); settings.setValue("xtalk_nor_2x2ToolButton", cdw->ui->xtalk_nor_2x2ToolButton->isChecked()); settings.setValue("xtalk_row_1x2ToolButton", cdw->ui->xtalk_row_1x2ToolButton->isChecked()); settings.setValue("xtalk_row_2x1ToolButton", cdw->ui->xtalk_row_2x1ToolButton->isChecked()); settings.setValue("xtalk_row_2x2ToolButton", cdw->ui->xtalk_row_2x2ToolButton->isChecked()); // MAIN WINDOW settings.setValue("applyAbsphotindirectCheckBox", ui->applyAbsphotindirectCheckBox->isChecked()); settings.setValue("applyAstromphotomCheckBox", ui->applyAstromphotomCheckBox->isChecked()); settings.setValue("applyBackgroundCheckBox", ui->applyBackgroundCheckBox->isChecked()); settings.setValue("applyBinnedpreviewCheckBox", ui->applyBinnedpreviewCheckBox->isChecked()); settings.setValue("applyChopnodCheckBox", ui->applyChopnodCheckBox->isChecked()); settings.setValue("applyCoadditionCheckBox", ui->applyCoadditionCheckBox->isChecked()); settings.setValue("applyCollapseCheckBox", ui->applyCollapseCheckBox->isChecked()); settings.setValue("applyCreatesourcecatCheckBox", ui->applyCreatesourcecatCheckBox->isChecked()); settings.setValue("applyGlobalweightCheckBox", ui->applyGlobalweightCheckBox->isChecked()); settings.setValue("applyHDUreformatCheckBox", ui->applyHDUreformatCheckBox->isChecked()); settings.setValue("applyIndividualweightCheckBox", ui->applyIndividualweightCheckBox->isChecked()); settings.setValue("applyProcessbiasCheckBox", ui->applyProcessbiasCheckBox->isChecked()); settings.setValue("applyProcessdarkCheckBox", ui->applyProcessdarkCheckBox->isChecked()); settings.setValue("applyProcessflatCheckBox", ui->applyProcessflatCheckBox->isChecked()); settings.setValue("applyProcessflatoffCheckBox", ui->applyProcessflatoffCheckBox->isChecked()); settings.setValue("applyProcessscienceCheckBox", ui->applyProcessscienceCheckBox->isChecked()); settings.setValue("applySeparateCheckBox", ui->applySeparateCheckBox->isChecked()); settings.setValue("applySkysubCheckBox", ui->applySkysubCheckBox->isChecked()); settings.setValue("applyStarflatCheckBox", ui->applyStarflatCheckBox->isChecked()); settings.setValue("processingTabWidget", ui->processingTabWidget->currentIndex()); settings.setValue("setupBiasLineEdit", ui->setupBiasLineEdit->text()); settings.setValue("setupDarkLineEdit", ui->setupDarkLineEdit->text()); settings.setValue("setupFlatLineEdit", ui->setupFlatLineEdit->text()); settings.setValue("setupFlatoffLineEdit", ui->setupFlatoffLineEdit->text()); settings.setValue("setupInstrumentComboBox", ui->setupInstrumentComboBox->currentText()); settings.setValue("setupMainLineEdit", ui->setupMainLineEdit->text()); settings.setValue("setupProjectLineEdit", ui->setupProjectLineEdit->text()); settings.setValue("setupScienceLineEdit", ui->setupScienceLineEdit->text()); settings.setValue("setupSkyLineEdit", ui->setupSkyLineEdit->text()); settings.setValue("setupStandardLineEdit", ui->setupStandardLineEdit->text()); settings.endGroup(); settings.sync(); return settings.status(); } int MainWindow::readGUISettings(QString projectname) { preventLoop_WriteSettings = true; if (projectname.isEmpty()) { projectname = "MyProject"; ui->setupProjectLineEdit->setText(projectname); cdw->loadDefaults(); fill_setupInstrumentComboBox(); preventLoop_WriteSettings = false; return 3; // not checked } QSettings settings("THELI", projectname); settings.beginGroup("MainWindow"); readingSettings = true; setStatusFromSettings(settings.value("statusString").toString()); // CONF DOCK WIDGET cdw->ui->APDfilterComboBox->setCurrentIndex(settings.value("APDfilterComboBox").toInt()); cdw->ui->APDmaxphoterrorLineEdit->setText(settings.value("APDmaxphoterrorLineEdit").toString()); cdw->ui->APDrefcatComboBox->setCurrentIndex(settings.value("APDrefcatComboBox").toInt()); cdw->ui->APIWCSCheckBox->setChecked(settings.value("APIWCSCheckBox").toBool()); cdw->ui->APIWCSLineEdit->setText(settings.value("APIWCSLineEdit").toString()); cdw->ui->APIapertureLineEdit->setText(settings.value("APIapertureLineEdit").toString()); cdw->ui->APIcalibrationmodeComboBox->setCurrentIndex(settings.value("APIcalibrationmodeComboBox").toInt()); cdw->ui->APIcolorComboBox->setCurrentIndex(settings.value("APIcolorComboBox").toInt()); cdw->ui->APIcolortermLineEdit->setText(settings.value("APIcolortermLineEdit").toString()); cdw->ui->APIconvergenceLineEdit->setText(settings.value("APIconvergenceLineEdit").toString()); cdw->ui->APIextinctionLineEdit->setText(settings.value("APIextinctionLineEdit").toString()); cdw->ui->APIfilterComboBox->setCurrentIndex(settings.value("APIfilterComboBox").toInt()); cdw->ui->APIfilterkeywordLineEdit->setText(settings.value("APIfilterkeywordLineEdit").toString()); cdw->ui->APIkappaLineEdit->setText(settings.value("APIkappaLineEdit").toString()); cdw->ui->APIminmagLineEdit->setText(settings.value("APIminmagLineEdit").toString()); cdw->ui->APInight1ComboBox->setCurrentIndex(settings.value("APInight1ComboBox").toInt()); cdw->ui->APInight2ComboBox->setCurrentIndex(settings.value("APInight2ComboBox").toInt()); cdw->ui->APInight3ComboBox->setCurrentIndex(settings.value("APInight3ComboBox").toInt()); cdw->ui->APInight4ComboBox->setCurrentIndex(settings.value("APInight4ComboBox").toInt()); cdw->ui->APInight5ComboBox->setCurrentIndex(settings.value("APInight5ComboBox").toInt()); cdw->ui->APInight6ComboBox->setCurrentIndex(settings.value("APInight6ComboBox").toInt()); cdw->ui->APInight7ComboBox->setCurrentIndex(settings.value("APInight7ComboBox").toInt()); cdw->ui->APInight8ComboBox->setCurrentIndex(settings.value("APInight8ComboBox").toInt()); cdw->ui->APInight9ComboBox->setCurrentIndex(settings.value("APInight9ComboBox").toInt()); cdw->ui->APIrefcatComboBox->setCurrentIndex(settings.value("APIrefcatComboBox").toInt()); cdw->ui->APIthresholdLineEdit->setText(settings.value("APIthresholdLineEdit").toString()); cdw->ui->APIzpmaxLineEdit->setText(settings.value("APIzpmaxLineEdit").toString()); cdw->ui->APIzpminLineEdit->setText(settings.value("APIzpminLineEdit").toString()); cdw->ui->ARCDMINLineEdit->setText(settings.value("ARCDMINLineEdit").toString()); cdw->ui->ARCDTLineEdit->setText(settings.value("ARCDTLineEdit").toString()); cdw->ui->ARCcatalogComboBox->setCurrentIndex(settings.value("ARCcatalogComboBox").toInt()); cdw->ui->ARCdecLineEdit->setText(settings.value("ARCdecLineEdit").toString()); cdw->ui->ARCimageRadioButton->setChecked(settings.value("ARCimageRadioButton").toBool()); cdw->ui->ARCmaxpmLineEdit->setText(settings.value("ARCmaxpmLineEdit").toString()); cdw->ui->ARCpmRALineEdit->setText(settings.value("ARCpmRALineEdit").toString()); cdw->ui->ARCpmDECLineEdit->setText(settings.value("ARCpmDECLineEdit").toString()); cdw->ui->ARCminmagLineEdit->setText(settings.value("ARCminmagLineEdit").toString()); cdw->ui->ARCraLineEdit->setText(settings.value("ARCraLineEdit").toString()); cdw->ui->ARCradiusLineEdit->setText(settings.value("ARCradiusLineEdit").toString()); cdw->ui->ARCselectimageLineEdit->setText(settings.value("ARCselectimageLineEdit").toString()); cdw->ui->ARCtargetresolverLineEdit->setText(settings.value("ARCtargetresolverLineEdit").toString()); cdw->ui->ARCwebRadioButton->setChecked(settings.value("ARCwebRadioButton").toBool()); cdw->ui->ASTastrefweightLineEdit->setText(settings.value("ASTastrefweightLineEdit").toString()); cdw->ui->ASTastrinstrukeyLineEdit->setText(settings.value("ASTastrinstrukeyLineEdit").toString()); cdw->ui->ASTcrossidLineEdit->setText(settings.value("ASTcrossidLineEdit").toString()); cdw->ui->ASTdistortLineEdit->setText(settings.value("ASTdistortLineEdit").toString()); cdw->ui->ASTdistortgroupsLineEdit->setText(settings.value("ASTdistortgroupsLineEdit").toString()); cdw->ui->ASTdistortkeysLineEdit->setText(settings.value("ASTdistortkeysLineEdit").toString()); cdw->ui->ASTfocalplaneComboBox->setCurrentIndex(settings.value("ASTfocalplaneComboBox").toInt()); cdw->ui->ASTmatchMethodComboBox->setCurrentIndex(settings.value("ASTmatchMethodComboBox").toInt()); cdw->ui->ASTmatchflippedCheckBox->setChecked(settings.value("ASTmatchflippedCheckBox").toBool()); cdw->ui->ASTmethodComboBox->setCurrentIndex(settings.value("ASTmethodComboBox").toInt()); cdw->ui->ASTmosaictypeComboBox->setCurrentIndex(settings.value("ASTmosaictypeComboBox").toInt()); cdw->ui->ASTphotinstrukeyLineEdit->setText(settings.value("ASTphotinstrukeyLineEdit").toString()); cdw->ui->ASTpixscaleLineEdit->setText(settings.value("ASTpixscaleLineEdit").toString()); cdw->ui->ASTposangleLineEdit->setText(settings.value("ASTposangleLineEdit").toString()); cdw->ui->ASTpositionLineEdit->setText(settings.value("ASTpositionLineEdit").toString()); cdw->ui->ASTresolutionLineEdit->setText(settings.value("ASTresolutionLineEdit").toString()); cdw->ui->ASTsnthreshLineEdit->setText(settings.value("ASTsnthreshLineEdit").toString()); cdw->ui->ASTstabilityComboBox->setCurrentIndex(settings.value("ASTstabilityComboBox").toInt()); cdw->ui->ASTxcorrDTLineEdit->setText(settings.value("ASTxcorrDTLineEdit").toString()); cdw->ui->ASTxcorrDMINLineEdit->setText(settings.value("ASTxcorrDMINLineEdit").toString()); cdw->ui->BAC1nhighLineEdit->setText(settings.value("BAC1nhighLineEdit").toString()); cdw->ui->BAC1nlowLineEdit->setText(settings.value("BAC1nlowLineEdit").toString()); cdw->ui->BAC2nhighLineEdit->setText(settings.value("BAC2nhighLineEdit").toString()); cdw->ui->BAC2nlowLineEdit->setText(settings.value("BAC2nlowLineEdit").toString()); cdw->ui->BAC2passCheckBox->setChecked(settings.value("BAC2passCheckBox").toBool()); cdw->ui->BACDMINLineEdit->setText(settings.value("BACDMINLineEdit").toString()); cdw->ui->BACDTLineEdit->setText(settings.value("BACDTLineEdit").toString()); cdw->ui->BACapplyComboBox->setCurrentIndex(settings.value("BACapplyComboBox").toInt()); cdw->ui->BACbacksmoothscaleLineEdit->setText(settings.value("BACbacksmoothscaleLineEdit").toString()); cdw->ui->BACconvolutionCheckBox->setChecked(settings.value("BACconvolutionCheckBox").toBool()); cdw->ui->BACdistLineEdit->setText(settings.value("BACdistLineEdit").toString()); cdw->ui->BACgapsizeLineEdit->setText(settings.value("BACgapsizeLineEdit").toString()); cdw->ui->BACmagLineEdit->setText(settings.value("BACmagLineEdit").toString()); cdw->ui->BACmefLineEdit->setText(settings.value("BACmefLineEdit").toString()); cdw->ui->BACmethodComboBox->setCurrentIndex(settings.value("BACmethodComboBox").toInt()); cdw->ui->BACrescaleCheckBox->setChecked(settings.value("BACrescaleCheckBox").toBool()); cdw->ui->BACwindowLineEdit->setText(settings.value("BACwindowLineEdit").toString()); cdw->ui->BACminWindowLineEdit->setText(settings.value("BACminWindowLineEdit").toString()); cdw->ui->BIPSpinBox->setValue(settings.value("BIPSpinBox").toInt()); cdw->ui->BIPrejectCheckBox->setChecked(settings.value("BIPrejectCheckBox").toBool()); cdw->ui->CGWbackclustolLineEdit->setText(settings.value("CGWbackclustolLineEdit").toString()); cdw->ui->CGWbackcoltolLineEdit->setText(settings.value("CGWbackcoltolLineEdit").toString()); cdw->ui->CGWbackmaxLineEdit->setText(settings.value("CGWbackmaxLineEdit").toString()); cdw->ui->CGWbackminLineEdit->setText(settings.value("CGWbackminLineEdit").toString()); cdw->ui->CGWbackrowtolLineEdit->setText(settings.value("CGWbackrowtolLineEdit").toString()); cdw->ui->CGWbacksmoothLineEdit->setText(settings.value("CGWbacksmoothLineEdit").toString()); cdw->ui->CGWdarkmaxLineEdit->setText(settings.value("CGWdarkmaxLineEdit").toString()); cdw->ui->CGWdarkminLineEdit->setText(settings.value("CGWdarkminLineEdit").toString()); cdw->ui->CGWflatclustolLineEdit->setText(settings.value("CGWflatclustolLineEdit").toString()); cdw->ui->CGWflatcoltolLineEdit->setText(settings.value("CGWflatcoltolLineEdit").toString()); cdw->ui->CGWflatmaxLineEdit->setText(settings.value("CGWflatmaxLineEdit").toString()); cdw->ui->CGWflatminLineEdit->setText(settings.value("CGWflatminLineEdit").toString()); cdw->ui->CGWflatrowtolLineEdit->setText(settings.value("CGWflatrowtolLineEdit").toString()); cdw->ui->CGWflatsmoothLineEdit->setText(settings.value("CGWflatsmoothLineEdit").toString()); cdw->ui->CGWsameweightCheckBox->setChecked(settings.value("CGWsameweightCheckBox").toBool()); cdw->ui->CIWsaturationLineEdit->setText(settings.value("CIWsaturationLineEdit").toString()); cdw->ui->CIWbloomRangeLineEdit->setText(settings.value("CIWbloomRangeLineEdit").toString()); cdw->ui->CIWbloomMinaduLineEdit->setText(settings.value("CIWbloomMinaduLineEdit").toString()); cdw->ui->CIWaggressivenessLineEdit->setText(settings.value("CIWaggressivenessLineEdit").toString()); cdw->ui->CIWmaskbloomingCheckBox->setChecked(settings.value("CIWmaskbloomingCheckBox").toBool()); cdw->ui->CIWmasksaturationCheckBox->setChecked(settings.value("CIWmasksaturationCheckBox").toBool()); cdw->ui->CIWmaxaduLineEdit->setText(settings.value("CIWmaxaduLineEdit").toString()); cdw->ui->CIWminaduLineEdit->setText(settings.value("CIWminaduLineEdit").toString()); cdw->ui->COAcelestialtypeComboBox->setCurrentIndex(settings.value("COAcelestialtypeComboBox").toInt()); cdw->ui->COAchipsLineEdit->setText(settings.value("COAchipsLineEdit").toString()); cdw->ui->COAcombinetypeComboBox->setCurrentIndex(settings.value("COAcombinetypeComboBox").toInt()); cdw->ui->COAdecLineEdit->setText(settings.value("COAdecLineEdit").toString()); cdw->ui->COAedgesmoothingLineEdit->setText(settings.value("COAedgesmoothingLineEdit").toString()); cdw->ui->COAfluxcalibCheckBox->setChecked(settings.value("COAfluxcalibCheckBox").toBool()); cdw->ui->COAkernelComboBox->setCurrentIndex(settings.value("COAkernelComboBox").toInt()); cdw->ui->COAoutborderLineEdit->setText(settings.value("COAoutborderLineEdit").toString()); cdw->ui->COAoutsizeLineEdit->setText(settings.value("COAoutsizeLineEdit").toString()); cdw->ui->COAoutthreshLineEdit->setText(settings.value("COAoutthreshLineEdit").toString()); cdw->ui->COApixscaleLineEdit->setText(settings.value("COApixscaleLineEdit").toString()); cdw->ui->COApmComboBox->setCurrentIndex(settings.value("COApmComboBox").toInt()); cdw->ui->COApmdecLineEdit->setText(settings.value("COApmdecLineEdit").toString()); cdw->ui->COApmraLineEdit->setText(settings.value("COApmraLineEdit").toString()); cdw->ui->COAprojectionComboBox->setCurrentIndex(settings.value("COAprojectionComboBox").toInt()); cdw->ui->COAraLineEdit->setText(settings.value("COAraLineEdit").toString()); cdw->ui->COArescaleweightsCheckBox->setChecked(settings.value("COArescaleweightsCheckBox").toBool()); cdw->ui->COAsizexLineEdit->setText(settings.value("COAsizexLineEdit").toString()); cdw->ui->COAsizeyLineEdit->setText(settings.value("COAsizeyLineEdit").toString()); cdw->ui->COAskypaLineEdit->setText(settings.value("COAskypaLineEdit").toString()); cdw->ui->COAuniqueidLineEdit->setText(settings.value("COAuniqueidLineEdit").toString()); cdw->ui->COCDMINLineEdit->setText(settings.value("COCDMINLineEdit").toString()); cdw->ui->COCDTLineEdit->setText(settings.value("COCDTLineEdit").toString()); cdw->ui->COCdirectionComboBox->setCurrentIndex(settings.value("COCdirectionComboBox").toInt()); cdw->ui->COCmefLineEdit->setText(settings.value("COCmefLineEdit").toString()); cdw->ui->COCrejectLineEdit->setText(settings.value("COCrejectLineEdit").toString()); cdw->ui->COCxmaxLineEdit->setText(settings.value("COCxmaxLineEdit").toString()); cdw->ui->COCxminLineEdit->setText(settings.value("COCxminLineEdit").toString()); cdw->ui->COCymaxLineEdit->setText(settings.value("COCymaxLineEdit").toString()); cdw->ui->COCyminLineEdit->setText(settings.value("COCyminLineEdit").toString()); cdw->ui->CSCDMINLineEdit->setText(settings.value("CSCDMINLineEdit").toString()); cdw->ui->CSCDTLineEdit->setText(settings.value("CSCDTLineEdit").toString()); cdw->ui->CSCFWHMLineEdit->setText(settings.value("CSCFWHMLineEdit").toString()); cdw->ui->CSCbackgroundLineEdit->setText(settings.value("CSCbackgroundLineEdit").toString()); cdw->ui->CSCmaxflagLineEdit->setText(settings.value("CSCmaxflagLineEdit").toString()); cdw->ui->CSCMethodComboBox->setCurrentIndex(settings.value("CSCMethodComboBox").toInt()); cdw->ui->CSCmincontLineEdit->setText(settings.value("CSCmincontLineEdit").toString()); cdw->ui->CSCrejectExposureLineEdit->setText(settings.value("CSCrejectExposureLineEdit").toString()); cdw->ui->CSCconvolutionCheckBox->setChecked(settings.value("CSCconvolutionCheckBox").toBool()); cdw->ui->CSCsamplingCheckBox->setChecked(settings.value("CSCsamplingCheckBox").toBool()); cdw->ui->CSCsaturationLineEdit->setText(settings.value("CSCsaturationLineEdit").toString()); cdw->ui->SPSlengthLineEdit->setText(settings.value("SPSlengthLineEdit").toString()); cdw->ui->SPSnumbergroupsLineEdit->setText(settings.value("SPSnumbergroupsLineEdit").toString()); cdw->ui->SPSexcludeLineEdit->setText(settings.value("SPSexcludeLineEdit").toString()); cdw->ui->biasMaxLineEdit->setText(settings.value("biasMaxLineEdit").toString()); cdw->ui->biasMinLineEdit->setText(settings.value("biasMinLineEdit").toString()); cdw->ui->biasNhighLineEdit->setText(settings.value("biasNhighLineEdit").toString()); cdw->ui->biasNlowLineEdit->setText(settings.value("biasNlowLineEdit").toString()); cdw->ui->biasMethodComboBox->setCurrentIndex(settings.value("biasMethodComboBox").toInt()); cdw->ui->chopnodComboBox->setCurrentIndex(settings.value("chopnodComboBox").toInt()); cdw->ui->chopnodInvertCheckBox->setChecked(settings.value("chopnodInvertCheckBox").toBool()); cdw->ui->darkMaxLineEdit->setText(settings.value("darkMaxLineEdit").toString()); cdw->ui->darkMinLineEdit->setText(settings.value("darkMinLineEdit").toString()); cdw->ui->darkNhighLineEdit->setText(settings.value("darkNhighLineEdit").toString()); cdw->ui->darkNlowLineEdit->setText(settings.value("darkNlowLineEdit").toString()); cdw->ui->darkMethodComboBox->setCurrentIndex(settings.value("darkMethodComboBox").toInt()); cdw->ui->excludeDetectorsLineEdit->setText(settings.value("excludeDetectorsLineEdit").toString()); cdw->ui->flatMaxLineEdit->setText(settings.value("flatMaxLineEdit").toString()); cdw->ui->flatMinLineEdit->setText(settings.value("flatMinLineEdit").toString()); cdw->ui->flatNhighLineEdit->setText(settings.value("flatNhighLineEdit").toString()); cdw->ui->flatNlowLineEdit->setText(settings.value("flatNlowLineEdit").toString()); cdw->ui->flatMethodComboBox->setCurrentIndex(settings.value("flatMethodComboBox").toInt()); cdw->ui->flatoffMaxLineEdit->setText(settings.value("flatoffMaxLineEdit").toString()); cdw->ui->flatoffMinLineEdit->setText(settings.value("flatoffMinLineEdit").toString()); cdw->ui->flatoffNhighLineEdit->setText(settings.value("flatoffNhighLineEdit").toString()); cdw->ui->flatoffNlowLineEdit->setText(settings.value("flatoffNlowLineEdit").toString()); cdw->ui->flatoffMethodComboBox->setCurrentIndex(settings.value("flatoffMethodComboBox").toInt()); cdw->ui->skyAreaComboBox->setCurrentIndex(settings.value("skyAreaComboBox").toInt()); cdw->ui->skyConstsubRadioButton->setChecked(settings.value("skyConstsubRadioButton").toBool()); cdw->ui->skyDMINLineEdit->setText(settings.value("skyDMINLineEdit").toString()); cdw->ui->skyDTLineEdit->setText(settings.value("skyDTLineEdit").toString()); cdw->ui->skyKernelLineEdit->setText(settings.value("skyKernelLineEdit").toString()); cdw->ui->skyMefLineEdit->setText(settings.value("skyMefLineEdit").toString()); cdw->ui->skyModelRadioButton->setChecked(settings.value("skyModelRadioButton").toBool()); cdw->ui->skyPolynomialRadioButton->setChecked(settings.value("skyPolynomialRadioButton").toBool()); cdw->ui->skyPolynomialSpinBox->setValue(settings.value("skyPolynomialSpinBox").toInt()); cdw->ui->skySavemodelCheckBox->setChecked(settings.value("skySavemodelCheckBox").toBool()); cdw->ui->theliRenamingCheckBox->setChecked(settings.value("theliRenamingCheckBox").toBool()); cdw->ui->overscanCheckBox->setChecked(settings.value("overscanCheckBox").toBool()); cdw->ui->nonlinearityCheckBox->setChecked(settings.value("nonlinearityCheckBox").toBool()); cdw->ui->normalxtalkAmplitudeLineEdit->setText(settings.value("normalxtalkAmplitudeLineEdit").toString()); cdw->ui->normalxtalkCheckBox->setChecked(settings.value("normalxtalkCheckBox").toBool()); cdw->ui->overscanMethodComboBox->setCurrentIndex(settings.value("overscanMethodComboBox").toInt()); cdw->ui->splitMIRcubeCheckBox->setChecked(settings.value("splitMIRcubeCheckBox").toBool()); cdw->ui->xtalk_col_1x2ToolButton->setChecked(settings.value("xtalk_col_1x2ToolButton").toBool()); cdw->ui->xtalk_col_2x1ToolButton->setChecked(settings.value("xtalk_col_2x1ToolButton").toBool()); cdw->ui->xtalk_col_2x2ToolButton->setChecked(settings.value("xtalk_col_2x2ToolButton").toBool()); cdw->ui->xtalk_nor_1x2ToolButton->setChecked(settings.value("xtalk_nor_1x2ToolButton").toBool()); cdw->ui->xtalk_nor_2x1ToolButton->setChecked(settings.value("xtalk_nor_2x1ToolButton").toBool()); cdw->ui->xtalk_nor_2x2ToolButton->setChecked(settings.value("xtalk_nor_2x2ToolButton").toBool()); cdw->ui->xtalk_row_1x2ToolButton->setChecked(settings.value("xtalk_row_1x2ToolButton").toBool()); cdw->ui->xtalk_row_2x1ToolButton->setChecked(settings.value("xtalk_row_2x1ToolButton").toBool()); cdw->ui->xtalk_row_2x2ToolButton->setChecked(settings.value("xtalk_row_2x2ToolButton").toBool()); cdw->ui->confStackedWidget->setCurrentIndex(settings.value("confStackedWidget").toInt()); cdw->ui->rowxtalkAmplitudeLineEdit->setText(settings.value("rowxtalkAmplitudeLineEdit").toString()); cdw->ui->rowxtalkCheckBox->setChecked(settings.value("rowxtalkCheckBox").toBool()); cdw->ui->saturationLineEdit->setText(settings.value("saturationLineEdit").toString()); cdw->ui->separateTargetLineEdit->setText(settings.value("separateTargetLineEdit").toString()); // MAIN WINDOW ui->applyAbsphotindirectCheckBox->setChecked(settings.value("applyAbsphotindirectCheckBox").toBool()); ui->applyAstromphotomCheckBox->setChecked(settings.value("applyAstromphotomCheckBox").toBool()); ui->applyBackgroundCheckBox->setChecked(settings.value("applyBackgroundCheckBox").toBool()); ui->applyBinnedpreviewCheckBox->setChecked(settings.value("applyBinnedpreviewCheckBox").toBool()); ui->applyChopnodCheckBox->setChecked(settings.value("applyChopnodCheckBox").toBool()); ui->applyCoadditionCheckBox->setChecked(settings.value("applyCoadditionCheckBox").toBool()); ui->applyCollapseCheckBox->setChecked(settings.value("applyCollapseCheckBox").toBool()); ui->applyCreatesourcecatCheckBox->setChecked(settings.value("applyCreatesourcecatCheckBox").toBool()); ui->applyGlobalweightCheckBox->setChecked(settings.value("applyGlobalweightCheckBox").toBool()); ui->applyHDUreformatCheckBox->setChecked(settings.value("applyHDUreformatCheckBox").toBool()); ui->applyIndividualweightCheckBox->setChecked(settings.value("applyIndividualweightCheckBox").toBool()); ui->applyProcessbiasCheckBox->setChecked(settings.value("applyProcessbiasCheckBox").toBool()); ui->applyProcessdarkCheckBox->setChecked(settings.value("applyProcessdarkCheckBox").toBool()); ui->applyProcessflatCheckBox->setChecked(settings.value("applyProcessflatCheckBox").toBool()); ui->applyProcessflatoffCheckBox->setChecked(settings.value("applyProcessflatoffCheckBox").toBool()); ui->applyProcessscienceCheckBox->setChecked(settings.value("applyProcessscienceCheckBox").toBool()); ui->applySeparateCheckBox->setChecked(settings.value("applySeparateCheckBox").toBool()); ui->applySkysubCheckBox->setChecked(settings.value("applySkysubCheckBox").toBool()); ui->applyStarflatCheckBox->setChecked(settings.value("applyStarflatCheckBox").toBool()); ui->processingTabWidget->setCurrentIndex(settings.value("processingTabWidget").toInt()); fill_setupInstrumentComboBox(); // Must be populated first so that the matching entry can be selected ui->setupInstrumentComboBox->setCurrentText(settings.value("setupInstrumentComboBox").toString()); ui->setupBiasLineEdit->setText(settings.value("setupBiasLineEdit").toString()); ui->setupDarkLineEdit->setText(settings.value("setupDarkLineEdit").toString()); ui->setupFlatLineEdit->setText(settings.value("setupFlatLineEdit").toString()); ui->setupFlatoffLineEdit->setText(settings.value("setupFlatoffLineEdit").toString()); ui->setupMainLineEdit->setText(settings.value("setupMainLineEdit").toString()); ui->setupProjectLineEdit->setText(settings.value("setupProjectLineEdit").toString()); ui->setupScienceLineEdit->setText(settings.value("setupScienceLineEdit").toString()); ui->setupSkyLineEdit->setText(settings.value("setupSkyLineEdit").toString()); ui->setupStandardLineEdit->setText(settings.value("setupStandardLineEdit").toString()); settings.endGroup(); preventLoop_WriteSettings = false; readingSettings = false; // Housekeeping for correct display cdw->updateARCdisplay(); updatePreferences(); updateInstrumentComboBoxBackgroundColor(); return settings.status(); } THELI-3.1.3/src/status.cc000066400000000000000000000107651417631501300150160ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "status.h" #include "mainwindow.h" #include "ui_mainwindow.h" // Constructor Status::Status() { } // Set the background of the checkboxes according to the processing history void Status::history2checkbox() { int i=0; QPalette palette; for (auto &checked : listHistory) { if (checked) palette.setColor(QPalette::Button,QColor("#33e3cc")); else palette.setColor(QPalette::Button,QColor("#eeffff")); // Paint checkbox background listCheckBox.operator[](i)->setPalette(palette); listCheckBox.operator[](i)->setAutoFillBackground(true); ++i; } } // Triggered by mainguiworker (everytime a task is finished) void Status::updateStatusReceived(QString taskBasename, bool success) { int index = indexMap.value(taskBasename,-1); if (index == -1) return; else { listHistory.operator[](index) = success; updateStatus(); } } // Triggered by user actions in the main window. // Repaints the task checkboxes (among others) void Status::updateStatus() { int i=0; QPalette palette; for (auto &checked : listHistory) { if (checked) palette.setColor(QPalette::Button, QColor("#33e3cc")); else palette.setColor(QPalette::Button, QColor("#eeffff")); // Paint checkbox background listCheckBox.operator[](i)->setPalette(palette); listCheckBox.operator[](i)->setAutoFillBackground(true); // Only UNCHECK a task checkbox if the history changed to "executed", never CHECK it // because we don't know whether the user wants to redo it. if (checked) listCheckBox.operator[](i)->setChecked(false); ++i; } } void Status::clearAllCheckBoxes() { for (auto &cb : listCheckBox) cb->setChecked(false); } QString Status::getStatusFromHistory(bool keepblanks) { QString statusString; for (int i=0; i #include #include #include #include #include // This class keeps track of the data processing, mainly so that the GUI displays background color of tasks correctly. // The 'status' is not used to reflect the actual processing status of data. This is handled internally to the Data and MyImage classes. class Status : public QObject { Q_OBJECT public: Status(); void history2checkbox(); QString getStatusFromHistory(bool keepblanks = false); QString checkboxStatus(QCheckBox *cb); // These lists contain the tasks, in the order in which they occur in the GUI QList listHistory; // Whether a task has been executed or not; this is the central piece that rules it all QList listCheckBox; // the list of all task checkboxes QList listToolButtons; // the list of all tool buttons QList listName; // The unique ID string common to checkbox, undo Button and Action QList listDataDirs; // The list of all data dir LineEdits QList listCurrentValue; // The current string value (A,B,C,M,D or empty) associated with the checkbox QList listFixedValue; // (constant). A character for each task box, used to comprise the processing string QList listBreakpoints; // (constant). The character associated to each processing task (mostly blanks) QMap indexMap; // Identifies the index of a task (the order in which the task appears) // The number of task checkboxes in the GUI; sorry, hardcoded. const int numtasks = 19; void statusstringToHistory(QString &statusstring); void clearAllCheckBoxes(); private: // int lastExecutedTaskId(); signals: void statusChanged(); public slots: void updateStatus(); void updateStatusReceived(QString taskBasename, bool success); }; #endif // STATUS_H THELI-3.1.3/src/taskinfrastructure.cc000066400000000000000000001377031417631501300174400ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "ui_confdockwidget.h" #include "functions.h" #include "status.h" #include "threading/mainguiworker.h" #include "processingInternal/data.h" #include "processingExternal/errordialog.h" #include "datadir.h" #include "tools/cfitsioerrorcodes.h" #include #include #include #include #include #include QStringList MainWindow::matchCalibToScience(const QStringList scienceList, const QStringList calibList) { // This utility modifies the calib list so that it matches the science list in length. // Example: // science list contains S1, S2, S3 // calib list contains F. Then, at the end it will contain F, F, F // If calib list is empty, then at the end it will contain "", "", "" int nscience = scienceList.length(); int ncalib = calibList.length(); // Initialize the newCalibList with blanks and the same dimension as the scienceList. QStringList newCalibList; for (int i=0; i 1) { for (int i=0; itext().isEmpty()) return; // Convert data dir(s) to stringlists QStringList scienceList = datadir2StringList(scienceLineEdit); QStringList calib1List = datadir2StringList(calib1LineEdit); QStringList calib2List = datadir2StringList(calib2LineEdit); QStringList newCalib1List; QStringList newCalib2List; // Match the calib list to the science list (increase length if necessary) // If a LineEdit is not needed, an empty constructor is used in the caller, resulting in an empty stringList; newCalib1List = matchCalibToScience(scienceList, calib1List); newCalib2List = matchCalibToScience(scienceList, calib2List); // Last consistency check: if (scienceList.length() != newCalib1List.length() || scienceList.length() != newCalib2List.length()) { success = false; return; } QString main = ui->setupMainLineEdit->text(); // QString scriptArg; QString scriptArg_blank; QDir scienceDir; // Loop over directories, prepend maindir if necessary; // The idea is to produce strings "main science calib" separated by blanks, or "main science flagString". // We check elsewhere in areAllPathsValid() whether directories are good for (int i=0; i= 2) workingDir = list.at(1); else workingDir = list.at(0); commandList.append("MESSAGE::"+message+" "+workingDir); // The actual task commandList.append("RUN::"+taskBasename+":: "+arg1); } // Like above, but used for processscience, which may operate on science, sky or std // Also used for create source cat void MainWindow::updateProcessList(QStringList &commandList, QString taskBasename, QString arg1, QString arg2) { // This will show in the overview window which task is currently running QString message = taskCommentMap.value(taskBasename); QStringList list = arg1.split(" "); QString workingDir = ""; if (list.length() >= 2) workingDir = list.at(1); else workingDir = list.at(0); commandList.append("MESSAGE::"+message+" "+workingDir); // The actual task commandList.append("RUN::"+taskBasename+":: "+arg1+" "+arg2); } // This function collects the internal process calls // NOTE: THIS IS CALLED FOR EACH TASK SEQUENTIALLY QStringList MainWindow::createCommandlistBlock(QString taskBasename, QStringList goodDirList, bool &stop, const QString mode) { // Does the task exist in the checkbox map? QString taskName; if (checkboxMap.values().contains(taskBasename)) taskName = checkboxMap.key(taskBasename)->text(); else taskName = ""; if (goodDirList.isEmpty()) { message(ui->plainTextEdit, "STOP: No data were provided for '"+taskName+"' , or the data tree is inconsistent."); stop = true; return QStringList(); } DataDir datadir; datadir.numChips = instData.numChips; QStringList commandList; // Process science can act on DT_SCIENCE, SKY, STD and thus needs to distinguish between them QString scienceMode = ""; QString last = goodDirList.last(); if (last == "theli_DT_SCIENCE" || last == "theli_DT_SKY" || last == "theli_DT_STANDARDD") { scienceMode = last; goodDirList.removeLast(); // do not interpret the last string as a data directory; in this case it's a flag } // Loop over all directories found for the current task for (auto &it : goodDirList) { if (taskBasename != "ResolveTargetSidereal") datadir.setPaths(it); // triggers qdebug() message if just resolving a target // Now call a consistency check by the function's string representation. // The function name is "check_task()" // and it simply updates the 'stop' and 'skip' flags bool skip = false; bool test = QMetaObject::invokeMethod(this, ("check_task"+taskBasename).toStdString().c_str(), Qt::DirectConnection, Q_ARG(DataDir*, &datadir), Q_ARG(bool &, stop), Q_ARG(bool &, skip), Q_ARG(const QString, mode)); if (!test) { qDebug() << __func__ << "Could not evaluate QMetaObject."; stop = true; return QStringList(); } // Omit the current task if either skip or stop are true; // Several commands can be skipped, but we stop everything (at a later point below) at the first stop. if (stop) continue; if (skip) continue; QStringList tmpdirlist = it.split(" "); QString main = tmpdirlist.at(0); // Few (1?) exceptions were 'science' is not needed QString science = ""; if (tmpdirlist.length() >= 2) science = tmpdirlist.at(1); if (taskBasename == "HDUreformat" || taskBasename == "Processbias" || taskBasename == "Processdark" || taskBasename == "Processflatoff" || taskBasename == "Processflat" || taskBasename == "Binnedpreview" || taskBasename == "Background" || taskBasename == "Collapse" || taskBasename == "Globalweight" || taskBasename == "Individualweight" || taskBasename == "Skysub" || taskBasename == "ResolveTargetSidereal" || taskBasename == "GetCatalogFromIMAGE" || taskBasename == "RestoreHeader" || taskBasename == "Separate") { updateProcessList(commandList, taskBasename, it); } /* if (taskBasename == "Background" && mode == "simulate" && ui->applyBackgroundCheckBox->isChecked()) { QSettings settings("THELI", "PREFERENCES"); int maxCPU = settings.value("prefCPUSpinBox").toInt(); if (maxCPU > 1) { QMessageBox::warning(this, tr("Parallelization unstable"), tr("You are running the background modelling with more than 1 CPU. ") + tr("Parallel background modeling COULD be unstable and might crash THELI, in which case you have to manually delete all *PAB.fits files from the data directory.\n") + tr("Use a single CPU if you have problems. Once background modeling is done, you can revert to full parallelization."), QMessageBox::Ok); } } */ if (taskBasename == "Processscience") { updateProcessList(commandList, taskBasename, it, scienceMode); } if (taskBasename == "Createsourcecat") { QString coordsMode = manualCoordsUpdate(science, mode); updateProcessList(commandList, taskBasename, it, coordsMode); } if (taskBasename == "GetCatalogFromWEB") { if (!checkCatalogUsability(mode)) { stop = true; return QStringList(); } updateProcessList(commandList, "GetCatalogFromWEB", it); } if (taskBasename == "Astromphotom") { // do we need to update the reference catalog? if (!isRefcatRecent(main+"/"+science)) { if (cdw->ui->ASTmethodComboBox->currentText() == "Scamp" || cdw->ui->ASTmethodComboBox->currentText() == "astrometry.net") { if (cdw->ui->ARCwebRadioButton->isChecked()) { if (!checkCatalogUsability(mode)) { stop = true; return QStringList(); } updateProcessList(commandList, "GetCatalogFromWEB", it); } else { updateProcessList(commandList, "GetCatalogFromIMAGE", it); } } } if (cdw->ui->ASTmethodComboBox->currentText() == "Scamp") { if (!cdw->checkRightScampMode(mode)) { message(ui->plainTextEdit, "Aborted, please choose a different MOSAIC_TYPE for scamp.", "stop"); stop = true; return QStringList(); } } // TODO // Put other methods here: a.net, x-corr, header-astrom updateProcessList(commandList, taskBasename, it); } if (taskBasename == "Coaddition") { // Check how many filters we have in the coadd dir QString filterChoice; QStringList filterlist = displayCoaddFilterChoice(main+"/"+science+"/", filterChoice, mode); // Suggest the user to add reference coordinates for a multi-color data set if (filterlist.length() > 1) { QString coordsMode = sameRefCoords(mode); if (coordsMode == "Cancel") { stop = true; return QStringList(); } } QString flag = ""; // Loop over all potential filters for (auto &filter : filterlist) { QString filterArg = ""; if (filterChoice == "Separately") { // for loop will run over each filter filterArg = filter; } else if (filterChoice == "all") { // for loop will run exactly once, because we break at the end filterArg = "all"; } else if (filterChoice == filter) { // for loop will run exactly once, because we break at the end filterArg = filter; flag = "individual"; } else if (filterChoice == "Abort") break; if (filterArg.isEmpty()) continue; updateProcessList(commandList, taskBasename, it+" "+filterArg); if (filterArg == "all" || flag == "individual") break; } if (filterlist.isEmpty()) updateProcessList(commandList, taskBasename, it+" "+"all"); } // TODO /* if (taskBasename == "Chopnod") { updateCommandList(commandList, taskBasename, science, it, count, "process_science_chopnod_para.sh"); } if (taskBasename == "Absphotindirect") { QString extension = tmpdirlist.at(2); QString standard = ui->setupStandardLineEdit->text(); updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension, count, "create_astromcats_phot_para.sh"); if (cdw->ui->APIWCSCheckBox->isChecked()) { updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension, count, "create_scampcats.sh"); updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension+" photom", count, "create_scamp.sh"); } updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension, count, "create_stdphotom_prepare_para.sh"); updateCommandList(commandList, taskBasename, science, main+" "+science+" "+standard+" "+extension, count, "create_abs_photo_info.sh"); commandList.append("UPDATESOLUTIONS::"+main+"/"+standard); // must trigger cdw->updateAPIsolutions() } */ } commandList.append("UPDATESTATUS::"+taskBasename); return commandList; } void MainWindow::on_yieldToolButton_clicked() { // There is only sth to abort if the start button is disabled if (!ui->startPushButton->isEnabled()) { controller->userYield = true; emit messageAvailable("Yield request received ...", "stop"); message(ui->plainTextEdit, "Will stop after current task has finished, please wait ...", "stop"); mainGUIWorker->yield = true; if (!ui->startPushButton->isEnabled()) { ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); } } } void MainWindow::on_stopToolButton_clicked() { // There is only sth to abort if the start button is disabled if (!ui->startPushButton->isEnabled()) { controller->userStop = true; emit messageAvailable("Stop request received, finishing current calculations ...", "stop"); message(ui->plainTextEdit, "Stopping current task, please wait ...", "stop"); // Make sure we are not entering next task in the queue mainGUIWorker->yield = true; QTest::qWait(50); // Pause thread mainGUIWorker->pause(); if (controller->currentData != nullptr && controller->taskBasename != "HDUreformat") { // reformatting falls through because of userAbort flag controller->currentData->setSuccess(false); } mainGUIWorker->resume(); if (controller->taskBasename == "Astromphotom") { emit messageAvailable("Sending Scamp a kill signal ...", "stop"); controller->scampWorker->abort(); controller->workerThread->quit(); controller->workerThread->wait(); emit messageAvailable("Successfully detached from Scamp", "stop"); } if (controller->taskBasename == "Coaddition") { controller->successProcessing = false; // Must set to false first, to make sure that any subsequent coadd commands exit immediately emit messageAvailable("Sending Swarp a kill signal ...", "stop"); if (controller->currentSwarpProcess != "swarpPreparation") { if (controller->swarpWorker) controller->swarpWorker->abort(); if (controller->workerThreadPrepare) controller->workerThreadPrepare->quit(); if (controller->workerThreadPrepare) controller->workerThreadPrepare->wait(); controller->successProcessing = false; emit messageAvailable("Successfully detached from Swarp", "stop"); } else if (controller->currentSwarpProcess != "swarpCoaddition") { if (controller->swarpWorker) controller->swarpWorker->abort(); if (controller->workerThreadCoadd) controller->workerThreadCoadd->quit(); if (controller->workerThreadCoadd) controller->workerThreadCoadd->wait(); controller->successProcessing = false; emit messageAvailable("Successfully detached from Swarp", "stop"); } else { for (int i=0; iswarpWorkers.length(); ++i) { emit controller->swarpWorkers[i]->finishedResampling(controller->swarpWorkers[i]->threadID); if (controller->swarpWorkers[i]) controller->swarpWorkers[i]->abort(); if (controller->workerThreads[i]) controller->workerThreads[i]->quit(); if (controller->workerThreads[i]) controller->workerThreads[i]->wait(); emit messageAvailable("Successfully detached from Swarp", "stop"); } } } workerThread->quit(); workerThread->wait(); if (controller->taskBasename == "Processbias" || controller->taskBasename == "Processdark" || controller->taskBasename == "Processflatoff" || controller->taskBasename == "Processflat" || controller->taskBasename == "Binnedpreview" || controller->taskBasename == "Globalweight" || controller->taskBasename == "Individualweight" || controller->taskBasename == "Createsourcecat" || controller->taskBasename == "Astromphotom" || controller->taskBasename == "Coaddition") { emit messageAvailable("Hard abort: " + controller->taskBasename, "stop"); emit messageAvailable("Manual clean-up is not required, simply re-run the task for a clean state.", "note"); } else { emit messageAvailable("
*****************************************************************", "stop"); emit messageAvailable("Hard abort: " + controller->taskBasename, "stop"); emit messageAvailable("Files in " + controller->currentDirName + " likely need manual clean-up.", "stop"); emit messageAvailable("*****************************************************************", "stop"); } if (!ui->startPushButton->isEnabled()) { ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); } } } void MainWindow::on_actionKill_triggered() { // There is only sth to abort if the start button is disabled if (!ui->startPushButton->isEnabled()) { controller->userKill = true; emit messageAvailable("Abort request received ...", "stop"); message(ui->plainTextEdit, "Kill signal sent, please wait ...", "stop"); if (controller->taskBasename == "Astromphotom") { emit messageAvailable("Sending Scamp a kill signal ...", "stop"); controller->scampWorker->abort(); controller->workerThread->quit(); controller->workerThread->wait(); emit messageAvailable("Successfully detached from Scamp", "stop"); } if (controller->taskBasename == "Coaddition") { emit messageAvailable("Sending Swarp a kill signal ...", "stop"); controller->swarpWorker->abort(); controller->workerThread->quit(); controller->workerThread->wait(); emit messageAvailable("Successfully detached from Swarp", "stop"); } workerThread->terminate(); workerThread->wait(); message(ui->plainTextEdit, "Aborted.", "stop"); if (!ui->startPushButton->isEnabled()) { ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); } if (controller->taskBasename == "Processbias" || controller->taskBasename == "Processdark" || controller->taskBasename == "Processflatoff" || controller->taskBasename == "Processflat" || controller->taskBasename == "Binnedpreview" || controller->taskBasename == "Globalweight" || controller->taskBasename == "Individualweight" || controller->taskBasename == "Createsourcecat" || controller->taskBasename == "Astromphotom" || controller->taskBasename == "Coaddition") { emit messageAvailable("Task killed: " + controller->taskBasename, "warning"); emit messageAvailable("Manual clean-up is not required, simply re-run the task for a clean state.", "note"); } emit messageAvailable("Task killed: " + controller->taskBasename, "stop"); emit messageAvailable("
*****************************************************************", "stop"); emit messageAvailable("Files in " + controller->currentDirName + " need manual clean-up.", "stop"); emit messageAvailable("Data model in RAM in undefined state, recommend THELI restart.", "stop"); emit messageAvailable("*****************************************************************", "stop"); } } void MainWindow::startPushButton_clicked_dummy(QString string) { on_startPushButton_clicked(); } // This top level function has two modes: a "simulator" mode, executed when task checkboxes are checked or // unchecked, or data dirs edited successfully. It goes through all the tests and prints notifications in plainTextEdit, // but it does not execute anything. Only when the actual start button is clicked, the function goes through with the execution // but does not print any uncritical information anymore void MainWindow::on_startPushButton_clicked() { if (!doingInitialLaunch) { controller->progress = 0.; } QSettings settings("THELI", "PREFERENCES"); processSkyImages = settings.value("prefProcessSkyCheckBox",false).toBool(); // Do not do anything while tasks are running already if (!ui->startPushButton->isEnabled()) return; // Do not simulate during startup (excessive (?) parseing of the directory tree) // if (doingInitialLaunch || readingSettings) return; // The current execution mode QString mode = OSPBC_determineExecutionMode(sender()); // Reset error message box flags resetProcessingErrorFlags(); // Check whether the directory tree is consistent if (mode != "simulate") { if (!OSPBC_multipleDirConsistencyCheck()) return; } // Check if all data Dirs are valid. If there is a single one that isn't, abort! // Exception: mode = ResolveTargetSidereal does not require any data directories if (! areAllPathsValid() && (mode != "ResolveTargetSidereal") && !doingInitialLaunch) { message(ui->plainTextEdit, "STOP: Nonexistent entries were found in the data directory tree. " "They must be fixed or removed."); ui->processingTabWidget->setCurrentIndex(0); return; } // Save the setup in case the GUI crashes writeGUISettings(); // The following list contains all script commands that would be executed totalCommandList.clear(); bool stop = false; QString taskBasename; // Process commands from other buttons than the "start" button if (mode == "GetCatalogFromWEB" || mode == "GetCatalogFromIMAGE" || mode == "ResolveTargetSidereal" || mode == "RestoreHeader") { taskBasename = mode; if (!OSPBC_addCommandBlock(taskBasename, mode, stop)) return; // updates totalCommandList } else { // process commands from the start button (must loop over task checkboxes) for (auto &it : status.listCheckBox) { // Include only tasks visible on the currently visible stacked widget page // if (it->isChecked() && isTaskCurrentlyVisible(it)) { if (it->isChecked()) { taskBasename = it->objectName().remove("apply").remove("CheckBox"); if (!OSPBC_addCommandBlock(taskBasename, mode, stop)) return; // updates totalCommandList } } } totalCommandList.append("END::"+taskBasename); // If we are not in simulator mode then do the real thing if (mode != "simulate") { bool anythingChecked = false; for (auto &it : status.listCheckBox) { if (it->isChecked()) { anythingChecked = true; } } // Leave if no normal task is checked (apart from special buttons) if (mode != "GetCatalogFromWEB" && mode != "GetCatalogFromIMAGE" && mode != "ResolveTargetSidereal" && mode != "RestoreHeader" && !anythingChecked) { return; } // Reset the controller's processing status controller->successProcessing = true; controller->userYield = false; controller->userStop = false; controller->userKill = false; controller->abortProcess = false; controller->swapWarningShown = false; ui->startPushButton->setText("Running ..."); ui->startPushButton->setDisabled(true); for (auto &it : status.listDataDirs) { it->setDisabled(true); } cdw->ui->confStackedWidget->setDisabled(true); emit runningStatusChanged(true); toggleButtonsWhileRunning(); workerThread = new QThread(); mainGUIWorker = new MainGUIWorker(controller, totalCommandList); //workerInit = true; //workerThreadInit = true; mainGUIWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, mainGUIWorker, &MainGUIWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(mainGUIWorker, &MainGUIWorker::finished, this, &MainWindow::taskFinished); connect(mainGUIWorker, &MainGUIWorker::updateStatus, &status, &Status::updateStatusReceived); connect(mainGUIWorker, &MainGUIWorker::messageAvailable, this, &MainWindow::displayMessage); connect(mainGUIWorker, &MainGUIWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(mainGUIWorker, &MainGUIWorker::finished, mainGUIWorker, &QObject::deleteLater, Qt::DirectConnection); // if an error is encountered during scanning, we must end the worker thread workerThread->start(); // show the process monitor, for normal processing tasks, only if (taskBasename != "ResolveTargetSidereal") { if (switchProcessMonitorPreference) monitor->raise(); ui->processProgressBar->setValue(0); } // Speed up the CPU and RAM timers cpuTimer->setInterval(500); ramTimer->setInterval(500); driveTimer->setInterval(500); } else { bool anythingChecked = false; int numTasksChecked = 0; for (auto &it : status.listCheckBox) { if (it->isChecked()) { ++numTasksChecked; anythingChecked = true; } } if (!anythingChecked) { message(ui->plainTextEdit, "Currently no activated tasks.", "info"); } else { if (! stop) { if (totalCommandList.length() == 1) message(ui->plainTextEdit, "Nothing to be done. Selected tasks already executed.", "info"); else { if (numTasksChecked == 1) message(ui->plainTextEdit, QString::number(numTasksChecked) + " task activated. Ready !", "info"); else message(ui->plainTextEdit, QString::number(numTasksChecked) + " tasks activated. Ready !", "info"); } } } } } void MainWindow::displayMessage(QString messagestring, QString type) { message(ui->plainTextEdit, messagestring, type); } bool MainWindow::OSPBC_addCommandBlock(const QString taskBasename, const QString mode, bool &stop) { QStringList commandblock; // call the function by its string representation (needs a const char *) bool test = QMetaObject::invokeMethod(this, ("task"+taskBasename).toStdString().c_str(), Qt::DirectConnection, Q_RETURN_ARG(QStringList, commandblock), Q_ARG(bool &, stop), Q_ARG(const QString, mode)); if (!test) { qDebug() << __func__ << "Could not evaluate QMetaObject."; return false; } // Check if the task identified a condition (which it will print to ui->plainTextEdit) // that should prevent execution (e.g. insufficient number of exposures, etc). if (stop && mode != "simulate") { return false; } // If an inconsistency in the data tree was detected. // Instead of checking and reporting this in handleDataDirs(), we just do it once to avoid multiple instances of the readme window shown if (commandblock.isEmpty() && mode != "simulate") { QMessageBox::critical(this, tr("THELI: Invalid data dir configuration"), tr("An incompatible number of directories was detected in the data tree.\n" "Allowed setups will be displayed next."), QMessageBox::Ok); on_setupReadmePushButton_clicked(); return false; } // Add the actual processing commands (script calls) to a string list totalCommandList.append(commandblock); return true; } // UNUSED // Check if a task is on the currently displayed stack widget page bool MainWindow::OSPBC_isTaskCurrentlyVisible(QCheckBox *cb) { if (ui->processingTabWidget->currentIndex() == 0) return false; else if (ui->processingTabWidget->currentIndex() == 1) { if (cb == ui->applyHDUreformatCheckBox || cb == ui->applyProcessbiasCheckBox || cb == ui->applyProcessdarkCheckBox || cb == ui->applyProcessflatoffCheckBox || cb == ui->applyProcessflatCheckBox || cb == ui->applyProcessscienceCheckBox || cb == ui->applyChopnodCheckBox || cb == ui->applyBackgroundCheckBox || cb == ui->applyCollapseCheckBox || cb == ui->applyBinnedpreviewCheckBox) return true; else return false; } else if (ui->processingTabWidget->currentIndex() == 2) { if (cb == ui->applyGlobalweightCheckBox || cb == ui->applyIndividualweightCheckBox || cb == ui->applySeparateCheckBox || cb == ui->applyAbsphotindirectCheckBox || cb == ui->applyCreatesourcecatCheckBox || cb == ui->applyAstromphotomCheckBox || cb == ui->applyStarflatCheckBox || cb == ui->applySkysubCheckBox || cb == ui->applyCoadditionCheckBox) return true; else return false; } else { // never evaluated return false; } } // Which mode are we in QString MainWindow::OSPBC_determineExecutionMode(QObject *sender) { QString mode; if (sender == ui->startPushButton) mode = "execute"; else if (sender == cdw->ui->ARCgetcatalogPushButton) { if (cdw->ui->ARCwebRadioButton->isChecked()) mode = "GetCatalogFromWEB"; if (cdw->ui->ARCimageRadioButton->isChecked()) mode = "GetCatalogFromIMAGE"; } else if (sender == cdw->ui->restoreHeaderPushButton) mode = "RestoreHeader"; else if (sender == cdw->ui->ARCtargetresolverToolButton) mode = "ResolveTargetSidereal"; else { mode = "simulate"; ui->plainTextEdit->clear(); } return mode; } bool MainWindow::OSPBC_multipleDirConsistencyCheck() { // CONSISTENCY CHECK concerning multiple directories // Loop over initial checkboxes (0-8, 6&7 don't matter) // Hardcoded, needs to be adjusted when more tasks are introduced before applyBackgroundCheckBox int i = 0; bool test = true; for (auto &it : status.listCheckBox) { if (it->isChecked()) { QString taskBasename = it->objectName().remove("apply").remove("CheckBox"); test = test && checkMultipledirConsistency(taskBasename); } ++i; // Don't have to evaluate more checkboxes. if (i >= 9) break; } // If this evaluates to false, then at least one part of the data directory tree is inconsistent. // In this case warning messages will have been printed to plainTextEdit already by // checkMultipledirConsistency() // We just need to show the dialog with the explanation. if (!test) { on_setupReadmePushButton_clicked(); return false; } else return true; } //UNUSED void MainWindow::appendOK() { ui->plainTextEdit->moveCursor (QTextCursor::End); ui->plainTextEdit->insertPlainText("OK"); ui->plainTextEdit->moveCursor (QTextCursor::End); } void MainWindow::taskFinished() { cdw->ui->confStackedWidget->setEnabled(true); if (controller->userYield) { emit messageAvailable("Task '"+controller->taskBasename + "' finished.\nSoft abort. ", "stop"); emit messageAvailable(controller->currentDirName + " in clean state, no manual clean-up required.", "note"); } ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); for (auto &it : status.listDataDirs) { it->setEnabled(true); } monitor->displayMessage("
*** DONE ***", "note"); emit runningStatusChanged(false); // enable various buttons again toggleButtonsWhileRunning(); // Reset all abort flags to false in the current Data class if the task was aborted. // Not when we still do splitting, because Data classes have not been instantiated if (controller->currentData == nullptr) return; if (controller->userYield || controller->userStop || controller->userKill) { controller->currentData->resetUserAbort(); } // Allow reprocessing after hard aborts if (controller->userStop || controller->userKill) { controller->currentData->resetSuccessProcessing(); } // slow down CPU and RAM timers cpuTimer->setInterval(2000); ramTimer->setInterval(2000); driveTimer->setInterval(2000); // not needed, handled by 'deleteLater' // delete workerThread; } bool MainWindow::isRefcatRecent(QString dirname) { QFile file(dirname+"/cat/refcat/.refcatID"); QFile catalog(dirname+"/cat/refcat/theli_mystd.scamp"); if (!file.exists()) return false; if (!catalog.exists()) return false; QString id; QString currentId; if ( !file.open(QIODevice::ReadOnly)) { // qDebug() << "QDEBUG: isRefcatRecent(): "+dirname+".refcatID could not be opened."; return false; } else { // extract the ID string QTextStream stream( &file ); id = stream.readLine(); id = id.simplified(); file.close(); if (cdw->ui->ARCwebRadioButton->isChecked()) { QString catalog = cdw->ui->ARCcatalogComboBox->currentText(); QString ra = cdw->ui->ARCraLineEdit->text(); QString dec = cdw->ui->ARCdecLineEdit->text(); if (ra.contains(":")) ra = hmsToDecimal(ra); if (dec.contains(":")) dec = dmsToDecimal(dec); QString minmag = cdw->ui->ARCminmagLineEdit->text(); if (minmag.isEmpty()) minmag = cdw->defaultMap["ARCminmagLineEdit"]; QString radius = cdw->ui->ARCradiusLineEdit->text(); currentId = catalog+"_"+ra+"_"+dec+"_"+minmag+"_"+radius; if (catalog.contains("GAIA")) currentId.append("_"+cdw->ui->ARCmaxpmLineEdit->text()); } else { QString image = cdw->ui->ARCselectimageLineEdit->text(); QString dt = cdw->ui->ARCDTLineEdit->text(); QString dmin = cdw->ui->ARCDMINLineEdit->text(); // QString deblend = cdw->ui->ARCmincontLineEdit->text(); currentId = image+"_"+dt+"_"+dmin; } // Uncomment this to understand why refcat is downloaded twice // qDebug() << id << currentId; if (id != currentId) return false; else return true; } } void MainWindow::processMessage(QString text, QString type) { message(ui->plainTextEdit, text, type); } QString MainWindow::manualCoordsUpdate(QString science, QString mode) { if (mode != "execute") return "empty"; if (cdw->ui->ARCraLineEdit->text() != "" && cdw->ui->ARCdecLineEdit->text() != "") { QMessageBox msgBox; msgBox.setText(science+": Overwrite CRVAL1/2 and CDi_j keywords?"); msgBox.setInformativeText("Manual coordinates were provided. " "Do you want to overwrite the CRVAL1/2 " "keywords with the values for RA and DEC entered above?\n" "Optionally, you can also force the CD matrix to have North up and East left.\n\n"); QAbstractButton *pButtonCrval = msgBox.addButton(tr("Update Ra/DEC"), QMessageBox::YesRole); QAbstractButton *pButtonCrvalCD = msgBox.addButton(tr("Update RA/DEC, reset CD matrix"), QMessageBox::YesRole); QAbstractButton *pButtonUnchanged = msgBox.addButton(tr("Leave header unchanged"), QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton() == pButtonCrval) return "crval"; else if (msgBox.clickedButton() == pButtonCrvalCD) return "crval+cd"; else if (msgBox.clickedButton() == pButtonUnchanged) return "empty"; else if (msgBox.clickedButton() == pButtonCancel) return "Cancel"; } else return "empty"; return "empty"; } bool MainWindow::checkCatalogUsability(QString mode) { // Confirm the catalog choice if possible not very useful if (cdw->ui->ARCwebRadioButton->isChecked()) { if (instData.pixscale > 2.0 && instData.pixscale < 10.0 && mode != "simulate") { QString refcatName = cdw->ui->ARCcatalogComboBox->currentText(); if (refcatName.contains("GAIA") || refcatName.contains("PANSTARRS") || refcatName.contains("SKYMAPPER") || refcatName.contains("VHS") || refcatName.contains("SDSS") || refcatName.contains("2MASS")) { QMessageBox msgBox; msgBox.setModal(true); msgBox.setInformativeText(tr("Very large online query detected.\n\n") + tr("Downloading data from ") + refcatName + tr(" for your data could take very long. ") + tr("Since your field of view is large and the resolution less than 2 arcsec / pixel, UCAC5 is a better alternative.\n")); QAbstractButton *pButtonUCAC = msgBox.addButton(tr("Use UCAC5"), QMessageBox::YesRole); QAbstractButton *pButtonOrig = msgBox.addButton(tr("Use ")+refcatName, QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton() == pButtonUCAC) cdw->ui->ARCcatalogComboBox->setCurrentText("UCAC5"); else if (msgBox.clickedButton() == pButtonCancel) return false; else if (msgBox.clickedButton() == pButtonOrig) return true; } } else if (instData.pixscale > 10.0 && mode != "simulate") { QString refcatName = cdw->ui->ARCcatalogComboBox->currentText(); if (!refcatName.contains("ASCC") && !refcatName.contains("TYC")) { QMessageBox msgBox; msgBox.setModal(true); msgBox.setInformativeText(tr("Very large online query detected.\n\n") + tr("Downloading data from ") + refcatName + tr(" for your data will take very long. ") + tr("Since your field of view is large and the resolution less than 2\" / pixel, ASCC is a better alternative.\n")); QAbstractButton *pButtonUCAC = msgBox.addButton(tr("Use ASCC"), QMessageBox::YesRole); QAbstractButton *pButtonOrig = msgBox.addButton(tr("Use ")+refcatName, QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton() == pButtonUCAC) cdw->ui->ARCcatalogComboBox->setCurrentText("ASCC"); else if (msgBox.clickedButton() == pButtonCancel) return false; else if (msgBox.clickedButton() == pButtonOrig) return true; } } } return true; } QString MainWindow::sameRefCoords(QString coordsMode) { if (coordsMode != "execute") return ""; if (cdw->ui->COAraLineEdit->text() == "" || cdw->ui->COAdecLineEdit->text() == "") { QMessageBox msgBox; msgBox.setText("No reference coordinates provided for multi-color data set"); msgBox.setInformativeText("Several coadditions will be performed for a multi-color data set. " "It is highly recommended that you use identical RA/DEC reference coordinates for the " "projection of each coaddition. Images can then be automatically cropped such that " "the same object appears on the same pixel in all coadded images.\n\n"); QAbstractButton* pButtonAuto = msgBox.addButton(tr("Use field centroid"), QMessageBox::YesRole); QAbstractButton* pButtonContinue = msgBox.addButton(tr("Continue as is"), QMessageBox::YesRole); QAbstractButton* pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton() == pButtonAuto) { QString alphaCenter = ""; QString deltaCenter = ""; if (controller->DT_SCIENCE.length() == 1) { controller->getFieldCenter(controller->DT_SCIENCE[0], alphaCenter, deltaCenter); cdw->ui->COAraLineEdit->setText(alphaCenter); cdw->ui->COAdecLineEdit->setText(deltaCenter); return "Continue"; } else { QMessageBox::warning(this, "THELI", "Multiple science directories. You must specifyy the field centers manually.", QMessageBox::Ok); return "Cancel"; } } else if (msgBox.clickedButton() == pButtonContinue) return "Continue"; else if (msgBox.clickedButton() == pButtonCancel) return "Cancel"; else return "Cancel"; } else return ""; } QStringList MainWindow::displayCoaddFilterChoice(QString dirname, QString &filterChoice, QString mode) { // QStringList filterList = controller->getFilterList(dirname); // We look in normal images, then in skysub images for filter string QDir dir(dirname); // Figure out a chip that must be present (not excluded by the user int testChip = -1; for (int chip=0; chip 1 QMessageBox msgBox; msgBox.setText("Different filters are available for coaddition in\n "+dirname); msgBox.setInformativeText("Choose a method below to coadd these filters :\n"); QAbstractButton *pAllSeparately = msgBox.addButton(tr("Separately"), QMessageBox::YesRole); pAllSeparately->setToolTip("Create separate coadded images for each filter"); QAbstractButton *pAllTogether = msgBox.addButton(tr("Together"), QMessageBox::YesRole); pAllTogether->setToolTip("Combine images from all filters into a single coadded image"); for (auto &it : filterList) { QAbstractButton *button = msgBox.addButton(it, QMessageBox::YesRole); button->setToolTip("Coadd this filter, only"); } msgBox.addButton(tr("Abort"), QMessageBox::NoRole); msgBox.exec(); // WARNING! Some KDE versions / settings make KDE inserts the & char for the shortcut into // the string returned by text(). HUGE screwup. KDE should never mess with GUI at this level filterChoice = msgBox.clickedButton()->text().remove('&'); if (filterChoice == "Together") filterChoice = "all"; } } return filterList; } void MainWindow::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable(funcName+":
" + errorCodes->errorKeyMap.value(status), "error"); } } void MainWindow::refreshMemoryViewerReceiver() { monitor->raise(); memoryViewer->raise(); } THELI-3.1.3/src/tasks.cc000066400000000000000000000355471417631501300146250ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "ui_confdockwidget.h" #include "functions.h" #include "status.h" #include "processingExternal/errordialog.h" #include "datadir.h" #include #include #include #include #include QStringList MainWindow::taskHDUreformat(bool &stop, const QString mode) { QString taskBasename = "HDUreformat"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupBiasLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupDarkLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupFlatoffLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupFlatLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskProcessbias(bool &stop, const QString mode) { QString taskBasename = "Processbias"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupBiasLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskProcessdark(bool &stop, const QString mode) { QString taskBasename = "Processdark"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupDarkLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskProcessflatoff(bool &stop, const QString mode) { QString taskBasename = "Processflatoff"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupFlatoffLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskProcessflat(bool &stop, const QString mode) { QString taskBasename = "Processflat"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; // Do we use the FLAT OFF/DARK or BIAS (in case one or more are defined); // FLAT OFF preferred over BIAS QString bias = ui->setupBiasLineEdit->text(); QString flatoff = ui->setupFlatoffLineEdit->text(); if (!flatoff.isEmpty()) le1 = ui->setupFlatoffLineEdit; else if (!bias.isEmpty()) le1 = ui->setupBiasLineEdit; else le1->setText("theli_nobias"); handleDataDirs(goodDirList, ui->setupFlatLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskProcessscience(bool &stop, const QString mode) { QString taskBasename = "Processscience"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; // Do we use the FLAT and / or BIAS (in case one or more are defined); QString bias = ui->setupBiasLineEdit->text(); QString dark = ui->setupDarkLineEdit->text(); QString flat = ui->setupFlatLineEdit->text(); if (!dark.isEmpty()) le1 = ui->setupDarkLineEdit; else if (!bias.isEmpty()) le1 = ui->setupBiasLineEdit; else le1->setText("theli_nobias"); if (!flat.isEmpty()) le2 = ui->setupFlatLineEdit; else le2->setText("theli_noflat"); // append DT_x to tell the internal processor which Data structure we have to work on // For FLAT and FLAT_OFF we have separate taskBasenames, for SCIENCE we don't. // I should revisit this and make it more consistent handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "theli_DT_SCIENCE", success); handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "theli_DT_SKY", success); handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "theli_DT_STANDARD", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskChopnod(bool &stop, const QString mode) { QString taskBasename = "Chopnod"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskBackground(bool &stop, const QString mode) { QString taskBasename = "Background"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; // The first argument gets replaced by the sky dir (if any) QString sky = ui->setupSkyLineEdit->text(); if (!sky.isEmpty()) le1 = ui->setupSkyLineEdit; else le1->setText("noskydir"); // Standard stars don't have separate sky entries (at least we don't support it) auto *nosky = new QLineEdit(controller); nosky->setText("noskydir"); handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupStandardLineEdit, nosky, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskCollapse(bool &stop, const QString mode) { QString taskBasename = "Collapse"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskBinnedpreview(bool &stop, const QString mode) { QString taskBasename = "Binnedpreview"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskGlobalweight(bool &stop, const QString mode) { QString taskBasename = "Globalweight"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; // Do we use the FLAT and / or BIAS (in case one or more are defined); QString bias = ui->setupBiasLineEdit->text(); QString dark = ui->setupDarkLineEdit->text(); QString flat = ui->setupFlatLineEdit->text(); if (!flat.isEmpty()) le1 = ui->setupFlatLineEdit; else le1->setText("theli_noflat"); if (!dark.isEmpty()) le2 = ui->setupDarkLineEdit; else if (!bias.isEmpty()) le2 = ui->setupBiasLineEdit; else le2->setText("theli_nobias"); handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskIndividualweight(bool &stop, const QString mode) { QString taskBasename = "Individualweight"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskSeparate(bool &stop, const QString mode) { QString taskBasename = "Separate"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskAbsphotindirect(bool &stop, const QString mode) { QString taskBasename = "Absphotindirect"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskCreatesourcecat(bool &stop, const QString mode) { QString taskBasename = "Createsourcecat"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskAstromphotom(bool &stop, const QString mode) { QString taskBasename = "Astromphotom"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskGetCatalogFromWEB(bool &stop, const QString mode) { QString taskBasename = "GetCatalogFromWEB"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskGetCatalogFromIMAGE(bool &stop, const QString mode) { QString taskBasename = "GetCatalogFromIMAGE"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskRestoreHeader(bool &stop, const QString mode) { QString taskBasename = "RestoreHeader"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskSkysub(bool &stop, const QString mode) { QString taskBasename = "Skysub"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } QStringList MainWindow::taskCoaddition(bool &stop, const QString mode) { QString taskBasename = "Coaddition"; QStringList goodDirList; auto *le1 = new QLineEdit(controller); auto *le2 = new QLineEdit(controller); bool success = true; handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success); if (!success) return QStringList(); return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } // TODO: go through these tasks and clean up those we don't need anymore, or info therein we don't need QStringList MainWindow::taskResolveTargetSidereal(bool &stop, const QString mode) { QString taskBasename = "ResolveTargetSidereal"; QStringList goodDirList; // Replace blanks by underscores, and push the target name onto 'gooddirlist', which carries no other information QString target = cdw->ui->ARCtargetresolverLineEdit->text(); target = target.replace(" ","_"); cdw->ui->ARCraLineEdit->clear(); cdw->ui->ARCdecLineEdit->clear(); goodDirList << target; return createCommandlistBlock(taskBasename, goodDirList, stop, mode); } THELI-3.1.3/src/threading/000077500000000000000000000000001417631501300151205ustar00rootroot00000000000000THELI-3.1.3/src/threading/abszpworker.cc000066400000000000000000000034221417631501300200010ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "abszpworker.h" #include "../abszp/abszeropoint.h" #include #include AbszpWorker::AbszpWorker(AbsZeroPoint *abszeropoint, QObject *parent) : Worker(parent) { // abszpCommand = command; // abszpDirName = dir; absZeroPoint = abszeropoint; } void AbszpWorker::runTask() { QTest::qWait(50); if (yield) { emit finished(); return; } absZeroPoint->taskInternalAbszeropoint(); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void AbszpWorker::processExternalStdout() { QProcess *process = qobject_cast(sender()); QString stdout(process->readAllStandardOutput()); // QString stdout(externalProcess->readLine()); stdout.remove(QRegExp("[^a-zA-Z.:-\\d\\s]")); emit messageAvailable(stdout.simplified(), "normal"); } void AbszpWorker::processExternalStderr() { QProcess *process = qobject_cast(sender()); QString stderr(process->readAllStandardError()); stderr.remove(QRegExp("[^a-zA-Z\\d\\s]")); emit messageAvailable(stderr.simplified(), "normal"); } THELI-3.1.3/src/threading/abszpworker.h000066400000000000000000000023131417631501300176410ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef ABSZPWORKER_H #define ABSZPWORKER_H #include "../abszp/abszeropoint.h" #include "worker.h" #include class AbsZeroPoint; class AbszpWorker : public Worker { Q_OBJECT public: explicit AbszpWorker(AbsZeroPoint *abszeropoint, QObject *parent = nullptr); QString abszpCommand; QString abszpDirName; AbsZeroPoint *absZeroPoint; bool yield = false; public slots: void runTask(); private slots: void processExternalStdout(); void processExternalStderr(); signals: }; #endif // ABSZPWORKER_H THELI-3.1.3/src/threading/anetworker.cc000066400000000000000000000066121417631501300176150ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "anetworker.h" #include "../functions.h" #include #include AnetWorker::AnetWorker(QString command, QString dir, QObject *parent) : Worker(parent) { anetCommand = command; anetDirName = dir; } void AnetWorker::runAnet() { extProcess = new QProcess(); connect(extProcess, &QProcess::readyReadStandardOutput, this, &AnetWorker::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &AnetWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(anetDirName); extProcess->start("/bin/sh -c \""+anetCommand+"\""); extProcess->waitForFinished(-1); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void AnetWorker::processExternalStdout() { QProcess *process = qobject_cast(sender()); QString stdout(process->readAllStandardOutput()); stdout.replace(" Field", "
Field"); stdout.replace("\nField", "
Field"); stdout.replace("Hit/miss: Hit/miss:", "
Hit/miss:"); QStringList errors; errors << "Did not solve (or no WCS file was written)." << "Error" << "ERROR"; // Highlight a successful solve // Sometimes neighboring lines are included in one push to stdout, and then they are colored green as well. // if (stdout.contains("solved with index theli_mystd.index")) { // emit messageAvailable(stdout.simplified(), "note"); // return; // } // And a field that did not solve for (auto &error : errors) { if (stdout.contains(error)) { emit errorFound(); emit messageAvailable(stdout.simplified(), "stop"); break; } } emit messageAvailable(stdout.simplified(), "image"); } void AnetWorker::processExternalStderr() { QProcess *process = qobject_cast(sender()); QString stderr(process->readAllStandardError()); stderr.replace("> *Error*:", "

> *Error*:"); stderr.replace("> *ERROR*:", "

> *ERROR*:"); QStringList errors; errors << "*Error*:" << "*ERROR*:"; for (auto &error : errors) { if (stderr.contains(error)) { emit errorFound(); emit messageAvailable("Astrometry.net: " + stderr.simplified(), "stop"); break; } } } void AnetWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // The kill the process that invokes the commandline task extProcess->kill(); emit finished(); } THELI-3.1.3/src/threading/anetworker.h000066400000000000000000000024211417631501300174510ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef ANETWORKER_H #define ANETWORKER_H #include "worker.h" #include #include class AnetWorker : public Worker { Q_OBJECT public: explicit AnetWorker(QString command, QString dir, QObject *parent = nullptr); QString anetCommand; QString anetDirName; QProcess *extProcess = nullptr; void abort(); // Currently not used anywhere public slots: void runAnet(); private slots: void processExternalStdout(); void processExternalStderr(); signals: void errorFound(); void messageAvailable(QString message, QString type); }; #endif // ANETWORKER_H THELI-3.1.3/src/threading/colorpictureworker.cc000066400000000000000000000030111417631501300213660ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpictureworker.h" #include "../colorpicture/colorpicture.h" #include ColorPictureWorker::ColorPictureWorker(ColorPicture *colorpicture, QString workmode, QObject *parent) : Worker(parent) { colorPicture = colorpicture; workMode = workmode; } void ColorPictureWorker::runTask() { QTest::qWait(50); if (yield) { emit finished(); return; } if (workMode == "CropCoadds") colorPicture->taskInternalCropCoadds(); else if (workMode == "ColorCalib") colorPicture->taskInternalColorCalib(); else if (workMode == "Fits2Tiff") colorPicture->taskInternalFits2Tiff(); else if (workMode == "BBNBratio") colorPicture->taskInternalBBNBratio(); else if (workMode == "BBNBcombine") colorPicture->taskInternalBBNBcombine(); else { // nothing yet } emit tasknameReturned(workMode); } THELI-3.1.3/src/threading/colorpictureworker.h000066400000000000000000000024171417631501300212410ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef COLORPICTUREWORKER_H #define COLORPICTUREWORKER_H #include "../colorpicture/colorpicture.h" #include "worker.h" #include // Forward declaration, because 'include colorpciture.h' includes this worker class ColorPicture; class ColorPictureWorker : public Worker { Q_OBJECT public: explicit ColorPictureWorker(ColorPicture *colorpicture, QString workmode, QObject *parent = nullptr); ColorPicture *colorPicture; QString workMode; bool yield = false; public slots: void runTask(); signals: void tasknameReturned(QString workmode); }; #endif // COLORPICTUREWORKER_H THELI-3.1.3/src/threading/mainguiworker.cc000066400000000000000000000060001417631501300203060ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainguiworker.h" #include "../processingInternal/controller.h" #include #include #include #include MainGUIWorker::MainGUIWorker(Controller *mycontroller, QStringList mycommands, QObject *parent) : Worker(parent) { commands = mycommands; controller = mycontroller; } void MainGUIWorker::runTask() { // isWorkerRunning = true; // Grab the command list, read the keywords, and process it accordingly QString key; QString instructions; QStringList list; // The following loop handles 4 different types of 'key events' // yield can be triggered from outside for (auto &it : commands) { // We need a little wait here (50msec) to allow for the parent process to update "abort" // in case the process is aborted by the user. QTest::qWait(50); if (yield || !controller->successProcessing) { emit messageAvailable("Aborted.\n", "stop"); emit finished(); break; } list = it.split("::"); key = list.at(0); // EVENT 1: Used to show which task is currently executed if (key == "MESSAGE") { int length = list.length(); // Only emit non-empty messages if (length > 1) { instructions = list.at(1).simplified(); emit messageAvailable(instructions+" ... ", "output"); } } // EVENT 2: execute the task else if (key == "RUN") { QString taskBasename = list.at(1); instructions = list.at(2).simplified(); // Set up the controller with the taskname, the arguments, and the parallelization, then run the task controller->taskBasename = taskBasename; controller->instructions = instructions; controller->loadPreferences(); // update the data tree here? controller->runTask(); } // EVENT 3: show in the GUI which task has just successfully finished else if (key == "UPDATESTATUS") { QString taskBasename = list.at(1); emit updateStatus(taskBasename, true); } // EVENT 4: show that everything is done. else if (key == "END") { emit messageAvailable("All tasks finished.\n", "info"); emit finished(); } } } THELI-3.1.3/src/threading/mainguiworker.h000066400000000000000000000022711417631501300201560ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MAINGUIWORKER_H #define MAINGUIWORKER_H #include "worker.h" #include "../processingInternal/controller.h" #include class MainGUIWorker : public Worker { Q_OBJECT public: explicit MainGUIWorker(Controller *mycontroller, QStringList mycommands, QObject *parent = nullptr); QStringList commands; Controller *controller; bool yield = false; public slots: void runTask(); private slots: signals: void updateStatus(QString taskBasename, bool success); }; #endif // MAINGUIWORKER_H THELI-3.1.3/src/threading/memoryworker.cc000066400000000000000000000113141417631501300201710ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "memoryworker.h" #include "functions.h" #include "../dockwidgets/memoryviewer.h" #include "../processingInternal/data.h" #include "ui_memoryviewer.h" #include "../myimage/myimage.h" #include #include #include MemoryWorker::MemoryWorker(MemoryViewer *memViewer, QObject *parent) : Worker(parent) { memoryViewer = memViewer; } MemoryWorker::MemoryWorker(Data *datadir, QObject *parent) : Worker(parent) { data = datadir; } /* * Done internally to MyImage by calling setActiveStatus() void MemoryWorker::processActiveStatusChanged() { if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); // Previously active image is now inactive if (myImage->oldState == MyImage::ACTIVE && myImage->activeState == MyImage::INACTIVE) { moveFile(myImage->baseName+".fits", path, path+"/inactive/"); } // Restore inactive images QString inactivePath = path+"/inactive/"; if (myImage->activeState == MyImage::BADSTATS) inactivePath.append("/badStatistics/"); if (myImage->activeState == MyImage::BADBACK) inactivePath.append("/badBackground/"); if (myImage->activeState != MyImage::ACTIVE && myImage->activeState != MyImage::DELETED) { moveFile(myImage->baseName+".fits", inactivePath, path); } emit finished(); } */ void MemoryWorker::MemoryViewerDumpImagesToDrive() { emit resetProgressBar(); if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); memoryViewer->ui->downloadToolButton->setText("Wait "); memoryViewer->ui->downloadToolButton->setDisabled(true); QTest::qWait(50); int index = memoryViewer->ui->datadirComboBox->currentIndex(); if (index == -1) return; int numImages = memoryViewer->dataModelList[index]->imageList.length(); progressStepSize = 1./float(numImages); #pragma omp parallel for num_threads(memoryViewer->controller->maxExternalThreads) for (int i=0; idataModelList[index]->imageList[i]; if (!it->imageOnDrive) { it->writeImage(); it->imageOnDrive = true; it->emitModelUpdateNeeded(); incrementProgress(); emit progressUpdate(progress); } } memoryViewer->ui->downloadToolButton->setText("Write"); memoryViewer->ui->downloadToolButton->setEnabled(true); emit progressUpdate(100.); emit finished(); } void MemoryWorker::DataDumpImagesToDrive() { emit resetProgressBar(); if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); // memoryViewer->ui->downloadToolButton->setText("Wait "); // memoryViewer->ui->downloadToolButton->setDisabled(true); QTest::qWait(50); progressStepSize = 1. / float(data->numImages); emit progressUpdate(0.); data->populateExposureList(); #pragma omp parallel for num_threads(data->maxExternalThreads) for (long i=0; iexposureList.length(); ++i) { for (auto &it : data->exposureList[i]) { if (!it->imageOnDrive) { it->writeImage(); it->imageOnDrive = true; it->emitModelUpdateNeeded(); incrementProgress(); emit progressUpdate(progress); } } } // memoryViewer->ui->downloadToolButton->setText("Write"); // memoryViewer->ui->downloadToolButton->setEnabled(true); emit progressUpdate(100.); emit finished(); } void MemoryWorker::incrementProgress() { omp_set_lock(&progressLock); progress += progressStepSize; emit progressUpdate(progress); omp_unset_lock(&progressLock); } void MemoryWorker::dumpImageToDrive() { if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); myImage->writeImage(); myImage->imageOnDrive = true; emit finished(); } THELI-3.1.3/src/threading/memoryworker.h000066400000000000000000000030611417631501300200330ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MEMORYWORKER_H #define MEMORYWORKER_H #include "worker.h" #include "../processingInternal/data.h" #include "../dockwidgets/memoryviewer.h" class MemoryViewer; class MemoryWorker : public Worker { Q_OBJECT public: explicit MemoryWorker(MemoryViewer *memViewer, QObject *parent = 0); explicit MemoryWorker(Data *datadir, QObject *parent = 0); MyImage *myImage = nullptr; QString path = ""; Data *data = nullptr; public slots: void MemoryViewerDumpImagesToDrive(); void DataDumpImagesToDrive(); void dumpImageToDrive(); // void processActiveStatusChanged(); private: MemoryViewer *memoryViewer = nullptr; // Data *data; omp_lock_t progressLock; float progress = 0.; float progressStepSize = 0.; void incrementProgress(); signals: void progressUpdate(float progress); void resetProgressBar(); }; #endif // MEMORYWORKER_H THELI-3.1.3/src/threading/scampworker.cc000066400000000000000000000163601417631501300177720ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "scampworker.h" #include "../functions.h" #include #include ScampWorker::ScampWorker(QString command, QString dir, QString shortname, QObject *parent) : Worker(parent) { scampCommand = command; scampDirName = dir; shortname = shortname; } void ScampWorker::runScamp() { // If using QProcess instead of QProcess*, we get a "cannot create child in different thread" error extProcess = new QProcess(); // connect(&extProcess, &QProcess::readyReadStandardOutput, this, &ScampWorker::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &ScampWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(scampDirName); extProcess->start("/bin/sh -c \""+scampCommand+"\""); extProcess->waitForFinished(-1); emit finishedScamp(); emit finished(); delete extProcess; extProcess = nullptr; // stdout and stderr channels are slotted into the monitor's plainTextEdit } /* void ScampWorker::runScamp() { // If using QProcess instead of QProcess*, we get a "cannot create child in different thread" error QProcess extProcess1; // connect(&extProcess, &QProcess::readyReadStandardOutput, this, &ScampWorker::processExternalStdout); connect(&extProcess1, &QProcess::readyReadStandardError, this, &ScampWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess1.setWorkingDirectory(scampDirName); extProcess1.start("/bin/sh -c \""+scampCommand+"\""); extProcess1.waitForFinished(-1); emit finishedScamp(); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } */ void ScampWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // The kill the process that invokes the commandline task extProcess->kill(); emit finished(); } void ScampWorker::processExternalStderr() { QProcess *process = qobject_cast(sender()); // have to remove the '\x1B[1A' and '\x1B[1M' escape sequences. QString stderr(process->readAllStandardError()); stderr.remove(QRegExp("[^a-zA-Z\\d\\s\\.\\:\\-\\_/]")); stderr.remove("1A1M "); stderr.remove("1A "); stderr.remove("1M "); // stderr.remove(QRegExp("![^0131m]")); stderr.remove("0131m"); stderr.remove("WARNING: scamp.conf not found using internal defaults"); stderr = stderr.simplified(); stderr.replace(" WARNING: ", "
WARNING: "); stderr.replace(" Error: ", "
Error: "); stderr.replace("... Matching ", "...
Matching "); stderr.replace("detections ", "detections
"); stderr.replace("scamp Examining", "scamp
Examining"); stderr.replace(" ----- Astrometric stats internal :All detections", "
----- Astrometric stats internal: All detections"); stderr.replace(" ----- Astrometric stats external:All detections", "
----- Astrometric stats external: All detections"); stderr.replace(" ----- Photometric stats internal:All detections", "
----- Photometric stats internal: All detections"); stderr.replace(" ----- Photometric stats external:All detections", "
----- Photometric stats external: All detections"); stderr.replace(" Instrument", "
Instrument"); stderr.replace(" Grouping fields:", "
Grouping fields:"); stderr.replace(" Matching field", "
Matching field"); stderr.replace(" Grouping fields on the sky", "
Grouping fields on the sky"); stderr.replace(" Group ", "
Group "); stderr.replace(" Generating ", "
Generating "); // if (!stderr.contains("Matching field") && !stderr.contains("Examining Catalog")) { // stderr.replace(" "+shortName, "
"+shortName); // } stderr.replace(" Making mosaic adjustments","
Making mosaic adjustments"); stderr.replace("7m instruments pos.angle scale cont. shift cont.0m", "instruments pos.angle scale cont. shift cont."); stderr.replace(" Solving the global astrometry matrix", "
Solving the global astrometry matrix"); stderr.replace(" Solving the global photometry matrix", "
Solving the global photometry matrix"); stderr.replace(" Initializing the global astrometry matrix", "
Initializing the global astrometry matrix"); stderr.replace(" Initializing the global photometry matrix", "
Initializing the global photometry matrix"); stderr.replace("instruments epoch center coordinates radius scale","
instruments epoch center coordinates radius scale
"); stderr.replace(" instrument found for astrometry:", " instrument found for astrometry:
"); stderr.replace(" instrument found for photometry:", "
instrument found for photometry:
"); stderr.replace(" Filling the global astrometry matrix", "
Filling the global astrometry matrix"); stderr.replace(" Computing set shifts for field", "
Computing set shifts for field"); stderr.replace(" Initializing detection weight factors", "
Initializing detection weight factors"); stderr.remove(QRegExp("^1A")); stderr.remove(" 0m "); stderr.remove(" 7m "); if (stderr.contains(" deg ")) emit fieldMatched(); QStringList warnings; warnings << "WARNING: "; warnings << "Not enough matched detections"; warnings << "inaccuracies likely to occur"; QStringList errors; errors << "Error: "; errors << "fatal: division by zero attempted"; errors << "no match with reference catalog"; errors << "Not enough memory"; errors << "buffer overflow detected"; errors << "Could not allocate memory"; errors << "Invalid deprojected coordinates"; errors << "keyword out of range"; errors << "WARNING: Not a positive definite matrix in astrometry solver"; errors << "Segmentation fault"; QString type = "normal"; for (auto &warning : warnings) { if (stderr.contains(warning)) { type = "warning"; break; } } for (auto &error : errors) { if (stderr.contains(error)) { type = "error"; stderr.remove("Error: "); stderr.remove("WARNING: "); stderr.replace("Segmentation fault", "Scamp ended with a segmentation fault."); emit errorFound(); break; } } emit messageAvailable(stderr.simplified(), type); } THELI-3.1.3/src/threading/scampworker.h000066400000000000000000000025301417631501300176260ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef SCAMPWORKER_H #define SCAMPWORKER_H #include "worker.h" #include #include class ScampWorker : public Worker { Q_OBJECT public: explicit ScampWorker(QString command, QString dir, QString shortname, QObject *parent = nullptr); QString scampCommand; QString scampDirName; QString shortName; QProcess *extProcess = nullptr; void abort(); public slots: void runScamp(); private slots: // void processExternalStdout(); void processExternalStderr(); signals: void errorFound(); void fieldMatched(); void finishedScamp(); void messageAvailable(QString message, QString type); }; #endif // SCAMPWORKER_H THELI-3.1.3/src/threading/sourceextractorworker.cc000066400000000000000000000056151417631501300221240ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "sourceextractorworker.h" #include "../functions.h" #include #include SourceExtractorWorker::SourceExtractorWorker(QString command, QString dir, QObject *parent) : Worker(parent) { sourceExtractorCommand = command; sourceExtractorDirName = dir; } void SourceExtractorWorker::runSourceExtractor() { extProcess = new QProcess(); connect(extProcess, &QProcess::readyReadStandardOutput, this, &SourceExtractorWorker::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &SourceExtractorWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(sourceExtractorDirName); extProcess->start("/bin/sh -c \""+sourceExtractorCommand+"\""); extProcess->waitForFinished(-1); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void SourceExtractorWorker::processExternalStdout() { // Ignoring stdout /* QProcess *process = qobject_cast(sender()); QString stdout(process->readAllStandardOutput()); // QString stdout(externalProcess->readLine()); stdout.remove(QRegExp("[^a-zA-Z.:-\\d\\s]")); emit messageAvailable(stdout.simplified(), "normal"); */ } void SourceExtractorWorker::processExternalStderr() { QProcess *process = qobject_cast(sender()); QString stderr(process->readAllStandardError()); stderr.replace("> *Error*:", "

> *Error*:"); stderr.replace("> *ERROR*:", "

> *ERROR*:"); QStringList errors; errors << "*Error*:" << "*ERROR*:"; for (auto &error : errors) { if (stderr.contains(error)) { emit errorFound(); emit messageAvailable("Source Extractor: " + stderr.simplified(), "stop"); break; } } } void SourceExtractorWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // The kill the process that invokes the commandline task extProcess->kill(); emit finished(); } THELI-3.1.3/src/threading/sourceextractorworker.h000066400000000000000000000025431417631501300217630ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef SOURCEEXTRACTORWORKER_H #define SOURCEEXTRACTORWORKER_H #include "worker.h" #include #include class SourceExtractorWorker : public Worker { Q_OBJECT public: explicit SourceExtractorWorker(QString command, QString dir, QObject *parent = nullptr); QString sourceExtractorCommand; QString sourceExtractorDirName; QProcess *extProcess = nullptr; void abort(); // Currently not used anywhere public slots: void runSourceExtractor(); private slots: void processExternalStdout(); void processExternalStderr(); signals: void errorFound(); void messageAvailable(QString message, QString type); }; #endif // SOURCEEXTRACTOR_H THELI-3.1.3/src/threading/swarpworker.cc000066400000000000000000000106631417631501300200230ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "swarpworker.h" #include "../functions.h" #include #include SwarpWorker::SwarpWorker(QString command, QString dir, QString type, QObject *parent) : Worker(parent) { swarpCommand = command; coaddDirName = dir; swarpType = type; } void SwarpWorker::runSwarp() { extProcess = new QProcess(); // connect(&extProcess, &QProcess::readyReadStandardOutput, this, &Controller::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &SwarpWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(coaddDirName); extProcess->start("/bin/sh -c \""+swarpCommand+"\""); extProcess->waitForFinished(-1); if (swarpType == "swarpPreparation") emit finishedPreparation(); if (swarpType == "swarpResampling") emit finishedResampling(threadID); if (swarpType == "swarpCoaddition") emit finishedCoaddition(); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void SwarpWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // Then kill the process that invokes the commandline task extProcess->kill(); emit finished(); } void SwarpWorker::processExternalStderr() { QProcess *process = qobject_cast(sender()); // have to remove the '\x1B[1A' and '\x1B[1M' escape sequences. QString stderr(process->readAllStandardError()); stderr.remove(QRegExp("[^a-zA-Z\\d\\s\\.\\:\\-\\_/]")); stderr.remove("1A1M "); stderr.remove("1A "); stderr.remove("1M "); stderr = stderr.simplified(); stderr.replace(" Center:", "
Center:"); stderr.replace(" Gain:", "
Gain:"); stderr.replace(" Scale:", "
Scale:"); stderr.replace(" Background:", "
Background:"); stderr.replace(" RMS:", "
RMS:"); stderr.replace(" Weight scale:", "
Weight scale:"); stderr.replace("... Looking for ", "
Looking for "); stderr.replace(" Examining input data ...", "
Examining input data"); stderr.replace(" Creating NEW output image ", "
Creating NEW output image "); stderr.replace(" Creating NEW weight-map ", "
Creating NEW weight-map "); stderr.replace(" ----- SWarp ", "
----- SWarp "); stderr.replace(" ------- Output File coadd.fits:", "
------- Output File coadd.fits:"); stderr.replace(" Flux scaling astrom/photom:", "
Flux scaling astrom/photom:"); stderr.replace(" -------------- File", "
-------------- File"); stderr.remove(QRegExp("^1A")); stderr.remove(" 0m "); stderr.remove(" 7m "); QStringList warnings; warnings << "WARNING: Astrometric approximation too inaccurate for this re-projection"; warnings << "Significant inaccuracy likely to occur in projection"; warnings << "inaccuracies likely to occur"; QStringList errors; errors << "Error:"; errors << "Null or negative global weighting factor"; errors << "Not enough memory"; errors << "Buffer overflow detected"; errors << "core dumped"; errors << "has flux scale = 0: I will take 1 instead"; errors << "Could not allocate memory"; errors << "set to an unknown keyword"; QString type = "normal"; for (auto &warning : warnings) { if (stderr.contains(warning)) { type = "warning"; break; } } for (auto &error : errors) { if (stderr.contains(error)) { type = "error"; emit errorFound(); break; } } emit messageAvailable(stderr.simplified(), type); } THELI-3.1.3/src/threading/swarpworker.h000066400000000000000000000025721417631501300176650ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef SWARPWORKER_H #define SWARPWORKER_H #include "worker.h" #include #include class SwarpWorker : public Worker { Q_OBJECT public: explicit SwarpWorker(QString command, QString dir, QString type, QObject *parent = nullptr); QString swarpCommand; QString coaddDirName; QString swarpType; int threadID = 0; QProcess *extProcess = nullptr; void abort(); public slots: void runSwarp(); signals: void finishedPreparation(); void errorFound(); void finishedResampling(int threadID); void finishedCoaddition(); void messageAvailable(QString message, QString type); private slots: void processExternalStderr(); }; #endif // SWARPWORKER_H THELI-3.1.3/src/threading/worker.cc000066400000000000000000000032071417631501300167420ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "worker.h" Worker:: Worker(QObject *parent) : QObject(parent) { } void Worker::pause() { auto const dispatcher = QThread::currentThread()->eventDispatcher(); if (!dispatcher) { // qDebug() << "thread with no dispatcher"; return; } if (state != RUNNING) return; state = PAUSED; // qDebug() << "paused"; do { dispatcher->processEvents(QEventLoop::WaitForMoreEvents); } while (state == PAUSED); } void Worker::resume() { if (state == PAUSED) { state = RUNNING; // qDebug() << "resumed"; } } void Worker::cancel() { if (state != IDLE) { state = IDLE; // qDebug() << "cancelled"; } } bool Worker::isCancelled() { auto const dispatcher = QThread::currentThread()->eventDispatcher(); if (!dispatcher) { // qDebug() << "thread with no dispatcher"; return false; } dispatcher->processEvents(QEventLoop::AllEvents); return state == IDLE; } THELI-3.1.3/src/threading/worker.h000066400000000000000000000022711417631501300166040ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef WORKER_H #define WORKER_H #include #include #include #include class Worker : public QObject { Q_OBJECT public: explicit Worker(QObject *parent = 0); signals: void started(); void finished(); void messageAvailable(QString message, QString type); public slots: void pause(); void resume(); void cancel(); protected: enum State { IDLE, RUNNING, PAUSED }; State state = IDLE; bool isCancelled(); }; #endif // WORKER_H THELI-3.1.3/src/tools/000077500000000000000000000000001417631501300143135ustar00rootroot00000000000000THELI-3.1.3/src/tools/cfitsioerrorcodes.cc000066400000000000000000000263511417631501300203610ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "cfitsioerrorcodes.h" #include CfitsioErrorCodes::CfitsioErrorCodes(QObject *parent) : QObject(parent) { populateErrorKeyMap(); } void CfitsioErrorCodes::populateErrorKeyMap() { errorKeyMap.insert(101, "SAME_FILE: input and output files are the same"); errorKeyMap.insert(103, "TOO_MANY_FILES: tried to open too many FITS files"); errorKeyMap.insert(104, "FILE_NOT_OPENED: could not open the named file"); errorKeyMap.insert(105, "FILE_NOT_CREATED: could not create the named file"); errorKeyMap.insert(106, "WRITE_ERROR: error writing to FITS file"); errorKeyMap.insert(107, "END_OF_FILE: tried to move past end of file"); errorKeyMap.insert(108, "READ_ERROR: error reading from FITS file"); errorKeyMap.insert(110, "FILE_NOT_CLOSED: could not close the file"); errorKeyMap.insert(111, "ARRAY_TOO_BIG: array dimensions exceed internal limit"); errorKeyMap.insert(112, "READONLY_FILE: Cannot write to readonly file"); errorKeyMap.insert(113, "MEMORY_ALLOCATION: Could not allocate memory"); errorKeyMap.insert(114, "BAD_FILEPTR: invalid fitsfile pointer"); errorKeyMap.insert(115, "NULL_INPUT_PTR: NULL input pointer to routine"); errorKeyMap.insert(116, "SEEK_ERROR: error seeking position in file"); errorKeyMap.insert(121, "BAD_URL_PREFIX: invalid URL prefix on file name"); errorKeyMap.insert(122, "TOO_MANY_DRIVERS: tried to register too many IO drivers"); errorKeyMap.insert(123, "DRIVER_INIT_FAILED: driver initialization failed"); errorKeyMap.insert(124, "NO_MATCHING_DRIVER: matching driver is not registered"); errorKeyMap.insert(125, "URL_PARSE_ERROR: failed to parse input file URL"); errorKeyMap.insert(126, "RANGE_PARSE_ERROR: failed to parse input file URL"); errorKeyMap.insert(150, "SHARED_ERRBASE"); errorKeyMap.insert(151, "SHARED_BADARG"); errorKeyMap.insert(152, "SHARED_NULPTR"); errorKeyMap.insert(153, "SHARED_TABFULL"); errorKeyMap.insert(154, "SHARED_NOTINIT"); errorKeyMap.insert(155, "SHARED_IPCERR"); errorKeyMap.insert(156, "SHARED_NOMEM"); errorKeyMap.insert(157, "SHARED_AGAIN"); errorKeyMap.insert(158, "SHARED_NOFILE"); errorKeyMap.insert(159, "SHARED_NORESIZE"); errorKeyMap.insert(201, "HEADER_NOT_EMPTY: header already contains keywords"); errorKeyMap.insert(202, "KEY_NO_EXIST: keyword not found in header"); errorKeyMap.insert(203, "KEY_OUT_BOUNDS: keyword record number is out of bounds"); errorKeyMap.insert(204, "VALUE_UNDEFINED: keyword value field is blank"); errorKeyMap.insert(205, "NO_QUOTE: string is missing the closing quote"); errorKeyMap.insert(206, "BAD_INDEX_KEY: illegal indexed keyword name"); errorKeyMap.insert(207, "BAD_KEYCHAR: illegal character in keyword name or card"); errorKeyMap.insert(208, "BAD_ORDER: required keywords out of order"); errorKeyMap.insert(209, "NOT_POS_INT: keyword value is not a positive integer"); errorKeyMap.insert(210, "NO_END: couldn't find END keyword"); errorKeyMap.insert(211, "BAD_BITPIX: illegal BITPIX keyword value"); errorKeyMap.insert(212, "BAD_NAXIS: illegal NAXIS keyword value"); errorKeyMap.insert(213, "BAD_NAXES: illegal NAXISn keyword value"); errorKeyMap.insert(214, "BAD_PCOUNT: illegal PCOUNT keyword value"); errorKeyMap.insert(215, "BAD_GCOUNT: illegal GCOUNT keyword value"); errorKeyMap.insert(216, "BAD_TFIELDS: illegal TFIELDS keyword value"); errorKeyMap.insert(217, "NEG_WIDTH: negative table row size"); errorKeyMap.insert(218, "NEG_ROWS: negative number of rows in table"); errorKeyMap.insert(219, "COL_NOT_FOUND: column with this name not found in table"); errorKeyMap.insert(220, "BAD_SIMPLE: illegal value of SIMPLE keyword "); errorKeyMap.insert(221, "NO_SIMPLE: Primary array doesn't start with SIMPLE"); errorKeyMap.insert(222, "NO_BITPIX: Second keyword not BITPIX"); errorKeyMap.insert(223, "NO_NAXIS: Third keyword not NAXIS"); errorKeyMap.insert(224, "NO_NAXES: Couldn't find all the NAXISn keywords"); errorKeyMap.insert(225, "NO_XTENSION: HDU doesn't start with XTENSION keyword"); errorKeyMap.insert(226, "NOT_ATABLE: the CHDU is not an ASCII table extension"); errorKeyMap.insert(227, "NOT_BTABLE: the CHDU is not a binary table extension"); errorKeyMap.insert(228, "NO_PCOUNT: couldn't find PCOUNT keyword"); errorKeyMap.insert(229, "NO_GCOUNT: couldn't find GCOUNT keyword"); errorKeyMap.insert(230, "NO_TFIELDS: couldn't find TFIELDS keyword"); errorKeyMap.insert(231, "NO_TBCOL: couldn't find TBCOLn keyword"); errorKeyMap.insert(232, "NO_TFORM: couldn't find TFORMn keyword"); errorKeyMap.insert(233, "NOT_IMAGE: the CHDU is not an IMAGE extension"); errorKeyMap.insert(234, "BAD_TBCOL: TBCOLn keyword value < 0 or > rowlength"); errorKeyMap.insert(235, "NOT_TABLE: the CHDU is not a table"); errorKeyMap.insert(236, "COL_TOO_WIDE: column is too wide to fit in table"); errorKeyMap.insert(237, "COL_NOT_UNIQUE: more than 1 column name matches template"); errorKeyMap.insert(241, "BAD_ROW_WIDTH: sum of column widths not = NAXIS1"); errorKeyMap.insert(251, "UNKNOWN_EXT: unrecognizable FITS extension type"); errorKeyMap.insert(252, "UNKNOWN_REC: unrecognizable FITS record"); errorKeyMap.insert(253, "END_JUNK: END keyword is not blank"); errorKeyMap.insert(254, "BAD_HEADER_FILL: Header fill area not blank"); errorKeyMap.insert(255, "BAD_DATA_FILL: Data fill area not blank or zero"); errorKeyMap.insert(261, "BAD_TFORM: illegal TFORM format code"); errorKeyMap.insert(262, "BAD_TFORM_DTYPE: unrecognizable TFORM datatype code"); errorKeyMap.insert(263, "BAD_TDIM: illegal TDIMn keyword value"); errorKeyMap.insert(264, "BAD_HEAP_PTR: invalid BINTABLE heap address"); errorKeyMap.insert(301, "BAD_HDU_NUM: HDU number < 1 or > MAXHDU"); errorKeyMap.insert(302, "BAD_COL_NUM: column number < 1 or > tfields"); errorKeyMap.insert(304, "NEG_FILE_POS: tried to move before beginning of file "); errorKeyMap.insert(306, "NEG_BYTES: tried to read or write negative bytes"); errorKeyMap.insert(307, "BAD_ROW_NUM: illegal starting row number in table"); errorKeyMap.insert(308, "BAD_ELEM_NUM: illegal starting element number in vector"); errorKeyMap.insert(309, "NOT_ASCII_COL: this is not an ASCII string column"); errorKeyMap.insert(310, "NOT_LOGICAL_COL: this is not a logical datatype column"); errorKeyMap.insert(311, "BAD_ATABLE_FORMAT: ASCII table column has wrong format"); errorKeyMap.insert(312, "BAD_BTABLE_FORMAT: Binary table column has wrong format"); errorKeyMap.insert(314, "NO_NULL: null value has not been defined"); errorKeyMap.insert(317, "NOT_VARI_LEN: this is not a variable length column"); errorKeyMap.insert(320, "BAD_DIMEN: illegal number of dimensions in array"); errorKeyMap.insert(321, "BAD_PIX_NUM: first pixel number greater than last pixel"); errorKeyMap.insert(322, "ZERO_SCALE: illegal BSCALE or TSCALn keyword = 0"); errorKeyMap.insert(323, "NEG_AXIS: illegal axis length < 1"); errorKeyMap.insert(340, "NOT_GROUP_TABLE"); errorKeyMap.insert(341, "HDU_ALREADY_MEMBER"); errorKeyMap.insert(342, "MEMBER_NOT_FOUND"); errorKeyMap.insert(343, "GROUP_NOT_FOUND"); errorKeyMap.insert(344, "BAD_GROUP_ID"); errorKeyMap.insert(345, "TOO_MANY_HDUS_TRACKED"); errorKeyMap.insert(346, "HDU_ALREADY_TRACKED"); errorKeyMap.insert(347, "BAD_OPTION"); errorKeyMap.insert(348, "IDENTICAL_POINTERS"); errorKeyMap.insert(349, "BAD_GROUP_ATTACH"); errorKeyMap.insert(350, "BAD_GROUP_DETACH"); errorKeyMap.insert(360, "NGP_NO_MEMORY: malloc failed"); errorKeyMap.insert(361, "NGP_READ_ERR: read error from file"); errorKeyMap.insert(362, "NGP_NUL_PTR: null pointer passed as argument"); errorKeyMap.insert(363, "NGP_EMPTY_CURLINE: line read seems to be empty"); errorKeyMap.insert(364, "NGP_UNREAD_QUEUE_FULL: cannot unread more then 1 line (or single line twice)"); errorKeyMap.insert(365, "NGP_INC_NESTING: too deep include file nesting (inf. loop ?)"); errorKeyMap.insert(366, "NGP_ERR_FOPEN: fopen() failed, cannot open file"); errorKeyMap.insert(367, "NGP_EOF: end of file encountered"); errorKeyMap.insert(368, "NGP_BAD_ARG: bad arguments passed"); errorKeyMap.insert(369, "NGP_TOKEN_NOT_EXPECT: token not expected here"); errorKeyMap.insert(401, "BAD_I2C: bad int to formatted string conversion"); errorKeyMap.insert(402, "BAD_F2C: bad float to formatted string conversion"); errorKeyMap.insert(403, "BAD_INTKEY: can't interprete keyword value as integer"); errorKeyMap.insert(404, "BAD_LOGICALKEY: can't interprete keyword value as logical"); errorKeyMap.insert(405, "BAD_FLOATKEY: can't interprete keyword value as float"); errorKeyMap.insert(406, "BAD_DOUBLEKEY: can't interprete keyword value as double"); errorKeyMap.insert(407, "BAD_C2I: bad formatted string to int conversion"); errorKeyMap.insert(408, "BAD_C2F: bad formatted string to float conversion"); errorKeyMap.insert(409, "BAD_C2D: bad formatted string to double conversion"); errorKeyMap.insert(410, "BAD_DATATYPE: bad keyword datatype code"); errorKeyMap.insert(411, "BAD_DECIM: bad number of decimal places specified"); errorKeyMap.insert(412, "NUM_OVERFLOW: overflow during datatype conversion"); errorKeyMap.insert(413, "DATA_COMPRESSION_ERR: error in imcompress routines"); errorKeyMap.insert(414, "DATA_DECOMPRESSION_ERR: error in imcompress routines"); errorKeyMap.insert(415, "NO_COMPRESSED_TILE: compressed tile doesn't exist"); errorKeyMap.insert(420, "BAD_DATE: error in date or time conversion"); errorKeyMap.insert(431, "PARSE_SYNTAX_ERR: syntax error in parser expression"); errorKeyMap.insert(432, "PARSE_BAD_TYPE: expression did not evaluate to desired type"); errorKeyMap.insert(433, "PARSE_LRG_VECTOR: vector result too large to return in array"); errorKeyMap.insert(434, "PARSE_NO_OUTPUT: data parser failed not sent an out column"); errorKeyMap.insert(435, "PARSE_BAD_COL: bad data encounter while parsing column"); errorKeyMap.insert(436, "PARSE_BAD_OUTPUT: Output file not of proper type"); errorKeyMap.insert(501, "ANGLE_TOO_BIG: celestial angle too large for projection"); errorKeyMap.insert(502, "BAD_WCS_VAL: bad celestial coordinate or pixel value"); errorKeyMap.insert(503, "WCS_ERROR: error in celestial coordinate calculation"); errorKeyMap.insert(504, "BAD_WCS_PROJ: unsupported type of celestial projection"); errorKeyMap.insert(505, "NO_WCS_KEY: celestial coordinate keywords not found"); errorKeyMap.insert(506, "APPROX_WCS_KEY: approximate WCS keywords were calculated"); } THELI-3.1.3/src/tools/cfitsioerrorcodes.h000066400000000000000000000017771417631501300202300ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef CFITSIOERRORCODES_H #define CFITSIOERRORCODES_H #include #include class CfitsioErrorCodes : public QObject { Q_OBJECT void populateErrorKeyMap(); public: explicit CfitsioErrorCodes(QObject *parent = nullptr); QMap errorKeyMap; signals: public slots: }; #endif // CFITSIOERRORCODES_H THELI-3.1.3/src/tools/correlator.cc000066400000000000000000000144521417631501300170040ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "correlator.h" #include "../myimage/myimage.h" #include #include #include #include #include #include #include // #include "Array.h" // #include "fftw++.h" #include Correlator::Correlator(const MyImage *refimg, const MyImage *comimg, QObject *parent) : QObject(parent) { naxis1 = refimg->naxis1; naxis2 = refimg->naxis2; if (refimg->naxis1 != comimg->naxis1 || refimg->naxis2 != comimg->naxis2) { qDebug() << "ERROR: Correlator(): images have different geometries!"; successProcessing = false; } padImages(refimg->dataCurrent, comimg->dataCurrent); } void Correlator::padImages(const QVector &dataref, const QVector &datacom) { if (! successProcessing) return; // Zeropad data, to accomodate very large offsets // Max offset is the full field of view, thus we double the image size n_pad = 2*naxis1-1; m_pad = 2*naxis2-1; dataRef.resize(n_pad*m_pad); dataCom.resize(n_pad*m_pad); dataCorrelated.resize(n_pad*m_pad); dataRef.squeeze(); dataCom.squeeze(); dataCorrelated.squeeze(); int left = naxis1/2; int right = naxis1/2; int bottom = naxis2/2; int top = naxis2/2; for (int j=0; j=left && i=bottom && j fa(n,m,align), fb(n,m,align); Array::array2 ga(n,mp,align), gb(n,mp,align); fftwpp::rcfft2d Forward_a(n,m,fa,ga); fftwpp::rcfft2d Forward_b(n,m,fb,gb); fftwpp::crfft2d Backward(n,m,ga,fa); // write the data into arrays for (int i=0; i Correlator::find_peak() { if (! successProcessing) return QVector(); /* long ipos = 0; long jpos = 0; double max = 0.; // ignore the boundary (FFT may put spurious pixels there) // we choose a 3 pixel wide boundary, so there won't be any boundary issues when assigning the 7x7 subarray for (int j=3; j= max) { ipos = i; jpos = j; max = (double) dataCorrelated[i+n_pad*j]; } } } double xpos = (double) ipos; double ypos = (double) jpos; // we fit a 7x7 pixel area centred on the maximum pixel const size_t nx = 7, ny = 7, n = 7*7; const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; int status; const size_t p = 4; gsl_matrix *covar = gsl_matrix_alloc (p, p); double z[n], sigma[n]; struct dataGSL d = { nx, ny, z, sigma }; gsl_multifit_function_fdf f; const gsl_rng_type *type; gsl_rng *r; gsl_rng_env_setup(); type = gsl_rng_default; r = gsl_rng_alloc (type); f.f = &gauss_f; f.df = &gauss_df; f.fdf = &gauss_fdf; f.n = n; f.p = p; f.params = &d; // The data in which we search the maximum unsigned int k = 0; for (int j=-3; j<=3; ++j) { for (int i=-3; i<=3; ++i) { z[k] = dataCorrelated[ipos+i+n_pad*(jpos+j)] / max; sigma[k++] = 1.; // same weight for all pixels } } // the initial guess has to be as close as possible (totally sucks...) double x_init[4] = { 1.0, 3.0, 3.0, 2.0 }; gsl_vector_view x = gsl_vector_view_array (x_init, p); T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, &f, &x.vector); unsigned int iter = 0; do { ++iter; status = gsl_multifit_fdfsolver_iterate(s); if (status) break; status = gsl_multifit_test_delta (s->dx, s->x, 1e-4, 1e-4); } while (status == GSL_CONTINUE && iter < 50000); // gsl_multifit_covar (s->J, 0.0, covar); #define FIT(i) gsl_vector_get(s->x, i) // #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) QVector result; result.append(FIT(1)+xpos-3.0+1.0); result.append(FIT(2)+ypos-3.0+1.0); gsl_multifit_fdfsolver_free(s); gsl_matrix_free(covar); gsl_rng_free(r); return result */ return QVector(); } THELI-3.1.3/src/tools/correlator.h000066400000000000000000000026141417631501300166430ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef CORRELATOR_H #define CORRELATOR_H #include "../myimage/myimage.h" #include #include #include #include class Correlator : public QObject { Q_OBJECT public: explicit Correlator(const MyImage *refimg, const MyImage *comimg, QObject *parent = nullptr); int numThreads = 1; void xcorrelate(); QVector find_peak(); private: int naxis1; int naxis2; int n_pad; int m_pad; QVector dataRef; QVector dataCom; QVector dataCorrelated; bool successProcessing = true; void padImages(const QVector &dataref, const QVector &datacom); signals: public slots: }; #endif // CORRELATOR_H THELI-3.1.3/src/tools/cpu.cc000066400000000000000000000124401417631501300154120ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "cpu.h" #include #include #include #include #include #include #include #include #include #include #include "fitsio.h" #ifdef __MACH__ #include #define MACOS #elif __LINUX__ #define LINUX #endif CPU::CPU(QObject *parent) : QObject(parent) { file.setFileName("/proc/stat"); if ( !file.open(QIODevice::ReadOnly)) { CPUbarDeactivated = true; return; } instream.setDevice(&file); maxCPU = QThread::idealThreadCount(); if (!fits_is_reentrant()) maxCPU = 1; // new method init(); } CPU::~CPU() { file.close(); } int CPU::getCPUload() { if (CPUbarDeactivated) return 0; // Take two snapshots 250 ms apart if (kernelType == "linux") { readStatsCPU_Linux(tot1, idle1); QTest::qWait(250); readStatsCPU_Linux(tot2, idle2); } else if (kernelType == "darwin") { readStatsCPU_MAC(tot1, idle1); QTest::qWait(250); readStatsCPU_MAC(tot2, idle2); } double dTot = tot2-tot1; double dIdle = idle2-idle1; int CPUload = 100. * maxCPU * (dTot - dIdle) / dTot; return CPUload; } void CPU::readStatsCPU_Linux(double &totval, double &idleval) { // Reset file to beginning instream.seek(0); double tot = 0.; double idle = 0.; QString line = instream.readLine().simplified(); QStringList values = line.split(" "); if (values[0] == "cpu") { for (int i=1; ikernelType(); if (kernelType == "linux") { // Reset file to beginning lastTotal = 0; lastTotalActive = 0; lastTotalIdle = 0; instream.seek(0); QStringList values = instream.readLine().simplified().split(" "); for (int i=1; i #include #include #include class CPU : public QObject { Q_OBJECT public: explicit CPU(QObject *parent = nullptr); ~CPU(); int getCPUload(); void getCPUInfo_MAC(unsigned long *pulSystem, unsigned long *pulUser, unsigned long *pulNice, unsigned long *pulIdle); float getCurrentValue(); signals: private: bool CPUbarDeactivated = false; double tot1 = 0.; double tot2 = 0.; double idle1 = 0.; double idle2 = 0.; void readStatsCPU_Linux(double &totval, double &idleval); void readStatsCPU_MAC(double &totval, double &idleval); QFile file; QTextStream instream; int maxCPU = 1; QString kernelType; long long lastTotal = 0; long long lastTotalActive = 0; long long lastTotalIdle = 0; void init(); public slots: }; #endif // CPU_H THELI-3.1.3/src/tools/debayer.cc000066400000000000000000000412441417631501300162420ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include #include "tools.h" #include "../myimage/myimage.h" #include // For debayering float hue_transit(float l1, float l2, float l3, float v1, float v3) { //printf("hue_transit: l1 %5.1f l2 %5.1f l3 %5.1f v1 %5.1f v3 %5.1f\n",l1,l2,l3,v1,v3); if ((l1 l2 && l2 > l3)) return (v1+(v3-v1) * (l2-l1)/(l3-l1)); else return ((v1+v3)/2.0 + (l2*2.0-l1-l3)/4.0); } // For debayering int direction(float N, float E, float W, float S) { if (N < E && W < S) { if ( N < W) return 1; else return 3; } else { if (E < S) return 2; else return 4; } } // Qt5 implementation of the PPG (patterened pixel grouping) algorithm by Chuan-Kai Lin, // originally published at https://sites.google.com/site/chklin/demosaic. The URL is no longer available // but can be found here: // https://web.archive.org/web/20160923211135/https://sites.google.com/site/chklin/demosaic/ // First implementation for THELI v2 by Carsten Moos. // The input image becomes the R-band channel void debayer(int chip, MyImage *image, MyImage *imageB, MyImage *imageG, MyImage *imageR) { if (!image->successProcessing) return; QString pattern = image->getKeyword("BAYER"); if ( pattern != "RGGB" && pattern != "GRBG" && pattern != "GBRG" && pattern != "BGGR") { qDebug() << "Tools::debayer(): Bayer pattern not recognised. Nothing will be done.\n"; image->successProcessing = false; return; } // chop the last row / column of pixels if the image dimensions are uneven int n = image->naxis1; int m = image->naxis2; if ( n % 2 != 0) n = n - 1; if ( m % 2 != 0) m = m - 1; // Setup the debayered channels QList list; list << imageB << imageG << imageR; double mjdOffset = 0.; for (auto &it: list) { it->naxis1 = n; it->naxis2 = m; it->dataCurrent.resize(n*m); it->dataCurrent.squeeze(); it->path = image->path; it->weightPath = image->weightPath; it->baseName = image->rootName; it->rootName = image->rootName; it->chipName = image->rootName+"_"+QString::number(image->chipNumber); it->exptime = image->exptime; it->header = image->header; it->pathBackupL1 = image->pathBackupL1; it->baseNameBackupL1 = image->baseNameBackupL1; it->imageInMemory = true; it->wcs = image->wcs; it->plateScale = image->plateScale; it->wcsInit = image->wcsInit; it->gain = image->gain; it->airmass = image->airmass; it->fwhm = image->fwhm; it->fwhm_est = image->fwhm_est; it->gain = image->gain; it->ellipticity = image->ellipticity; it->ellipticity_est = image->ellipticity_est; it->RZP = image->RZP; it->gainNormalization = image->gainNormalization; it->hasMJDread = image->hasMJDread; it->headerInfoProvided = image->headerInfoProvided; it->skyValue = image->skyValue; it->modeDetermined = image->modeDetermined; it->fullheader = image->fullheader; it->dateobs = image->dateobs; it->cornersToRaDec(); // Data::populateExposureList() will group debayered images into one exposure, and then // mergeScampCatalogs() will create three extensions. But we need them individually. // Hence introducing a 0.1 s offset in MJD-OBS. // Fixing Data::populateExposureList() is non-trivial it->mjdobs = image->mjdobs + mjdOffset; mjdOffset += 1.e-6; } imageB->baseName.append("_B_"+QString::number(chip+1)); // status 'PA' will be appended externally imageG->baseName.append("_G_"+QString::number(chip+1)); imageR->baseName.append("_R_"+QString::number(chip+1)); imageB->rootName.append("_B"); imageG->rootName.append("_G"); imageR->rootName.append("_R"); imageB->chipName = imageB->baseName; imageG->chipName = imageG->baseName; imageR->chipName = imageR->baseName; imageB->filter = "B"; imageG->filter = "G"; imageR->filter = "R"; for (auto &card : imageB->header) { if (card.contains("FILTER = ")) { card = "FILTER = 'B'"; card.resize(80, ' '); } } for (auto &card : imageG->header) { if (card.contains("FILTER = ")) { card = "FILTER = 'G'"; card.resize(80, ' '); } } for (auto &card : imageR->header) { if (card.contains("FILTER = ")) { card = "FILTER = 'R'"; card.resize(80, ' '); } } // ==== BEGIN PPG algorithm === // cut all patterns to RGGB int xoffset; int yoffset; if (pattern == "RGGB") { xoffset = 0; yoffset = 0; } else if (pattern == "GRBG") { xoffset = 1; yoffset = 0; } else if (pattern == "GBRG") { xoffset = 0; yoffset = 1; } else { // pattern == "BGGR" xoffset = 1; yoffset = 1; } /* // The Bayer pattern looks like this RGRGRGRGR gBgBgBgBg RGRGRGRGR gBgBgBgBg */ long k = 0; QVector &I = image->dataCurrent; QVector &R = imageR->dataCurrent; QVector &G = imageG->dataCurrent; QVector &B = imageB->dataCurrent; // Calculate the green values at red and blue pixels for (long j=0; j=m-3 || i<=2 || i>=n-3) { // 3 rows top bottom left right R[k] = I[(i+n*j)]; // all the same with current color G[k] = I[(i+n*j)]; B[k] = I[(i+n*j)]; ++k; } else{ // gradient calculation for green values at red or blue pixels float DN = fabs(I[(i-2*n+n*j)]-I[(i+n*j)])*2.0 + fabs(I[(i-n+n*j)]-I[(i+n+n*j)]); float DE = fabs(I[(i+n*j)] -I[(i+2+n*j)])*2.0 + fabs(I[(i-1+n*j)]-I[(i+1+n*j)]); float DW = fabs(I[(i-2+n*j)] -I[(i+n*j)])*2.0 + fabs(I[(i-1+n*j)]-I[(i+1+n*j)]); float DS = fabs(I[(i+n*j)] -I[(i+2*n+n*j)])*2.0 + fabs(I[(i-n+n*j)]-I[(i+n+n*j)]); if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0) { // red pixel R[k] = I[(i+n*j)]; switch (direction(DN,DE,DW,DS)) { case 1: G[k] = (I[(i-n+n*j)]*3.0 + I[(i+n*j)] + I[(i+n+n*j)] - I[(i-2*n+n*j)]) / 4.0; break; case 2: G[k] = (I[(i+1+n*j)]*3.0 + I[(i+n*j)] + I[(i-1+n*j)] - I[(i+2+n*j)]) / 4.0; break; case 3: G[k] = (I[(i-1+n*j)]*3.0 + I[(i+n*j)] + I[(i+1+n*j)] - I[(i-2+n*j)]) / 4.0; break; case 4: G[k] = (I[(i+n+n*j)]*3.0 + I[(i+n*j)] + I[(i-n+n*j)] - I[(i+2*n+n*j)]) / 4.0; break; } ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel switch (direction(DN,DE,DW,DS)){ case 1: G[k] = (I[(i-n+n*j)]*3.0 + I[(i+n*j)] + I[(i+n+n*j)] - I[(i-2*n+n*j)]) / 4.0; break; case 2: G[k] = (I[(i+1+n*j)]*3.0 + I[(i+n*j)] + I[(i-1+n*j)] - I[(i+2+n*j)]) / 4.0; break; case 3: G[k] = (I[(i-1+n*j)]*3.0 + I[(i+n*j)] + I[(i+1+n*j)] - I[(i-2+n*j)]) / 4.0; break; case 4: G[k] = (I[(i+n+n*j)]*3.0 + I[(i+n*j)] + I[(i-n+n*j)] - I[(i+2*n+n*j)]) / 4.0; break; } B[k] = I[(i+n*j)]; ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above G[k] = I[(i+n*j)]; ++k; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above G[k] = I[(i+n*j)]; ++k; } } } } k = 0; // Calculating blue and red at green pixels // Calculating blue or red at red or blue pixels for (long j=0; j=m-3 || i<=2 || i>=n-3) { // 3 rows top bottom left right if (!xoffset && !yoffset) { // RGGB if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i+1+n*j)]; B[k] = I[(i+1+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i-n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i-1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i-1-n+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i+n*j)]; } } else if (xoffset && !yoffset) { //GRBG if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i-1+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i-n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i+1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i+1-n+n*j)]; G[k] = I[(i+1+n*j)]; B[k] = I[(i+n*j)]; } } else if (!xoffset && yoffset) { //GBRG if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i-n+n*j)]; B[k] = I[(i+1-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i+n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i-1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i-1+n+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i+n*j)]; } } else if (xoffset && yoffset) { //BGGR if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i-1-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i+n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i+1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i+1+n+n*j)]; G[k] = I[(i+1+n*j)]; B[k] = I[(i+n*j)]; } } ++k; } else{ // diagonal gradients float dne = fabs(I[(i-n+1+n*j)]-I[(i+n-1+n*j)]) + fabs(I[(i-2*n+2+n*j)]-I[(i+n*j)]) + fabs(I[(i+n*j)]-I[(i+2*n-2+n*j)]) + fabs(G[(i-n+1+n*j)]-G[(i+n*j)]) + fabs(G[(i+n*j)]-G[(i+n-1+n*j)]); float dnw = fabs(I[(i-n-1+n*j)]-I[(i+n+1+n*j)]) + fabs(I[(i-2-2*n+n*j)]-I[(i+n*j)]) + fabs(I[(i+n*j)]-I[(i+2+2*n+n*j)]) + fabs(G[(i-n-1+n*j)]-G[(i+n*j)]) + fabs(G[(i+n*j)]-G[(i+n+1+n*j)]); if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0) { // red pixel if (dne <= dnw) B[k] = hue_transit(G[i-n+1+n*j], G[i+n*j], G[i+n-1+n*j], I[(i-n+1+n*j)], I[(i+n-1+n*j)]); else B[k] = hue_transit(G[i-n-1+n*j], G[i+n*j], G[i+n+1+n*j], I[(i-n-1+n*j)], I[(i+n+1+n*j)]); ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0) { // green pixel, red above R[k] = hue_transit(G[(i-n+n*j)], I[(i+n*j)], G[(i+n+n*j)], I[(i-n+n*j)], I[(i+n+n*j)]); B[k] = hue_transit(G[(i-1+n*j)], I[(i+n*j)], G[(i+1+n*j)], I[(i-1+n*j)], I[(i+1+n*j)]); ++k; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1) { // green pixel, blue above R[k] = hue_transit(G[(i-1+n*j)], I[(i+n*j)], G[(i+1+n*j)], I[(i-1+n*j)], I[(i+1+n*j)]); B[k] = hue_transit(G[(i-n+n*j)], I[(i+n*j)], G[(i+n+n*j)], I[(i-n+n*j)], I[(i+n+n*j)]); ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1) { // blue pixel if (dne <= dnw) R[k] = hue_transit(G[(i-n+1+n*j)], G[(i+n*j)], G[(i+n-1+n*j)], I[(i-n+1+n*j)], I[(i+n-1+n*j)]); else R[k] = hue_transit(G[(i-n-1+n*j)], G[(i+n*j)], G[(i+n+1+n*j)], I[(i-n-1+n*j)], I[(i+n+1+n*j)]); ++k; } } } } // === END PPG algorithm === } void updateDebayerMemoryStatus(MyImage *image) { if (!image->successProcessing) return; image->imageInMemory = true; image->dataBackupL1 = image->dataCurrent; image->backupL1InMemory = true; } // Remove the relative sensitivity pattern from the bayerflat // (Calculate an average 2x2 superpixel and divide the flat by it) void equalizeBayerFlat(MyImage *image) { int n = image->naxis1; int m = image->naxis2; // calculate the average 2x2 pixel float ll = 0.; float lr = 0.; float ul = 0.; float ur = 0.; for (int j=0; jdataCurrent[i+n*j]; lr += image->dataCurrent[i+1+n*j]; ul += image->dataCurrent[i+n*(j+1)]; ur += image->dataCurrent[i+1+n*(j+1)]; } } ll /= ( n*m / 4. ); lr /= ( n*m / 4. ); ul /= ( n*m / 4. ); ur /= ( n*m / 4. ); // The four values above have the average intensity of the flat. // We want to preserve it after the super pixel normalization float sum = (ll + lr + ul + ur) / 4.; ll /= sum; lr /= sum; ul /= sum; ur /= sum; // Normalize the flat for (int j=0; jdataCurrent[i+n*j] /= ll; image->dataCurrent[i+1+n*j] /= lr; image->dataCurrent[i+n*(j+1)] /= ul; image->dataCurrent[i+1+n*(j+1)] /= ur; } } // Update the mode image->updateMode(); } THELI-3.1.3/src/tools/detectedobject.cc000066400000000000000000000722711417631501300176030ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // THELI internal source detection, (mostly) using the definitions and nomenclature from // https://sextractor.readthedocs.io/en/latest/index.html #include "detectedobject.h" #include #include "functions.h" #include #include "wcs.h" #include "wcshdr.h" // ======== WARNING ========================================== // // Image position parameters X, Y, XWIN and YWIN are zero-indexed // (must add +1 to be consistent with FITS convention) // // ============================================================== DetectedObject::DetectedObject(const QList &objectIndices, const QVector &data, const QVector &background, const QVector &weight, const QVector &_mask, bool weightinmemory, const long nax1, const long nax2, const long objid, const float satVal, const float gainval, wcsprm &wcsImage, QObject *parent) : QObject(parent), dataMeasure(data), dataBackground(background), dataWeight(weight), mask(_mask), weightInMemory(weightinmemory), wcs(wcsImage), saturationValue(0.98*satVal), // 98%: some margin against effective saturation, which might occur at slightly lower values already gain(gainval) // GAIN is 1.0 always as we convert ADU to electrons during HDU reformatting, already. Kept for clarity { area = objectIndices.length(); objID = objid; pixels_x.reserve(area); pixels_y.reserve(area); pixels_flux.reserve(area); pixels_back.reserve(area); pixels_weight.reserve(area); naxis1 = nax1; naxis2 = nax2; bitflags.resize(16); /* bit flags 0: at least 10% of object area is masked 1: object has been deblended (not implemented) 2: at least one pixel is saturated 3: the isophotal footprint of the detected object is truncated (too close to an image boundary) 4: the windowed footprint of the detected object is truncated (too close to an image boundary) 5: at least one photometric aperture has masked pixels or is truncated by the image boundary or has zero weight pixels 6: at least one pixel has zero weight 7: spurious or corrupted detection. Could be e.g. a bad column 8: */ // copy the pixel position and pixel value for all pixels comprising this object for (auto &index : objectIndices) { pixels_x.append(index % naxis1); pixels_y.append(index / naxis1); pixels_flux.append(data.at(index)); pixels_back.append(background.at(index)); if (weightInMemory) pixels_weight.append(weight.at(index)); else pixels_weight.append(1.0); } } DetectedObject::~DetectedObject() { remove(); } void DetectedObject::remove() { pixels_flux.clear(); pixels_back.clear(); pixels_weight.clear(); pixelsAper_back.clear(); pixelsAper_flux.clear(); pixelsAper_weight.clear(); pixelsWin_back.clear(); pixelsWin_flux.clear(); pixelsWin_weight.clear(); pixelsWin_x.clear(); pixelsWin_y.clear(); apertures.clear(); pixelsAper_x.clear(); pixelsAper_y.clear(); pixels_x.clear(); pixels_y.clear(); pixels_flux.squeeze(); pixels_back.squeeze(); pixels_weight.squeeze(); pixels_x.squeeze(); pixels_y.squeeze(); pixelsAper_back.squeeze(); pixelsAper_flux.squeeze(); pixelsAper_weight.squeeze(); pixelsWin_back.squeeze(); pixelsWin_flux.squeeze(); pixelsWin_weight.squeeze(); pixelsWin_x.squeeze(); pixelsWin_y.squeeze(); apertures.squeeze(); pixelsAper_x.squeeze(); pixelsAper_y.squeeze(); } void DetectedObject::computeObjectParams() { // Must be done in a specific order // ISOPHOTAL calcFlux(); calcMoments(); calcVariance(); calcEllipticity(); calcMomentsErrors(); calcApertureMagnitudes(); // WINDOWED calcFluxRadius(); calcFWHM(); calcMagAuto(); calcWindowedMoments(); calcWindowedEllipticity(); calcWindowedMomentsErrors(); filterSpuriousDetections(); // Applied only when writing catalogs to disk for scamp // correctOriginOffset(); calcSkyCoords(); } void DetectedObject::calcFlux() { if (badDetection) return; FLUX_ISO = std::accumulate(pixels_flux.begin(), pixels_flux.end(), .0); if (FLUX_ISO < 0.) { bitflags.setBit(7,true); badDetection = true; return; } MAG_ISO = -2.5*log10(FLUX_ISO) + ZP; } QVector DetectedObject::calcFluxAper(float aperture) { // get aperture pixels long xminAper = floor(X-0.5*aperture); long xmaxAper = ceil(X+0.5*aperture); long yminAper = floor(Y-0.5*aperture); long ymaxAper = ceil(Y+0.5*aperture); // Check truncation by image frame if (isTruncated(xminAper, xmaxAper, yminAper, ymaxAper)) bitflags.setBit(5,true); // Truncate if necessary xminAper = xminAper < 0 ? 0 : xminAper; xmaxAper = xmaxAper >=naxis1 ? naxis1-1 : xmaxAper; yminAper = yminAper < 0 ? 0 : yminAper; ymaxAper = ymaxAper >=naxis2 ? naxis2-1 : ymaxAper; long npixAper = (xmaxAper-xminAper+1) * (ymaxAper-yminAper+1); pixelsAper_flux.resize(npixAper); pixelsAper_back.resize(npixAper); pixelsAper_weight.fill(1.0, npixAper); // fill vector with dummy weight (if weight map is not available, e.g. during background object masking) pixelsAper_x.resize(npixAper); pixelsAper_y.resize(npixAper); long k = 0; for (long j=yminAper; j<=ymaxAper; ++j) { for (long i=xminAper; i<=xmaxAper; ++i) { pixelsAper_flux[k] = dataMeasure.at(i+naxis1*j); pixelsAper_back[k] = dataBackground.at(i+naxis1*j); if (weightInMemory) pixelsAper_weight[k] = dataWeight.at(i+naxis1*j); // update weight if weight map is available pixelsAper_x[k] = i; pixelsAper_y[k] = j; ++k; } } // We use a 4 times sub-sampled grid for finer resolution for compact objects smaller than 10 pixels int s = 0; if (XMAX-XMIN <= 10 && YMAX - YMIN <= 10) s = 4; else s = 1; // The measurement window is defined by the aperture long nn = (xmaxAper-xminAper+1) * s; long mm = (ymaxAper-yminAper+1) * s; QVector dataSub(nn*mm, 0); QVector backSub(nn*mm, 0); QVector weightSub(nn*mm, 0); // Subsample the original pixel data. The window is the minimum rectangular envelope long dim = pixelsAper_flux.length(); for (long k=0; k=nn || jj<0 || jj>=mm) continue; double rsq = (xcen-ii)*(xcen-ii) + (ycen-jj)*(ycen-jj); if (rsq <= 0.25*aperture*aperture*s*s) { fluxAper += dataSub[ii+nn*jj]; fluxErrAper += backSub[ii+nn*jj]/gain + dataSub[ii+nn*jj]/gain; if (weightSub[ii+nn*jj] == 0.) bitflags.setBit(5,true); if (dataSub[ii+nn*jj] > saturationValue) bitflags.setBit(2,true); dataSub[ii+nn*jj] = 0.; // just making sure we don't count a pixel twice } } } // correct for subsampling of aperture fluxAper = fluxAper / (s*s); fluxErrAper = fluxErrAper / (s*s); fluxErrAper = sqrt(fluxErrAper); double magAper = -2.5*log10(fluxAper) + ZP; double magErrAper = 99.; if (fluxAper > 0.) magErrAper = 2.5*log10(1.+fluxErrAper/fluxAper); QVector result; result << fluxAper << fluxErrAper << magAper << magErrAper; if ((fluxAper < 0. || std::isnan(magErrAper))) { bitflags.setBit(7,true); badDetection = true; } return result; } void DetectedObject::calcApertureMagnitudes() { if (badDetection) return; if (apertures.isEmpty()) return; FLUX_APER.reserve(apertures.length()); MAG_APER.reserve(apertures.length()); FLUXERR_APER.reserve(apertures.length()); MAGERR_APER.reserve(apertures.length()); QVector result; for (auto &aperture : apertures) { result = calcFluxAper(aperture); FLUX_APER.append(result[0]); FLUXERR_APER.append(result[1]); MAG_APER.append(result[2]); MAGERR_APER.append(result[3]); } } void DetectedObject::calcMoments() { if (badDetection) return; double xsum = 0.; double ysum = 0.; double xxsum = 0.; double yysum = 0.; double xysum = 0.; double xysumsq = 0.; for (long i=0; i= saturationValue) bitflags.setBit(2,true); if (pixels_weight.at(i) == 0.) bitflags.setBit(6,true); xsum += px*pi; ysum += py*pi; xxsum += px*px*pi; yysum += py*py*pi; xysum += px*py*pi; xysumsq += px*px*py*py*pi; } X = xsum / FLUX_ISO; Y = ysum / FLUX_ISO; if (X < 0. || X > naxis1 || Y < 0. || Y > naxis2) { bitflags.setBit(7,true); badDetection = true; return; } X2 = xxsum / FLUX_ISO - X*X; Y2 = yysum / FLUX_ISO - Y*Y; XY = xysum / FLUX_ISO - X*Y; X2Y2 = xysumsq / FLUX_ISO - X*X*Y*Y; // Handling of infinitely thin objects (pathological cases, such as bad columns) double rho = 1/12.; if (X2*Y2 - XY*XY < rho*rho) { bitflags.setBit(7,true); badDetection = true; return; } XMIN = minVec_T(pixels_x); XMAX = maxVec_T(pixels_x); YMIN = minVec_T(pixels_y); YMAX = maxVec_T(pixels_y); double s1 = (X2+Y2) / 2.; double s2 = sqrt((X2-Y2) * (X2-Y2) / 4. + XY*XY); if (s11) { double xsum = 0.; double ysum = 0.; double psum = 0.; double n_nonzero = 0; for (long i=0; i10.) return; // Windowed parameters useful for small objects, only double dsq = 4.*FLUX_RADIUS*FLUX_RADIUS / (8.*log(2.)); double rmaxsq = 4.*FLUX_RADIUS*FLUX_RADIUS; double eps = 2e-4; long iter = 0; long iterMax = 10; // verified that this converges indeed within less than 10 iterations, even for oddities like cosmics double diff = 1.; // Iterate to obtain first moments while (iter < iterMax && diff > eps) { double xwsum = 0.; double ywsum = 0.; double wsum = 0.; double XWIN0 = XWIN; double YWIN0 = YWIN; long i=0; for (auto &pixel : pixelsWin_flux) { double rsq = pow((pixelsWin_x.at(i) - XWIN0),2.) + pow((pixelsWin_y.at(i) - YWIN0),2.); if (rsq < rmaxsq) { double w = exp(-rsq / (2.*dsq)); xwsum += w*pixel*(pixelsWin_x.at(i)-XWIN0); ywsum += w*pixel*(pixelsWin_y.at(i)-YWIN0); wsum += w*pixel; } ++i; } XWIN = XWIN0 + 2.*xwsum/wsum; // didn't have the prefactor 2, but doesn't seem to make a difference; probably faster conversion like this YWIN = YWIN0 + 2.*xwsum/wsum; diff = sqrt( pow(XWIN-XWIN0,2) + pow(YWIN-YWIN0,2)); ++iter; } if (XWIN < 0. || XWIN > naxis1 || YWIN < 0. || YWIN > naxis2) { bitflags.setBit(7,true); badDetection = true; return; } // Second moments double xxwsum = 0.; double yywsum = 0.; double xywsum = 0.; double wsum = 0.; long i=0; for (auto &pixel : pixelsWin_flux) { double px = pixelsWin_x.at(i); double py = pixelsWin_y.at(i); double rsq = pow((px - XWIN),2.) + pow((py - YWIN),2.); if (rsq < rmaxsq) { double w = exp(-rsq / (2.*dsq)); xxwsum += w*pixel*(px-XWIN)*(px-XWIN); yywsum += w*pixel*(py-YWIN)*(py-YWIN); xywsum += w*pixel*(px-XWIN)*(py-YWIN); wsum += w*pixel; } ++i; } X2WIN = xxwsum / wsum; Y2WIN = yywsum / wsum; XYWIN = xywsum / wsum; } void DetectedObject::calcMomentsErrors() { if (badDetection) return; double xsum = 0.; double ysum = 0.; double xysum = 0.; double psum = 0.; for (long i=0; i10.) return; // Windowed parameters useful for small objects, only double dsq = 4.*FLUX_RADIUS*FLUX_RADIUS / (8.*log(2.)); double rmaxsq = 4.*FLUX_RADIUS*FLUX_RADIUS; double xwsum = 0.; double ywsum = 0.; double xywsum = 0.; double wsum = 0.; long i=0; for (auto &pixel : pixelsWin_flux) { double px = pixelsWin_x.at(i); double py = pixelsWin_y.at(i); double rsq = pow((px - XWIN),2.) + pow((py - YWIN),2.); double sisq = sigma_back*sigma_back + pixel / gain; // I think this is wrong, should divide sigma_back by gain, too! if (rsq < rmaxsq) { double w = exp(-rsq / (2.*dsq)); xwsum += w*w*sisq*(px-XWIN)*(px-XWIN); ywsum += w*w*sisq*(py-YWIN)*(py-YWIN); xywsum += w*w*sisq*(px-XWIN)*(py-YWIN); wsum += w*w*pixel*pixel; } ++i; } if (wsum > 0.) { ERRX2WIN = 4.*xwsum/wsum; ERRY2WIN = 4.*ywsum/wsum; ERRXYWIN = 4.*xywsum/wsum; ERRAWIN = 0.5*(ERRX2WIN+ERRY2WIN) + sqrt( 0.25*(ERRX2WIN-ERRY2WIN)*(ERRX2WIN-ERRY2WIN) + ERRXYWIN*ERRXYWIN); ERRBWIN = 0.5*(ERRX2WIN+ERRY2WIN) - sqrt( 0.25*(ERRX2WIN-ERRY2WIN)*(ERRX2WIN-ERRY2WIN) + ERRXYWIN*ERRXYWIN); ERRAWIN = sqrt(ERRAWIN); ERRBWIN = sqrt(ERRBWIN); ERRTHETAWIN = 2.*ERRXYWIN / (ERRX2WIN-ERRY2WIN); ERRTHETAWIN = fabs(0.5*atan(ERRTHETAWIN)/rad); } else { ERRX2WIN = 0.; ERRY2WIN = 0.; ERRXYWIN = 0.; ERRAWIN = 0.; ERRBWIN = 0.; ERRTHETAWIN = 0.; bitflags.setBit(7,true); badDetection = true; } // noise floor if (ERRTHETAWIN < 0.01) ERRTHETAWIN = 0.01; } void DetectedObject::calcSkyCoords() { if (badDetection) return; double world[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; // CAREFUL! wcslib starts pixels counting at 1, hence must add +1 to zero-indexed C++ vectors pixcrd[0] = XWIN + 1.; pixcrd[1] = YWIN + 1.; int stat[1]; wcsp2s(&wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world, stat); ALPHA_J2000 = world[0]; DELTA_J2000 = world[1]; } void DetectedObject::calcEllipticity() { // if (badDetection) return; if (XY == 0. || X2 == Y2) THETA = 0.; else { THETA = atan(2.*XY / (X2-Y2)) / 2. / rad; // THETA should have the same sign as XY if ( (THETA<0 && XY>0) || (THETA>0 && XY<0)) THETA *= -1.; } double s1 = (X2+Y2) / 2.; double s2 = sqrt((X2-Y2) * (X2-Y2) / 4. + XY*XY); if (s10) || (THETAWIN>0 && XYWIN<0)) THETAWIN *= -1.; } double s1 = (X2WIN+Y2WIN) / 2.; double s2 = sqrt((X2WIN-Y2WIN) * (X2WIN-Y2WIN) / 4. + XYWIN*XYWIN); if (s1100 || YMAX-YMIN > 100) { // don't calculate flux radius for very large objects (algorithm is very inefficient) FLUX_RADIUS = sqrt((XMAX-XMIN)*(XMAX-XMIN) + (YMAX-YMIN)*(YMAX-YMIN)); return; } else s = 1; long nn = (XMAX-XMIN+1) * s; long mm = (YMAX-YMIN+1) * s; QVector dataSub(nn*mm, 0); // Subsample the original pixel data. The window is the minimum rectangular envelope for (long k=0; k=nn || jj<0 || jj>=mm) continue; fluxInt += dataSub[ii+nn*jj]; dataSub[ii+nn*jj] = 0.; // making sure we don't count a pixel twice } } } flux_current = fluxInt; FLUX_RADIUS = step; ++step; } FLUX_RADIUS /= double(s); // Interpolate 0.1 pixel step size double intp = (0.5-flux_previous) / (flux_current - 0.5) / s; FLUX_RADIUS += intp; } void DetectedObject::calcFWHM() { // FWHM = 1.995*FLUX_RADIUS; // For a theoretical 2D gaussian FWHM = 2.355*sqrt(XVAR+YVAR); } void DetectedObject::getWindowedPixels() { if (badDetection) return; long xminWin = floor(X-2.*FLUX_RADIUS); long xmaxWin = ceil(X+2.*FLUX_RADIUS); long yminWin = floor(Y-2.*FLUX_RADIUS); long ymaxWin = ceil(Y+2.*FLUX_RADIUS); // Check truncation by image frame if (isTruncated(xminWin, xmaxWin, yminWin, ymaxWin)) bitflags.setBit(4,true); // Truncate if necessary xminWin = xminWin < 0 ? 0 : xminWin; xmaxWin = xmaxWin >=naxis1 ? naxis1-1 : xmaxWin; yminWin = yminWin < 0 ? 0 : yminWin; ymaxWin = ymaxWin >=naxis2 ? naxis2-1 : ymaxWin; long npixWin = (xmaxWin-xminWin+1) * (ymaxWin-yminWin+1); pixelsWin_flux.reserve(npixWin); pixelsWin_x.reserve(npixWin); pixelsWin_y.reserve(npixWin); for (long j=yminWin; j<=ymaxWin; ++j) { double jj = double(j); for (long i=xminWin; i<=xmaxWin; ++i) { double ii = double(i); double rsq = (X-ii)*(X-ii) + (Y-jj)*(Y-jj); if (rsq <= 4.*FLUX_RADIUS*FLUX_RADIUS) { if (weightInMemory && dataWeight.at(i+naxis1*j) == 0.) { bitflags.setBit(6,true); continue; } pixelsWin_flux.append(dataMeasure.at(i+naxis1*j)); pixelsWin_x.append(i); pixelsWin_y.append(j); } } } } bool DetectedObject::isTruncated(const long xmin, const long xmax, const long ymin, const long ymax) { bool truncation = false; if (xmin < 0) truncation = true; if (ymin < 0) truncation = true; if (xmax >= naxis1) truncation = true; if (ymax >= naxis2) truncation = true; return truncation; } void DetectedObject::calcMagAuto() { if (badDetection) return; // TODO: check that this parameterisation actually encompasses 6 times the best fit isophote long imin = floor(X - 6.*A); long imax = ceil(X + 6.*A); long jmin = floor(Y - 6.*A); long jmax = ceil(Y + 6.*A); imin = imin < 0 ? 0 : imin; imax = imax >=naxis1 ? naxis1-1 : imax; jmin = jmin < 0 ? 0 : jmin; jmax = jmax >=naxis2 ? naxis2-1 : jmax; // Loop over the rectangular subset of pixels that encompass the object double rkron = 0.; double fsum = 0.; for (long j=jmin; j<=jmax; ++j) { float dy = j - Y; for (long i=imin; i<=imax; ++i) { float dx = i - X; // Work on pixels within 6x the ellipse double rsq = CXX*dx*dx + CYY*dy*dy + CXY*dx*dy; if (rsq <= 36.*A*A) { rkron += sqrt(rsq) * dataMeasure.at(i+naxis1*j); fsum += dataMeasure.at(i+naxis1*j); } } } /* debugging // objects close to the detection limit may not fulfil the "rsq <= 36.*A*A" requirement if (fsum == 0.) { for (long j=jmin; j<=jmax; ++j) { float dy = j - Y; for (long i=imin; i<=imax; ++i) { float dx = i - X; double rsq = CXX*dx*dx + CYY*dy*dy + CXY*dx*dy; qDebug() << i << j << dx << dy << CXX << CYY << CXY << rsq << 36.*A*A << dataMeasure.at(i+naxis1*j); } } } */ if (fsum == 0.) rkron = 3.5; else rkron /= fsum; // enforce a minimum radius of 3.5 pixels for noisy objects rkron = rkron < 3.5 ? 3.5 : rkron; double auto_radius = 2.5*rkron; imin = floor(X - auto_radius); imax = ceil(X + auto_radius); jmin = floor(Y - auto_radius); jmax = ceil(Y + auto_radius); imin = imin < 0 ? 0 : int(imin); imax = imax >=naxis1 ? naxis1-1 : int(imax); jmin = jmin < 0 ? 0 : int(jmin); jmax = jmax >=naxis2 ? naxis2-1 : int(jmax); if (isTruncated(imin, imax, jmin, jmax)) bitflags.setBit(3,true); FLUX_AUTO = 0; FLUXERR_AUTO = 0; float numMasked = 0.; float numTot = 0.; for (long j=jmin; j<=jmax; ++j) { float dy = Y - j; for (long i=imin; i<=imax; ++i) { float dx = X - i; // Work on pixels within auto_radius if (dx*dx + dy*dy < auto_radius*auto_radius) { if (weightInMemory && dataWeight.at(i+naxis1*j) == 0.) bitflags.setBit(6,true); // With global mask if (globalMaskAvailable) { if (!mask.at(i+naxis1*j)) { FLUX_AUTO += dataMeasure.at(i+naxis1*j); FLUXERR_AUTO += dataBackground.at(i+naxis1*j)/gain + dataMeasure.at(i+naxis1*j)/gain; // neglecting readout noise } else { ++numMasked; } } // without global mask else { FLUX_AUTO += dataMeasure.at(i+naxis1*j); FLUXERR_AUTO += dataBackground.at(i+naxis1*j)/gain + dataMeasure.at(i+naxis1*j)/gain; // neglecting readout noise } ++numTot; } } } if (FLUX_AUTO < 0.) { bitflags.setBit(7,true); badDetection = true; MAGERR_AUTO = 99.; MAG_AUTO = 99.; FLUXERR_AUTO = 0.; } else { FLUXERR_AUTO = sqrt(FLUXERR_AUTO); MAG_AUTO = -2.5*log10(FLUX_AUTO) + ZP; MAGERR_AUTO = 2.5*log10(1.+FLUXERR_AUTO/FLUX_AUTO); } if (numMasked / numTot > 0.1) bitflags.setBit(1,true); } void DetectedObject::filterSpuriousDetections() { if (std::isnan(XWIN) || std::isnan(YWIN) || std::isnan(AWIN) || std::isnan(BWIN) || std::isnan(ERRAWIN) || std::isnan(ERRBWIN) || std::isnan(ERRTHETAWIN) || std::isnan(FLUX_RADIUS) || XWIN < 1. || YWIN < 1. || XWIN > naxis1-1 || YWIN > naxis2-1 || (AWIN==0 && BWIN==0)) { bitflags.setBit(7,true); badDetection = true; } FLAGS = 0; for (int i=0; i #include #include #include "wcs.h" class DetectedObject : public QObject { Q_OBJECT void calcFlux(); void calcMoments(); void calcMomentsErrors(); void calcVariance(); void calcEllipticity(); void calcFluxRadius(); void calcWindowedMoments(); void calcWindowedMomentsErrors(); void calcMagAuto(); void getWindowedPixels(); void calcSkyCoords(); void calcWindowedEllipticity(); void filterSpuriousDetections(); QVector calcFluxAper(float aperture); void calcApertureMagnitudes(); void correctOriginOffset(); void calcFWHM(); bool isTruncated(const long xmin, const long xmax, const long ymin, const long ymax); public: explicit DetectedObject(const QList &objectIndices, const QVector &data, const QVector &background, const QVector &weight, const QVector &mask, bool weightinmemory, const long naxis1, const long naxis2, const long objid, const float satVal, const float gainval, wcsprm &wcsImage, QObject *parent = nullptr); ~DetectedObject(); const QVector &dataMeasure; const QVector &dataBackground; const QVector &dataWeight; const QVector &mask; bool badDetection = false; // set if anything goes wrong with an object parameter's calculation bool globalMaskAvailable = true; // the default for internal processing (but not for external images, e.g. abs zeropoint) bool weightInMemory = true; wcsprm &wcs; // Moments and shapes // Using Source Extractor naming style for easier recognition // ISOPHOTAL long XMIN = 0; // min and max positions (used in calculations) long XMAX = 0; long YMIN = 0; long YMAX = 0; double X = 0.; // 1st moment // WARNING: zero-indexing, must add +1 if used externally double Y = 0.; // 1st moment // WARNING: zero-indexing, must add +1 if used externally double X2 = 0.; // 2nd moment double Y2 = 0.; // 2nd moment double XY = 0.; // 2nd moment double X2Y2 = 0.; // helper variable double A = 0; // major axis double B = 0; // minor axis double THETA = 0.; // position angle double CXX = 0; // cartesian ellipticity parameterization double CYY = 0.; // cartesian ellipticity parameterization double CXY = 0.; // cartesian ellipticity parameterization double XERR = 0.; double YERR = 0.; double ERRX2 = 0.; double ERRY2 = 0; double ERRXY = 0.; double ERRA = 0.; double ERRB = 0.; double ERRTHETA = 0.; double MAG_ISO = 0.; double FLUX_ISO = 0.; double XVAR = 0.; double YVAR = 0.; // WINDOWED double XWIN = 0.; // windowed 1st moment // WARNING: zero-indexing, must add +1 if used externally double YWIN = 0.; // windowed 1st moment // WARNING: zero-indexing, must add +1 if used externally double X2WIN = 0.; double Y2WIN = 0.; double XYWIN = 0.; double AWIN = 0.; double BWIN = 0.; double THETAWIN = 0.; double CXXWIN = 0; double CYYWIN = 0.; double CXYWIN = 0.; double ERRX2WIN = 0.; double ERRY2WIN = 0.; double ERRXYWIN = 0.; double ERRAWIN = 0.; double ERRBWIN = 0.; double ERRTHETAWIN = 0.; double XWINERR = 0.; double YWINERR = 0.; double MAG_AUTO = 0.; double MAGERR_AUTO = 0.; double FLUX_AUTO = 0.; double FLUXERR_AUTO = 0.; double FLUX_RADIUS = 0.; double FWHM = 0.; double ELLIPTICITY = 0.; // APERTURE QVector FLUX_APER; QVector MAG_APER; QVector FLUXERR_APER; QVector MAGERR_APER; float saturationValue = 1.e9; double sigmai = 0.; double sigmab = 0.; double ZP = 0; double ALPHA_J2000 = 0.; double DELTA_J2000 = 0.; double gain = 1.0; double sigma_back = 0.; double crval1 = 0.; double crval2 = 0.; long objID = 0; long area = 0; int FLAGS = 0; bool aperFlagSetAlready = false; QBitArray bitflags; QVector pixels_x; QVector pixels_y; QVector pixels_flux; QVector pixels_back; QVector pixels_weight; QVector pixelsWin_x; QVector pixelsWin_y; QVector pixelsWin_flux; QVector pixelsWin_back; QVector pixelsWin_weight; QVector apertures; QVector pixelsAper_x; QVector pixelsAper_y; QVector pixelsAper_flux; QVector pixelsAper_back; QVector pixelsAper_weight; long naxis1 = 0; // image geometry, needed to respect boundaries long naxis2 = 0; double rad = 3.14159265/180.; void computeObjectParams(); void remove(); signals: public slots: }; #endif // DETECTEDOBJECT_H THELI-3.1.3/src/tools/fileprogresscounter.cc000066400000000000000000000035561417631501300207370ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "fileprogresscounter.h" #include #include #include FileProgressCounter::FileProgressCounter(QString dirname, QString filter, int numtotimages, float *progressDep, QObject *parent) : QObject(parent) { dir.setPath(dirname); filterList << filter; numTotImages = numtotimages; timer = new QTimer(this); progress = progressDep; } FileProgressCounter::FileProgressCounter(QString dirname, long finalsize, float *progressDep, QObject *parent) : QObject(parent) { dirName = dirname; timer = new QTimer(this); finalSize = finalsize; progress = progressDep; } void FileProgressCounter::numberFileProgress() { int numImages = dir.entryList(filterList).length(); *progress = 100. * float(numImages) / float(numTotImages); // emit progressUpdate(progress); } void FileProgressCounter::sizeFileProgress() { fi.setFile(dirName+"/coadd.fits"); long currentSize = fi.size(); *progress = 100. * float(currentSize) / float(finalSize); // emit progressUpdate(progress); } void FileProgressCounter::stopFileProgressTimerReceived() { timer->stop(); } THELI-3.1.3/src/tools/fileprogresscounter.h000066400000000000000000000030061417631501300205670ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef FILEPROGRESSCOUNTER_H #define FILEPROGRESSCOUNTER_H #include #include #include #include class FileProgressCounter : public QObject { Q_OBJECT public: explicit FileProgressCounter(QString dirname, QString filter, int numtotimages, float *progressDep, QObject *parent = nullptr); explicit FileProgressCounter(QString dirname, long finalsize, float *progressDep, QObject *parent = nullptr); QDir dir; QString dirName; QStringList filterList; int numTotImages = 0; QTimer *timer = nullptr; QFileInfo fi; long finalSize = 0; float *progress; signals: void progressUpdate(float progress); public slots: void numberFileProgress(); void sizeFileProgress(); void stopFileProgressTimerReceived(); }; #endif // FILEPROGRESSCOUNTER_H THELI-3.1.3/src/tools/fitgauss1d.cc000066400000000000000000000107651417631501300167050ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "fitgauss1d.h" #include #include #include #include #include #include #include #include // A Levenberg-Markquardt solver with geodesic acceleration, see e.g. // https://www.gnu.org/software/gsl/doc/html/nls.html#examples // WARNING: for some reason this does not work. It returns the initial values, only! // UNUSED, kept for reference // model function: a * exp( -1/2 * [ (t - b) / c ]^2 ) double gaussian(const double a, const double b, const double c, const double t) { const double z = (t - b) / c; return (a * exp(-0.5 * z * z)); } int func_f (const gsl_vector *x, void *params, gsl_vector *f) { // long n = ((struct fitData *)params)->n; double *xdata = ((struct fitData *)params)->t; double *ydata = ((struct fitData *)params)->y; struct fitData *d = (struct fitData*) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); for (long i=0; in; ++i) { double ti = xdata[i]; double yi = ydata[i]; double y = gaussian(a, b, c, ti); gsl_vector_set(f, i, yi - y); } return GSL_SUCCESS; } int func_df (const gsl_vector *x, void *params, gsl_matrix *J) { struct fitData *d = (struct fitData*) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); for (long i=0; in; ++i) { double ti = d->t[i]; double zi = (ti - b) / c; double ei = exp(-0.5 * zi * zi); gsl_matrix_set(J, i, 0, -ei); gsl_matrix_set(J, i, 1, -(a / c) * ei * zi); gsl_matrix_set(J, i, 2, -(a / c) * ei * zi * zi); } return GSL_SUCCESS; } int func_fvv (const gsl_vector *x, const gsl_vector *v, void *params, gsl_vector *fvv) { struct fitData *d = (struct fitData*) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); double va = gsl_vector_get(v, 0); double vb = gsl_vector_get(v, 1); double vc = gsl_vector_get(v, 2); for (long i=0; in; ++i) { double ti = d->t[i]; double zi = (ti - b) / c; double ei = exp(-0.5 * zi * zi); double Dab = -zi * ei / c; double Dac = -zi * zi * ei / c; double Dbb = a * ei / (c * c) * (1.0 - zi*zi); double Dbc = a * zi * ei / (c * c) * (2.0 - zi*zi); double Dcc = a * zi * zi * ei / (c * c) * (3.0 - zi*zi); double sum; sum = 2.0 * va * vb * Dab + 2.0 * va * vc * Dac + vb * vb * Dbb + 2.0 * vb * vc * Dbc + vc * vc * Dcc; gsl_vector_set(fvv, i, sum); } return GSL_SUCCESS; } void solve_system(gsl_vector *x, gsl_multifit_nlinear_fdf *fdf, gsl_multifit_nlinear_parameters *params) { const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust; const size_t max_iter = 200; const double xtol = 1.0e-8; const double gtol = 1.0e-8; const double ftol = 1.0e-8; const size_t n = fdf->n; const size_t p = fdf->p; gsl_multifit_nlinear_workspace *work = gsl_multifit_nlinear_alloc(T, params, n, p); gsl_vector * f = gsl_multifit_nlinear_residual(work); gsl_vector * y = gsl_multifit_nlinear_position(work); int info; double chisq0, chisq, rcond; // initialize solver gsl_multifit_nlinear_init(x, fdf, work); // store initial cost gsl_blas_ddot(f, f, &chisq0); // iterate until convergence gsl_multifit_nlinear_driver(max_iter, xtol, gtol, ftol, NULL, NULL, &info, work); // store final cost gsl_blas_ddot(f, f, &chisq); // store cond(J(x)) gsl_multifit_nlinear_rcond(&rcond, work); gsl_vector_memcpy(x, y); gsl_multifit_nlinear_free(work); } THELI-3.1.3/src/tools/fitgauss1d.h000066400000000000000000000066061417631501300165460ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef FITGAUSS1D_H #define FITGAUSS1D_H #include #include #include #include #include #include #include #include struct fitData { double *t; double *y; long n; }; double gaussian(const double a, const double b, const double c, const double t); int func_f(const gsl_vector *x, void *params, gsl_vector *f); int func_df(const gsl_vector *x, void *params, gsl_matrix *J); int func_fvv(const gsl_vector *x, const gsl_vector *v, void *params, gsl_vector *fvv); void solve_system(gsl_vector *x, gsl_multifit_nlinear_fdf *fdf, gsl_multifit_nlinear_parameters *params); template QVector fitGauss1D(const QVector dataY, double amp0, double mean0, double sigma0, const QVector dataX = QVector()) { long n = dataY.length(); int p = 3; // number of parameters for the 1D Gaussian // The arrays holding the data (GSL doesn't know anything about vectors) double *xarr = new double[n]; double *yarr = new double[n]; // Copy the data for (long i=0; i result; // contains amplitude, mean, sigma solve_system(x, &fdf, &fdf_params); result << gsl_vector_get(x, 0) << gsl_vector_get(x, 1) << gsl_vector_get(x, 2); // debug: print data and model /* double A = gsl_vector_get(x, 0); double B = gsl_vector_get(x, 1); double C = gsl_vector_get(x, 2); for (size_t i=0; i #include #include #include #include #include #include #include #include #include Fitting::Fitting() { } Fitting::~Fitting() { } // 2D surface fit using polynomial of arbitrary degree // Weights are optional void Fitting::makePolynomialFit2D(const int order, const QVector x_in, const QVector y_in, const QVector z_in, QVector w_in) { if (!FITSUCCESS) return; long lx = x_in.length(); long ly = y_in.length(); long lz = y_in.length(); long lw = w_in.length(); if (lx != ly || lx != lz || ( lx != lw && lw > 0)) { emit messageAvailable("Fitting::makePolynomialFit2D(): Inconsistent size of input arrays:" + QString::number(lx) + " " + QString::number(ly) + " " + QString::number(lz) + " " + QString::number(lw), "error"); emit critical(); FITSUCCESS = false; return; } // Number of measurement positions long N = lx; // weights (optional) if (w_in.isEmpty()) w_in.fill(1.0, N); // Number of free parameters int P = 2*order + 1; if (N < P) { emit messageAvailable("Fitting::makePolynomialFit2D(): Insufficient number of data points (" + QString::number(N) + ") to do a fit of degree " +QString::number(order), "error"); emit critical(); FITSUCCESS = false; return; } // we don't use cross-terms // Linear combinations of various functions // order == 1: // z = p0 + p1 x + p2 y // order == 2: // z = p0 + p1 x + p2 x^2 + p3 y + p3 y^2 // etc ... gsl_vector *y; // observed data () gsl_vector *w; // data weights gsl_matrix *X; // data used to predict: x, y // allocate space for the matrices and vectors X = gsl_matrix_alloc(N, P); // this is an input y = gsl_vector_alloc(N); // this is an input w = gsl_vector_alloc(N); // this is an input c = gsl_vector_alloc(P); // this is an output cov = gsl_matrix_alloc(P, P); // this is an output // Put the data into the X matrix, row by row int ii = 0; for (int i=0; i> nodes) { long numNodes = nodes.length(); QVector x_in; QVector y_in; QVector z_in; x_in.reserve(numNodes); y_in.reserve(numNodes); z_in.reserve(numNodes); for (auto &it : nodes) { x_in.append(it[0]); y_in.append(it[1]); z_in.append(it[2]); } makePolynomialFit2D(order, x_in, y_in, z_in); } THELI-3.1.3/src/tools/fitting.h000066400000000000000000000030731417631501300161330ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef FITTING_H #define FITTING_H #include "../functions.h" #include #include #include #include #include #include #include #include class Fitting : public QObject { Q_OBJECT public: Fitting(); ~Fitting(); bool FITSUCCESS = true; void makePolynomialFit2D(const int order, QList> nodes); void makePolynomialFit2D(const int order, const QVector x_in, const QVector y_in, const QVector z_in, QVector w_in = QVector()); gsl_vector *c = nullptr; // e.g. for polynomial coefficients (fit result) gsl_matrix *cov = nullptr; signals: void messageAvailable(QString message, QString type); void critical(); void warning(); }; #endif // FITTING_H THELI-3.1.3/src/tools/imagequality.cc000066400000000000000000000056051417631501300173230ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagequality.h" #include "../myimage/myimage.h" #include "../instrumentdata.h" #include "../processingInternal/data.h" #include "../tools/tools.h" #include "../functions.h" #include #include #include ImageQuality::ImageQuality(const instrumentDataType *instrumentData, QString maindirname, QObject *parent) : QObject(parent), instData(instrumentData) { // instData = instrumentData; mainDirName = maindirname; } void ImageQuality::displayMessageReceived(QString message, QString type) { emit messageAvailable(message, type); } void ImageQuality::criticalReceived() { emit critical(); } bool ImageQuality::getSeeingFromGaia() { // Match GAIA point sources with detections in the image // refCat and sourceCat are populated externally in Controller::doImageQualityAnalysis() int dummy1; int dummy2; QVector> matchedCat; int maxCPU = 1; // external parallelization match2D(sourceCat, refCat, matchedCat, matchingTolerance, dummy1, dummy2, maxCPU); if (matchedCat.isEmpty()) { emit messageAvailable(baseName + " : No usable reference point sources identified for IQ analysis.", "warning"); // emit messageAvailable(baseName + " : No usable reference point sources identified for IQ analysis. Using rh-mag method ...", "warning"); fwhm = -1.0; ellipticity = -1.0; numSources = 0; return false; } emit messageAvailable(baseName + " : Matched "+QString::number(matchedCat.length()) + " sources identified for IQ analysis.", "image"); QVector fwhmVec; QVector ellipticityVec; fwhmVec.reserve(matchedCat.length()); ellipticityVec.reserve(matchedCat.length()); for (auto &source : matchedCat) { fwhmVec << source[3]; // matched vector contains: RA, DEC, MAG, FWHM, ELL ellipticityVec << source[4]; } // fwhm = meanMask_T(fwhmVec, QVector()) * instData->pixscale; // ellipticity = meanMask_T(ellipticityVec, QVector()); fwhm = straightMedian_T(fwhmVec); ellipticity = straightMedian_T(ellipticityVec); numSources = fwhmVec.length(); return true; } bool ImageQuality::getSeeingFromRhMag() { return true; } THELI-3.1.3/src/tools/imagequality.h000066400000000000000000000033761417631501300171700ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IMAGEQUALITY_H #define IMAGEQUALITY_H #include "../query/query.h" #include "../processingInternal/data.h" #include "../instrumentdata.h" #include class ImageQuality : public QObject { Q_OBJECT public: explicit ImageQuality(const instrumentDataType *instrumentData, QString maindirname, QObject *parent = nullptr); bool getSeeingFromGaia(); bool getSeeingFromRhMag(); double matchingTolerance = 1./3600; // 1.0 arcsec starting value QString baseName; double fwhm = -1.0; // in pixel double ellipticity = -1.0; long numSources = 0; QVector source; QVector> sourceCat; QVector> refCat; QVector sourceMag; QVector refRA; QVector refDEC; private: const instrumentDataType *instData; QString mainDirName; signals: void messageAvailable(QString message, QString type); void critical(); public slots: private slots: void displayMessageReceived(QString message, QString type); void criticalReceived(); }; #endif // IMAGEQUALITY_H THELI-3.1.3/src/tools/polygon.cc000066400000000000000000000263551417631501300163240ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "polygon.h" #include #include #include #include #include // Split a ds9 region POLYGON string into x- and y vertice arrays void polygon2vertices(QString polystring, QVector &vertx, QVector &verty) { // extract vertices polystring = polystring.split("(")[1].remove(")").simplified(); // split the polygon string into its vertices QStringList list = polystring.split(','); // number of vertices // int nvert = (polystring.count(',') + 1) / 2; // populate for (int i=0; i &vertx, const QVector &verty, const QString senseMode, QVector &mask) { float x, y; // apply the polygon mask // NOT THREADSAFE! // #pragma omp parallel for firstprivate(vertx, verty, senseMode) for (long j=0; j &vertx, const QVector &verty, const QString senseMode, QVector &mask) { // apply the polygon mask // NOT THREADSAFE! // #pragma omp parallel for firstprivate(vertx, verty, senseMode) for (long j=0; j &vertx, const QVector &verty, QString senseMode, QVector &weight) { // apply the polygon mask // NOT THREADSAFE //#pragma omp parallel for for (long j=0; j 0 if (weight[i+n*j] > 0.) { // test if the pixel is inside or outside the polygon bool polytest = pnpoly_T(vertx, verty, x, y); // Mask pixels inside or outside the polygon if (senseMode == "in") { // Pixels inside the polygon are bad // pnpoly() returns 0 if a pixel is outside the polygon if (polytest == 1) weight[i+n*j] = 0.; } else { if (polytest == 0) weight[i+n*j] = 0; } } } } } void addCircle_bool(const long n, const long m, float x, float y, float r, QString senseMode, QVector &mask) { // NOT THREADSAFE // #pragma omp parallel for for (long j=0; j= r*r) mask[i+n*j] = true; } else { // mask pixels inside the circle if (d <= r*r) mask[i+n*j] = true; } } } } } void addCircle_float(const long n, const long m, float x, float y, float r, QString senseMode, QVector &weight) { // NOT THREADSAFE // #pragma omp parallel for for (long j=0; j 0 if (weight[i+n*j] > 0.) { // Mask pixels inside or outside the circle float d = (ii-x) * (ii-x) + (jj-y) * (jj-y); if (senseMode == "in") { // mask pixels inside the circle if (d <= r*r) weight[i+n*j] = 0.; } else { // mask pixels inside the circle if (d >= r*r) weight[i+n*j] = 0.; } } } } } void addRegionFilesToMask(const long n, const long m, QString regionFile, QVector &mask, bool &isChipMasked) { QFile file(regionFile); if (!file.exists()) return; if ( !file.open(QIODevice::ReadOnly)) { qDebug() << "polygon::addRegionFilesToWeight: could not open "+regionFile; return; } isChipMasked = false; QString senseMode = "in"; QString combineMode = "or"; // not used QTextStream in(&(file)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty()) continue; if (line.contains("# Sense: ")) { senseMode = line.split(":")[1].simplified(); if (senseMode == "in") mask.fill(true); // default, everything masked. Only keep pixels inside polygons and circles else mask.fill(false); // default, everything unmasked. Only keep pixels inside polygons and circles } // if (line.contains("# Combine: ")) combineMode = line.split(":")[1].simplified(); // There can be an arbitrary sequence of polygons and circles // The masks will be combined in the sense that a pixel will be masked if it is masked at least once. // Mask a polygon if (line.contains("polygon(") || line.contains("POLYGON(")) { QVector vertx; QVector verty; polygon2vertices(line, vertx, verty); addPolygon_bool(n, m, vertx, verty, senseMode, mask); isChipMasked = true; } // Mask a circle if (line.contains("circle(") || line.contains("CIRCLE(")) { float x = 0.; float y = 0.; float r = 0.; region2circle(line, x, y, r); addCircle_bool(n, m, x, y, r, senseMode, mask); isChipMasked = true; } } file.close(); } void addRegionFilesToWeight(const long n, const long m, QString regionFile, QVector &weight) { QFile file(regionFile); if (!file.exists()) return; if ( !file.open(QIODevice::ReadOnly)) { qDebug() << "QDEBUG: polygon::addRegionFilesToWeight: could not open "+regionFile; return; } QString senseMode = "in"; QString combineMode = "or"; // not used QTextStream in(&(file)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty()) continue; if (line.contains("# Sense: ")) senseMode = line.split(":")[1].simplified(); // if (line.contains("# Combine: ")) combineMode = line.split(":")[1].simplified(); // There can be an arbitrary sequence of polygons and circles // The masks will be combined in the sense that a pixel will be masked if it is masked at least once. // Mask a polygon if (line.contains("polygon(") || line.contains("POLYGON(")) { QVector vertx; QVector verty; polygon2vertices(line, vertx, verty); addPolygon_float(n, m, vertx, verty, senseMode, weight); } // Mask a circle if (line.contains("circle(") || line.contains("CIRCLE(")) { float x = 0.; float y = 0.; float r = 0.; region2circle(line, x, y, r); addCircle_float(n, m, x, y, r, senseMode, weight); } } file.close(); } THELI-3.1.3/src/tools/polygon.h000066400000000000000000000067031417631501300161610ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef POLYGON_H #define POLYGON_H #include void polygon2vertices(QString polystring, QVector &vertx, QVector &verty); void addCircle_bool(const long n, const long m, float x, float y, float r, QString senseMode, QVector &mask); void addPolygon_bool(const long n, const long m, const QVector &vertx, const QVector &verty, const QString senseMode, QVector &mask); void addPolygon_float(const long n, const long m, const QVector &vertx, const QVector &verty, QString senseMode, QVector &weight); void addRegionFilesToMask(const long n, const long m, QString regionFile, QVector &mask, bool &isChipMasked); void addRegionFilesToWeight(const long n, const long m, QString regionFile, QVector &mask); void region2circle(QString circlestring, float &x, float &y, float &r); /* Polygon tester (pnpoly), implemented in pnpoly_T() below Copyright (c) 1970-2003, Wm. Randolph Franklin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers. (2) Redistributions in binary form must reproduce the above copyright notice in the documentation and/or other materials provided with the distribution. (3) The name of W. Randolph Franklin may not be used to endorse or promote products derived from this Software without specific prior written permission. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ template bool pnpoly_T(const QVector &vertx, const QVector &verty, const T testx, const T testy) { long i, j; long nvert = vertx.length(); bool c = false; for (i=0, j=nvert-1; itesty) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; } return c; // false if point is outside polygon, true if inside, true or false if exactly on the connecting line } #endif // POLYGON_H THELI-3.1.3/src/tools/ram.cc000066400000000000000000000070621417631501300154060ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ram.h" #include #include #include #include #include #include #include #include #include #include #ifdef __MACH__ #include #define MACOS #elif __LINUX__ #define LINUX #endif RAM::RAM(QObject *parent) : QObject(parent) { file.setFileName("/proc/meminfo"); if ( !file.open(QIODevice::ReadOnly)) { RAMbarDeactivated = true; return; } instream.setDevice(&file); QSysInfo *sysInfo = new QSysInfo; kernelType = sysInfo->kernelType(); delete sysInfo; sysInfo = nullptr; } RAM::~RAM() { file.close(); } long RAM::getRAMload() { if (RAMbarDeactivated) return 0; if (kernelType == "linux") { readStatsRAM_Linux(); } else if (kernelType == "darwin") { readStatsRAM_MAC(); } int RAMload = (totalRAM - availableRAM) / 1024; return RAMload; // in [MB] } void RAM::readStatsRAM_Linux() { // Reset file to beginning instream.seek(0); // Files in /proc/ report their size as zero. Hence we can't do "while until EOF", but just read until nothing is read anymore. QString line = instream.readLine().simplified(); while (!line.isNull()) { QStringList values = line.split(" "); if (values[0] == "MemAvailable:") { availableRAM = values[1].toLong(); break; } line = instream.readLine().simplified(); } } void RAM::readStatsRAM_MAC() { unsigned long ulSystem; unsigned long ulUser; unsigned long ulNice; unsigned long ulIdle; getRAMInfo_MAC(&ulSystem, &ulUser, &ulNice, &ulIdle); } float RAM::getCurrentValue() { if (kernelType == "linux") { readStatsRAM_Linux(); } else if (kernelType == "darwin") { readStatsRAM_MAC(); } return (totalRAM - availableRAM) / 1024.; } void RAM::getRAMInfo_MAC(unsigned long *pulSystem, unsigned long *pulUser, unsigned long *pulNice, unsigned long *pulIdle) { #ifdef __MACH__ mach_msg_type_number_t unCpuMsgCount = 0; processor_flavor_t nCpuFlavor = PROCESSOR_CPU_LOAD_INFO; kern_return_t nErr = 0; natural_t unCPUNum = 0; processor_cpu_load_info_t structCpuData; host_t host = mach_host_self(); *pulSystem = 0; *pulUser = 0; *pulNice = 0; *pulIdle = 0; nErr = host_processor_info(host, nCpuFlavor, &unCPUNum, (processor_info_array_t *)&structCpuData, &unCpuMsgCount); if(nErr != KERN_SUCCESS) { qDebug() << "Kernel error: " << mach_error_string(nErr); } else { for(int i=0; i<(int)unCPUNum; ++i) { *pulSystem += structCpuData[i].cpu_ticks[CPU_STATE_SYSTEM]; *pulUser += structCpuData[i].cpu_ticks[CPU_STATE_USER]; *pulNice += structCpuData[i].cpu_ticks[CPU_STATE_NICE]; *pulIdle += structCpuData[i].cpu_ticks[CPU_STATE_IDLE]; } } #endif } THELI-3.1.3/src/tools/ram.h000066400000000000000000000025211417631501300152430ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef RAM_H #define RAM_H #include #include #include #include class RAM : public QObject { Q_OBJECT public: explicit RAM(QObject *parent = nullptr); ~RAM(); long getRAMload(); void getRAMInfo_MAC(unsigned long *pulSystem, unsigned long *pulUser, unsigned long *pulNice, unsigned long *pulIdle); float getCurrentValue(); long totalRAM = 0; signals: private: bool RAMbarDeactivated = false; long availableRAM = 0; void readStatsRAM_Linux(); void readStatsRAM_MAC(); QFile file; QTextStream instream; QString kernelType; // void init(); public slots: }; #endif // RAM_H THELI-3.1.3/src/tools/splitter.cc000066400000000000000000001535711417631501300165040ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../functions.h" #include "../processingInternal/mask.h" #include "../processingInternal/data.h" #include "cfitsioerrorcodes.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "fitsio.h" #include "libraw/libraw.h" #include #include #include #include #include #include Splitter::Splitter(const instrumentDataType &instrumentData, const Mask *detectorMask, const Mask *altDetectorMask, Data *someData, QString datatype, const ConfDockWidget *confDockWidget, QString maindirname, QString subdirname, QString filename, int *verbose, QObject *parent) : QObject(parent), mask(detectorMask), altMask(altDetectorMask), instData(instrumentData), // instData is modified locally during splitting, in the Splitter class only cdw(confDockWidget) { fileName = filename; mainDirName = maindirname; subDirName = subdirname; path = mainDirName + "/" + subDirName; name = path+"/"+fileName; dataType = datatype; QFileInfo fi(name); baseName = fi.completeBaseName(); verbosity = verbose; data = someData; QDir rawdata(path+"/RAWDATA"); rawdata.mkpath(path+"/RAWDATA"); // Bypassing a memory leak in cfitsio QFile file(name); if (!file.exists()) { successProcessing = false; } // The remainder of the processing is called externally from the controller } void Splitter::backupRawFile() { if (!successProcessing) return; moveFile(fileName, path, path+"/RAWDATA/"); } void Splitter::determineFileFormat() { if (!successProcessing) return; alreadyProcessed = false; // Try opening as FITS fits_open_file(&rawFptr, name.toUtf8().data(), READONLY, &rawStatus); // CHECK: xtalk correction only works if we maintain the original detector geometry // correctXtalk(); if (!rawStatus) { dataFormat = "FITS"; // Already processed by THELI? long thelipro = 0; fits_read_key_lng(rawFptr, "THELIPRO", &thelipro, nullptr, &rawStatus); if (rawStatus != KEY_NO_EXIST) { // key exists, this file has been processed by the splitter alreay. Must skip. emit messageAvailable(fileName + " : Already processed, skipped.", "image"); rawStatus = 0; alreadyProcessed = true; return; } else { // Key does not exist, meaning file has not been processed. reset raw status rawStatus = 0; } uncompress(); consistencyChecks(); getDetectorSections(); // Read overscan and data sections for the current instrument; resize accordingly, including gain vector getNumberOfAmplifiers(); } else { // Try opening as RAW dataFormat = "RAW"; int ret = rawProcessor.open_file((path+"/"+fileName).toUtf8().data()); if (ret == LIBRAW_SUCCESS) { // Opened. Try unpacking bool unpack = rawProcessor.unpack(); if (unpack != LIBRAW_SUCCESS) { emit messageAvailable(fileName + " : Could not unpack file: " + libraw_strerror(unpack), "warning"); dataFormat = "UnknownFormat"; return; } getNumberOfAmplifiers(); } else dataFormat = "UnknownFormat"; } if (dataFormat == "UnknownFormat") { // FITS opening error? // printCfitsioError("determineFileFormat()", rawStatus); // successProcessing = false; // Don not trigger an error, just skip the file QDir unknownFile(path+"/UnknownFormat"); unknownFile.mkpath(path+"/UnknownFormat/"); moveFile(fileName, path, path+"/UnknownFormat"); emit messageAvailable("File "+fileName+" : Unknown format. Cfitsio error code: "+QString::number(rawStatus) + ". Moved to "+subDirName+"/UnknownFormat/", "warning"); } } void Splitter::uncompress() { if (!successProcessing) return; // Unpack tile-compressed image and write new fits file to disk if (fits_is_compressed_image(rawFptr, &rawStatus)) { if (*verbosity > 1) emit messageAvailable(baseName + " : Uncompressing ...", "image"); fitsfile *outRawPtr; int outRawStatus = 0; QFileInfo fi(name); QString outName = "!" + path + fi.completeBaseName(); if (!outName.contains(".fits") || !outName.contains(".fit") || !outName.contains(".fts")) outName.append(".fits"); fits_create_file(&outRawPtr, outName.toUtf8().data(), &outRawStatus); fits_img_decompress(rawFptr, outRawPtr, &rawStatus); // delete compressed file if uncompression was successful, create new fits pointer to uncompressed file // CHECK: xtalk correction only works if we maintain the original detector geometry // correctXtalk(); // CHECK : No uncompressed FITS files appear after splitting. Where are they? The raw file does not get removed either. if (!rawStatus && !outRawStatus) { fits_close_file(rawFptr, &rawStatus); //QFile compressedFile(name); //compressedFile.remove(); name = outName; name.remove('!'); QFileInfo fi2(name); baseName = fi2.completeBaseName(); fits_open_file(&rawFptr, name.toUtf8().data(), READONLY, &rawStatus); if (rawStatus) { emit messageAvailable(baseName + " : Could not open uncompressed FITS file!", "error"); printCfitsioError(__func__, rawStatus); } } else { emit messageAvailable(fi.fileName() + " : Uncompression did not work as expected!", "error"); printCfitsioError(__func__, rawStatus); printCfitsioError(__func__, outRawStatus); successProcessing = false; } } } void Splitter::consistencyChecks() { if (!successProcessing) return; // TODO: Determine FITS type (SINGLE, MEF or CUBE) fits_get_num_hdus(rawFptr, &numExt, &rawStatus); if (fitsType == "SINGLE" || fitsType == "MEF") { if (numHDU < instData.numChips) { emit messageAvailable(fileName + " : "+QString::number(numHDU)+" HDUs found, "+QString::number(instData.numChips) +" expected.
File is moved to "+subDirName+"/INCONSISTENT/", "warning"); emit warning(); QDir inconsistentFile(path+"/INCONSISTENT"); inconsistentFile.mkpath(path+"/INCONSISTENT"); moveFile(name, path, path+"/INCONSISTENT"); successProcessing = false; } // equal or more numHDUs than chips is fine (e.g. multi-channel cameras, or multiple readout ports per detector) } printCfitsioError(__func__, rawStatus); } void Splitter::compileNumericKeys() { numericKeyNames.clear(); numericKeyNames.append(headerDictionary.value("CRVAL1")); numericKeyNames.append(headerDictionary.value("CRVAL2")); numericKeyNames.append(headerDictionary.value("CRPIX1")); numericKeyNames.append(headerDictionary.value("CRPIX2")); numericKeyNames.append(headerDictionary.value("EXPTIME")); numericKeyNames.append(headerDictionary.value("CD1_1")); numericKeyNames.append(headerDictionary.value("CD1_2")); numericKeyNames.append(headerDictionary.value("CD2_1")); numericKeyNames.append(headerDictionary.value("CD2_2")); numericKeyNames.append(headerDictionary.value("CDELT1")); numericKeyNames.append(headerDictionary.value("CDELT2")); numericKeyNames.append(headerDictionary.value("AIRMASS")); numericKeyNames.append(headerDictionary.value("EQUINOX")); numericKeyNames.append(headerDictionary.value("MJD-OBS")); numericKeyNames.append(headerDictionary.value("GAIN")); numericKeyNames.append(headerDictionary.value("DATE")); numericKeyNames.append(headerDictionary.value("TIME")); numericKeyNames.append(headerDictionary.value("LST")); } void Splitter::extractImages() { if (!successProcessing) return; if (alreadyProcessed) return; if (dataFormat == "UnknownFormat") return; emit messageAvailable(fileName + " : HDU reformatting, low-level pixel processing ...", "image"); // adjust progress step size for multi-chip cameras whose detectors are stored in single extension FITS files // (i.e. raw data does not come as a MEF but as separate FITS files) QStringList instruments = {"Direct_4k_SWOPE@LCO", "FORS1_E2V_2x2@VLT", "FORS2_E2V_2x2@VLT", "FORS2_MIT_1x1@VLT", "FORS2_MIT_2x2@VLT", "FourStar@LCO", "HSC@SUBARU", "LDSS3_2004-201401@LCO", "LDSS3_from201402@LCO", "IMACS_F2_200404-2008@LCO", "IMACS_F2_2008-today@LCO", "IMACS_F4_200404-2012@LCO", "IMACS_F4_2012-today@LCO", "IMACS_F4_2012-today_2x2@LCO", "MOIRCS_200406-201006@SUBARU", "MOIRCS_201007-201505@SUBARU", "MOIRCS_201512-today@SUBARU", "SPARTAN@SOAR", "SuprimeCam_200101-200104@SUBARU", "SuprimeCam_200105-200807@SUBARU", "SuprimeCam_200808-201705@SUBARU", "SuprimeCam_200808-201705_SDFRED@SUBARU", "VIMOS@VLT"}; // multiple readout channels in different FITS extensions multiChannelMultiExt << "DEIMOS_2AMP@KECK" << "GMOS-N-HAM@GEMINI" << "GMOS-N-HAM_1x1@GEMINI" << "GMOS-S-HAM@GEMINI" << "GMOS-S-HAM_1x1@GEMINI" << "GMOS-S-HAM_4x4@GEMINI" << "LRIS_BLUE@KECK" << "LRIS_RED@KECK" << "MOSAIC-II_16@CTIO" << "MOSAIC-III_4@KPNO_4m" << "PISCO@LCO" << "SAMI_2x2@SOAR" << "SOI@SOAR"; if (multiChannelMultiExt.contains(instData.name)) ampInSeparateExt = true; if (instruments.contains(instData.name)) { progressStepSize *= instData.numChips; } if (dataFormat == "FITS") extractImagesFITS(); else if (dataFormat == "RAW") extractImagesRAW(); else { // nothing yet } // Lastly, store the raw file in the RAWDATA directory backupRawFile(); } // SINGLE and MEF files can be treated the same way void Splitter::extractImagesFITS() { if (!successProcessing) return; int hduType; int chip = 0; // Start counting at 0 (the output filename will have chip+1) // Step through HDUs, extract extensions if they are images, and process them // IMPORTANT: It is implied that the number of the extension, as encountered in the data, // is identical to the 'chip' number used throughout the rest of this source code readPrimaryHeader(); // Check if the instrument matches the data // This does NOT catch all inconsistent matches at this point (e.g. we are not comparing detector identification strings), // and the INSTRUME keyword has not been determined for all pre-defined instruments yet. In the altter case, the test is skipped. // And this works only for uncompressed data (INSTRUME keyword found in extension header of compressed data, which is not yet read at this point QString instrument = ""; searchKeyValue(headerDictionary.value("INSTRUME"), instrument); if (!checkInstrumentConsistency(instrument)) { if (rawStatus == END_OF_FILE) rawStatus = 0; fits_close_file(rawFptr, &rawStatus); printCfitsioError(__func__, rawStatus); return; } // FORCE a beginning with the absolute first HDU. If I use 'movrel' then I'm not sure it is going to skip // over the first HDU if there is one. To be tested with suitable data. Then we could remove the 'movabs' // and make 'movrel' the first command inside 'while () {}' fits_movabs_hdu(rawFptr, 1, &hduType, &rawStatus); while (rawStatus != END_OF_FILE && successProcessing) { if (hduType == IMAGE_HDU) { // for MMIRS and NOTcam, we only want to keep the first extension if (instData.name.contains("MMIRS") || instData.name.contains("NOTcam")) { if (chip >= 1) break; } // some multi-chip cams (FORS, etc) come with separate FITS files. For them, 'chip' would always be zero, // and thus the correct overscan regions etc not identified correctly. // Others such as GROND image simultaneously in different bandpasses on multiple detectors, but they show the // same field of view and should be treated as single-chip cameras. // Hence this mapping int chipMapped = inferChipID(chip) - 1; // same value as chip for normal 'MEF' files // For HSC@SUBARU, drop the 8 focus CCDs if (instData.name == "HSC@SUBARU" && chipMapped >= 104) break; // HSC chips too difficult for astrometry // "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,22,23,24,29,30,31,32,37,38,39,40,45,46,47,48,53,54,55,56,61,62,63,64,69,70,71,72,77,78,79,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104" // do we have an "image" (as compared to a data unit that is simply a nullptr) int naxis = -1; fits_get_img_dim(rawFptr, &naxis, &rawStatus); if (naxis == 0 || naxis == 1 || naxis >= 4) { // Empty or peculiar data units. Continue with the next one fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); continue; } if (chipMapped == -1) { emit messageAvailable("Splitter::extractImagesFITS(): Could not infer chip number", "error"); emit critical(); successProcessing = false; continue; } // OK, we have either a 2D image or a cube. // Saturation handling if (instData.type == "OPT") saturationValue = pow(2,16)-1.; else saturationValue = pow(2,20)-1.; // HAWAII-2RGs can on-chip coadd exposures, exceeding the usual 16-bit dynamic range if (userSaturationValue != 0) saturationValue = userSaturationValue; // Build the header. Must clear before processing new chip headerTHELI.clear(); readExtHeader(); if (!isDetectorAlive(chipMapped)) { fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); ++chip; continue; } if (!isImageUsable(chipMapped)) { fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); ++chip; continue; } testGROND(); // GROND data are an oddball and need to be tested here updateMEFpastingStatus(chip); // Some cameras have readout channels in individual FITS extensions, implying skipping e.g. writeImage() buildTheliHeaderFILTER(chip); buildTheliHeaderWCS(chipMapped); buildTheliHeaderEXPTIME(); buildTheliHeaderDATEOBS(); // must be done before MJD-OBS buildTheliHeaderMJDOBS(); buildTheliHeaderAIRMASS(); // buildTheliHeaderGAIN(chipMapped); // buildTheliHeader(); // Leave if this image is bad if (!successProcessing) continue; // 2D image if (naxis == 2) { getCurrentExtensionData(); // sets naxis1/2Raw, needed by everything below getMultiportInformation(chipMapped); // sets naxis1/2. Updates overscan and data sections for nonstandard multiport readouts // overrideDetectorSections(chip); // TESTING of a more autonomous procedure // gains must be built after multiport chips are assembled buildTheliHeaderGAIN(chipMapped); buildTheliHeader(); if (instData.name.contains("LIRIS")) descrambleLiris(); correctOverscan(); // correctOverscan(combineOverscan_ptr, overscanX[chipMapped], overscanY[chipMapped]); // cropDataSection(dataSection[chipMapped]); pasteMultiportIlluminatedSections(chipMapped); correctXtalk(); // Must maintain original detector geometry for x-talk correction, i.e. do before cropping. Must replace naxisi by naxisiRaw in xtalk methods. correctNonlinearity(chipMapped); convertToElectrons(chipMapped); applyMask(chipMapped); writeImage(chipMapped); // initMyImage(chip); } // Cube if (naxis == 3) { getDataInCube(); getMultiportInformation(chipMapped); // Update overscan and data sections for nonstandard multiport readouts buildTheliHeaderGAIN(chipMapped); buildTheliHeader(); // Test for invalid cube. Not sure such a FIS file can exist? if (naxis3Raw == 0) continue; // Invalid cube. Not sure such a thing can exist? // For these instruments we want to stack (mean) the cube, not slice it QStringList instruments = {"TRECS@GEMINI"}; if (instruments.contains(instData.name)) { stackCube(); correctOverscan(); // correctOverscan(combineOverscan_ptr, overscanX[chipMapped], overscanY[chipMapped]); // cropDataSection(dataSection[chipMapped]); pasteMultiportIlluminatedSections(chipMapped); correctXtalk(); // TODO: how valid is that operation for the stack? correctNonlinearity(chipMapped); // TODO: how valid is that operation for the stack? convertToElectrons(chipMapped); applyMask(chipMapped); writeImage(chipMapped); // initMyImage(chip); // TODO: how is the exposure time defined for these data? Probably requires individual solution // Hamamatsus: define temporary data array, larger than the individual FITS extension, // and successively copy pixels as they become available from the individual extensions. // Then introduce an individual exception in writeImage() and applymask() (once all extensions are available). } else { // Loop over slices, extract each of them for (long i=0; i 6) --chipMapped; // compensate chip number for lost chip } if (instData.name == "WFI_chips1-6@MPGESO") { if (chipMapped == 7) return false; if (chipMapped == 8) return false; } return true; } // For some cameras, the first (or other) images in a sequence might be unusable bool Splitter::isImageUsable(int &chipMapped) { if (instData.name == "NIRI@GEMINI") { QString value = ""; searchKeyValue(QStringList() << "DATALAB", value); QStringList list = value.split('-'); QString id = list.last(); if (id == "001") { if (*verbosity > 1) emit messageAvailable(baseName + " : First NIRI image in sequence, excluding ...", "ignore"); return false; } } return true; } int Splitter::inferChipID(int chip) { // Data from some cameras, such as SuprimeCam and FORS, come in separate FITS files instead of a MEF file. // Multichannel imagers also need to be treated here // We need to identify the chip number correctly: int chipID = chip + 1; // external counting starts with zero; 'chipID' is the number we return for most instruments // These need special treatment. The 'chip' variable is not necessarily used for all of them if (instData.name.contains("FORS1_E2V") // The FORSes with their newer 2-detector configuration || instData.name.contains("FORS2_E2V") || instData.name.contains("FORS2_MIT")) { QString value = ""; searchKeyValue(QStringList() << "ORIGFILE", value); // e.g. FORS2_IMG141.43.CHIP1.fits or FORS2_IMG141.43.CHIP2.fits QStringList valueList = value.split("CHIP"); if (valueList.length() == 2) { value = valueList.at(1); chipID = value.remove(".fits").toInt(); return chipID; } else { emit messageAvailable("Could not determine chip number for " + instData.name, "error"); emit critical(); return 1; } } else if (instData.name == "VIMOS@VLT") { int value = 0; searchKeyValue(QStringList() << "HIERARCH ESO OCS CON QUAD", value); // running from 1 to 4 chipID = value; return chipID; } else if (instData.name == "Direct_4k_SWOPE@LCO" || instData.name.contains("LDSS3")) { int value = 0; searchKeyValue(QStringList() << "OPAMP", value); // running from 1-2 (LDSS3) and from 1-4 (Direct_4k) chipID = value; return chipID; } else if (instData.name == "SuprimeCam_200105-200807@SUBARU" || instData.name == "SuprimeCam_200101-200104@SUBARU" || instData.name == "SuprimeCam_200808-201705@SUBARU" || instData.name == "HSC@SUBARU") { int value = 0; searchKeyValue(QStringList() << "DET-ID", value); // running from 0 to 9 (and 0 to 111 for HSC) chipID = value + 1; return chipID; } else if (instData.name.contains("MOIRCS")) { int value = 0; searchKeyValue(QStringList() << "DET-ID", value); // running from 1 to 2 chipID = value; return chipID; } else if (instData.name == "FourStar@LCO") { int value = 0; searchKeyValue(QStringList() << "CHIP", value); // running from 1 to 4 chipID = value; return chipID; } else if (instData.name.contains("IMACS")) { int value = 0; searchKeyValue(QStringList() << "CHIP", value); // running from 1 to 8 chipID = value; return chipID; } else if (instData.name == "SPARTAN@SOAR") { int value = 0; searchKeyValue(QStringList() << "DETSERNO", value); // detector serial number if (value == 102) chipID = 1; else if (value == 108) chipID = 2; else if (value == 97) chipID = 3; else if (value == 66) chipID = 4; else { emit messageAvailable("Unknown SPARTAN detector serial number: " + QString::number(value), "error"); return 0; } return chipID; } // Multichannel imagers: have just one (so far) detector number per channel, and the camera.ini specifies just 1 chip // Otherwise chipID runs to values larger than 1 which crashes queries of the Mask class else if (instData.name == "GROND_OPT@MPGESO" || instData.name == "GROND_NIR@MPGESO") { // || instData.name == "PISCO@LCO") { // must maintain chip id because of chip-dependent pasting // Simultaneous observations in multiple bands, but just a single detector per band return 1; // (reduced by -1 in caller) } return chipID; } // Retrieve the raw data pixel values void Splitter::getCurrentExtensionData() { if (!successProcessing) return; long naxis[2]; // Get image geometry fits_get_img_size(rawFptr, 2, naxis, &rawStatus); // Read the data block naxis1Raw = naxis[0]; naxis2Raw = naxis[1]; long nelements = naxis1Raw*naxis2Raw; float *buffer = new float[nelements]; float nullval = 0.; int anynull; long fpixel = 1; fits_read_img(rawFptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, &rawStatus); if (!rawStatus) { dataRaw.clear(); dataRaw.resize(nelements); dataRaw.squeeze(); for (long i=0; i xmin = instData.overscan_xmin; QVector xmax = instData.overscan_xmax; QVector ymin = instData.overscan_ymin; QVector ymax = instData.overscan_ymax; for (int chip=0; chip overscanxRegion; if (!xmin.isEmpty() && !xmax.isEmpty()) overscanxRegion << xmin[chip] << xmax[chip]; overscanX[chip] << overscanxRegion; // Overscan Y QVector overscanyRegion; if (!ymin.isEmpty() && !ymax.isEmpty()) overscanyRegion << ymin[chip] << ymax[chip]; overscanY[chip] << overscanyRegion; // Data Section QVector section; section << instData.cutx[chip]; section << instData.cutx[chip] + instData.sizex[chip] - 1; // sizex is not a coordinate, but the number of pixels along this axis. Hence -1 section << instData.cuty[chip]; section << instData.cuty[chip] + instData.sizey[chip] - 1; // sizey is not a coordinate, but the number of pixels along this axis. Hence -1 dataSection[chip] << section; } } // TESTING void Splitter::overrideDetectorSections(int chip) { if (instData.name == "MOSAIC-III@KPNO_4m" || instData.name == "WFC@INT") { multiportOverscanDirections << "vertical"; QVector tmp = extractVerticesFromKeyword("BIASSEC"); overscanX[chip] << tmp.at(0) << tmp.at(1); dataSection[chip] = extractVerticesFromKeyword("DATASEC"); dataSection[chip] = extractVerticesFromKeyword("TRIMSEC"); naxis1 = dataSection[chip].at(1) - dataSection[chip].at(0); naxis2 = dataSection[chip].at(3) - dataSection[chip].at(2); } } void Splitter::getNumberOfAmplifiers() { if (!successProcessing) return; numAmpPerChip = 1; // The number of amplifiers forming data for a single detector. Always 1, unless stored in separate FITS extensions if (instData.name.contains("GMOS-N-HAM") || instData.name.contains("GMOS-S-HAM")) { // update numAmpPerChip with NAMPS keyword fits_read_key_lng(rawFptr, "NAMPS", &numAmpPerChip, nullptr, &rawStatus); if (rawStatus) { emit messageAvailable("Splitter::getNumberOfAmplifiers(): Could not read NAMPS keyword!", "error"); numAmpPerChip = 1; rawStatus = 0; } } // 2 amps per detector if (instData.name == "SOI@SOAR" || instData.name == "DEIMOS_2AMP@KECK" || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "PISCO@LCO") { numAmpPerChip = 2; rawStatus = 0; } // 4 amps per detector (geometric layout doesn't matter here) if (instData.name == "MOSAIC-III_4@KPNO_4m" || instData.name == "SAMI_2x2@SOAR") { numAmpPerChip = 4; rawStatus = 0; } // multiple readout channels in different FITS extensions multiChannelMultiExt << "DEIMOS_2AMP@KECK" << "GMOS-N-HAM@GEMINI" << "GMOS-N-HAM_1x1@GEMINI" << "GMOS-S-HAM@GEMINI" << "GMOS-S-HAM_1x1@GEMINI" << "GMOS-S-HAM_4x4@GEMINI" << "LRIS_BLUE@KECK" << "LRIS_RED@KECK" << "MOSAIC-II_16@CTIO" << "MOSAIC-III_4@KPNO_4m" << "PISCO@LCO" << "SAMI_2x2@SOAR" << "SOI@SOAR"; if (multiChannelMultiExt.contains(instData.name)) ampInSeparateExt = true; if (numAmpPerChip > 1 && ampInSeparateExt) { overscanX.clear(); overscanY.clear(); dataSection.clear(); gain.clear(); overscanX.resize(instData.numChips * numAmpPerChip); overscanY.resize(instData.numChips * numAmpPerChip); dataSection.resize(instData.numChips * numAmpPerChip); gain.resize(instData.numChips * numAmpPerChip); } } // Write the pixel-corrected extension as a separate FITS file to disk void Splitter::writeImage(int chipMapped) { if (!successProcessing) return; if (!MEFpastingFinished) return; // Do not write bad detectors // Easiest done here, and not further above, in case of detectors with multiple readout amps if (instData.badChips.contains(chipMapped)) return; // Exceptions. Return if successful. if (individualFixWriteImage(chipMapped)) return; // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; iui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { if (dataFormat == "RAW" || !instData.bayer.isEmpty()) { // No filter name for bayer matrix images splitFileName = "!"+path+"/"+instData.shortName+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; } else { // general case splitFileName = "!"+path+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; // special cases (overrides outName) individualFixOutName(chipID); } } fits_create_file(&fptr, splitFileName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; i=imin && i<=imax && j>=jmin && j<=jmax) { array[k] = dataCurrent[i+naxis1Raw*j]; ++k; } } } long naxis = 2; long naxes[2] = {nax1, nax2}; // Replace blanks in file names baseName.replace(' ','_'); // Output file goes to a separate directory to account for different detectors / filters QString newPath = path+"_"+channelID; QDir newDir(newPath); newDir.mkpath(newPath); QString outName = "!"+newPath+"/"+baseName+"_"+channelID+"_1P.fits"; // If renaming active, and dateobs was determined successfully if (cdw->ui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { outName = "!"+newPath+"/"+instData.shortName+"."+filter+"_"+channelID+"."+dateObsValue+"_1P.fits"; } fits_create_file(&fptr, outName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; i=imin && i<=imax && j>=jmin && j<=jmax) { array[k] = -1.0 * dataCurrent[i+naxis1Raw*j] * gain; // ADUs counting negative?? I thought I have seen it all ... ++k; } } } long naxis = 2; long naxes[2] = {nax1, nax2}; // Replace blanks in file names baseName.replace(' ','_'); // Output file goes to a separate directory to account for different detectors / filters QString newPath = path+"_"+channelID; QDir newDir(newPath); newDir.mkpath(newPath); QString outName = "!"+newPath+"/"+baseName+"_"+channelID+"_1P.fits"; // If renaming active, and dateobs was determined successfully if (cdw->ui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { outName = "!"+newPath+"/"+instData.shortName+"."+channelID+"."+dateObsValue+"_1P.fits"; } fits_create_file(&fptr, outName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; iui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { if (dataFormat == "RAW") { // No filter name for bayer matrix images if (naxis3Raw == 1) outName = "!"+path+"/"+instData.shortName+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; else outName = "!"+path+"/"+instData.shortName+"."+dateObsValue+"_sl"+QString::number(slice)+"_"+QString::number(chipID)+"P.fits"; } else { if (naxis3Raw == 1) outName = "!"+path+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; else outName = "!"+path+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_sl"+QString::number(slice)+"_"+QString::number(chipID)+"P.fits"; } } fits_create_file(&fptr, outName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; iglobalMask (or mask->isChipMasked) vector when restoring data from RAWDATA and rerunning. // Works fine if done the first time. void Splitter::initMyImage(int chip) { if (!successProcessing) return; // TODO: must use chipID instead of "chip", e.g. for FORS2 MyImage *myImage = new MyImage(path, baseName+"_"+QString::number(chip+1)+"P.fits", "P", chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->imageOnDrive = true; omp_set_lock(genericLock); data->myImageList[chip].append(myImage); if (!data->uniqueChips.contains(chip+1)) data->uniqueChips.push_back(chip+1); omp_unset_lock(genericLock); connect(myImage, &MyImage::modelUpdateNeeded, data, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, data, &Data::pushCritical); connect(myImage, &MyImage::warning, data, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, data, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, data, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, data, &Data::setWCSLockReceived, Qt::DirectConnection); myImage->emitModelUpdateNeeded(); myImage->readImage(splitFileName.remove("!")); ++data->numImages; } void Splitter::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable(baseName + " Splitter::"+funcName+":
" + errorCodes->errorKeyMap.value(status), "error"); emit critical(); successProcessing = false; } } void Splitter::testGROND() { // we want to identify for each exposure whether it comes from the optical or the NIR camera // so that we can use the appropriate branch to deal with the data if (instData.name.contains("GROND")) { int nax1 = 0; searchKeyValue(QStringList() << "NAXIS1", nax1); if (nax1 == 3072) instNameFromData = "GROND_NIR@MPGESO"; else instNameFromData = "GROND_OPT@MPGESO"; } } void Splitter::readExtHeader() { if (rawStatus) return; // Read the entire header. This should always work! char *fullheader = nullptr; int numHeaderKeys = 0; fits_hdr2str(rawFptr, TRUE, NULL, 0, &fullheader, &numHeaderKeys, &rawStatus); printCfitsioError(__func__, rawStatus); if (rawStatus) return; fullExtHeaderString = QString::fromUtf8(fullheader); fits_free_memory(fullheader, &rawStatus); // Map the header onto a QVector int cardLength = 80; long length = fullExtHeaderString.length(); if (length<80) return; extHeader.clear(); for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&fullExtHeaderString, i, cardLength); QString string = subString.toString(); extHeader.push_back(string); } } void Splitter::readPrimaryHeader() { if (rawStatus) return; if (!successProcessing) return; // Read the entire header. This should always work! char *fullheader = nullptr; int numHeaderKeys = 0; fits_hdr2str(rawFptr, TRUE, NULL, 0, &fullheader, &numHeaderKeys, &rawStatus); printCfitsioError(__func__, rawStatus); if (rawStatus) return; fullPrimaryHeaderString = QString::fromUtf8(fullheader); fits_free_memory(fullheader, &rawStatus); // Map the header onto a QVector int cardLength = 80; long length = fullPrimaryHeaderString.length(); if (length<80) return; primaryHeader.clear(); for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&fullPrimaryHeaderString, i, cardLength); QString string = subString.toString(); primaryHeader.push_back(string); } } bool Splitter::checkCorrectMaskSize(const int chip) { if (instData.name.contains("DUMMY")) return true; long n_mask = mask->globalMask[chip].length(); long n_data = dataCurrent.length(); // detectors with multi-amps (one amp per FITS extension): masked at a later stage (calibration) if (n_mask > 0 && n_data > 0 && n_mask != n_data) { if (!maskSizeWarningShown) { emit messageAvailable(fileName + ": Inconsistent image size detected between data and instrument configuration" " (overscan and / or data section) in\n"+instData.nameFullPath+ " \n. The image will not be processed, please remove it manually.", "warning"); emit warning(); // successProcessing = false; // maskSizeWarningShown = true; return false; } } return true; } bool Splitter::checkInstrumentConsistency(QString foundInstrumentName) { QString expectedInstrumentName = instrumentDictionary.value(instData.name); if (!expectedInstrumentName.isEmpty() && expectedInstrumentName != foundInstrumentName) { emit messageAvailable(fileName + ": Wrong instrument selected: Expected " + instData.name + ", but \"INSTRUME= " + foundInstrumentName+"\"", "error"); emit critical(); successProcessing = false; return false; } return true; } THELI-3.1.3/src/tools/splitter.h000066400000000000000000000345561417631501300163470ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef SPLITTER_H #define SPLITTER_H #include "fitsio.h" #include "libraw/libraw.h" #include "../instrumentdata.h" #include "../processingInternal/mask.h" #include "../processingInternal/data.h" #include "../dockwidgets/confdockwidget.h" #include #include class Splitter : public QObject { Q_OBJECT public: explicit Splitter(const instrumentDataType &instrumentData, const Mask *detectorMask, const Mask *altDetectorMask, Data *someData, QString datatype, const ConfDockWidget *confDockWidget, QString maindirname, QString subdirname, QString filename, int *verbose, QObject *parent = nullptr); void extractImages(); void determineFileFormat(); // Pixel processing // x-talk float xtalkNorAmp = 0.; // normal xtalk amplitude float xtalkRowAmp = 0.; // row xtalk amplitude float xtalkKappa = 3.; // outlier rejection QString xtalkDirection = "x"; int xtalkNsection = 32; QString xtalkNorAmpString = ""; QString xtalkRowAmpString = ""; QString dataType = ""; QString splitFileName = ""; bool doXtalkNor = false; bool doXtalkRow = false; int xtalkNorMethod = -1; int xtalkRowMethod = -1; bool alreadyProcessed = false; bool MEFpastingFinished = true; bool maskSizeWarningShown = false; float *dateObsIncrementor = nullptr; // External variable, initialized before constructing the first Splitter object float gainForSaturation = 1.0; float minGainValue = 0.0; // unused long memoryUsed = 0; // Nonlinearity QList> nonlinearityCoefficients; // Overscan // Function pointer (updated externally by the controller) float (*combineOverscan_ptr) (const QVector &, const QVector &, long) = nullptr; const Mask *mask; const Mask *altMask; // alternative mask, in case of e.g. GROND where we have two very different detector types Data *data; QMap headerDictionary; // Defined once in the controller, we just link to it; NOPE! Local copy, thread safety! QMap filterDictionary; // Defined once in the controller, we just link to it QMap instrumentDictionary; // Defined once in the controller, we just link to it QStringList dummyKeys; // Defined once in the controller, we just link to it QStringList headerTHELI; float saturationValue = (float)USHRT_MAX; float userSaturationValue = 0.; QStringList multiChannelMultiExt; // Contains all instruments having multiple readout channels, stored in separate FITS extensions bool successProcessing = true; float progressStepSize = 0.; float *progress = nullptr; omp_lock_t *progressLock = nullptr; omp_lock_t *genericLock = nullptr; bool commaDetected = false; void compileNumericKeys(); private: fitsfile *rawFptr = nullptr; LibRaw rawProcessor; int rawStatus = 0; int numExt = 1; // Number of FITS extensions in a 2D MEF int numSlice = 1; // Number of slices in a 3D cube int numHDU = 1; // Number of HDUs in a FITS file int *verbosity; long naxis1Raw = 0; // Before trimming overscan regions long naxis2Raw = 0; // Before trimming overscan regions long naxis3Raw = 0; // Before trimming overscan regions long naxis1 = 0; long naxis2 = 0; long naxis3 = 0; double rad = 3.1415926535 / 180.; long numAmpPerChip = 1; // The number of amplifiers per detector bool ampInSeparateExt = false; // Whether the data from an amplifier is in a separate FITS extension (e.g., GMOS Hamamatsu, but not for SuprimeCam-2008) QVector> overscanX; QVector> overscanY; QVector> dataSection; QVector gain; // gain values per chip in a multichip camera QVector channelGains; // gain values per readout channel in a detector; e.g. 4-port readout mode with FORS2 not requiring pasting int numReadoutChannels = 1; // number of readout channels per detector // The following must have the same first dimension QVector> multiportOverscanSections; // The sections containing the overscan pixels. Coord system: entire FITS extension QVector> multiportIlluminatedSections; // The sections containing the illuminated pixels. Coord system: entire FITS channel QVector> multiportChannelSections; // The sections containing the entire readout channel (including overscan). Coord system: entire FITS channel QVector multiportGains; // The gain factors for each readout channel; e.g. if amplifiers stored in different FITS extensions QVector multiportOffsetX; // The x-offset of that port's data section from the lower left pixel of the pasted image QVector multiportOffsetY; // The y-offset of that port's data section from the lower left pixel of the pasted image QStringList multiportOverscanDirections; // Whether the overscan strips are vertical or horizontal instrumentDataType instData; // No pointer, because it is accessed from multiple threads and is not thread safe (QVectors, QStrings) // instrumentDataType altInstData; // For GROND, where we have two very different detector types const ConfDockWidget *cdw; QString name; QString fileName; QString path; QString mainDirName; QString subDirName; QString baseName; QString fitsType; // SINGLE, MEF or CUBE QString dataFormat; // FITS or RAW, or UnknownFormat QString bayerPattern = ""; QString filter = "Unknown"; QString instNameFromData = ""; // needed only for a very small number of cameras, where the instrument must be deduced from the headers (GROND) QStringList numericKeyNames; QString dateObsValue = ""; double crval1 = 0.0; double crval2 = 0.0; float chipGain = 1.0; // effective gain for this detector (could be computed for multi-amp detectors) double positionAngle = 0.0; // in [deg] float exptimeValue = 0.0; // header keyword value to calculate other keywords float lstValue = 0.0; // header keyword value to calculate other keywords double mjdobsValue = 0.0; // header keyword value to calculate other keywords float sensorTemp = -1000.; float cameraTemp = -1000.; QString isoSpeed = ""; bool dateObsValid = true; // Used to see if we can safely and unambiguously rename files QVector dataRaw; QVector dataCubeRaw; QVector dataCurrent; QVector dataXcorr; QVector dataPasted; // Accumulates the data from readout channels in separate FITS extensions, until complete; Then transferred to dataCurrent; QString fullExtHeaderString; QString fullPrimaryHeaderString; QStringList extHeader; // The header of the currently read extension QStringList primaryHeader; QString uniqueID = ""; // If dateobs cannot be determined unambiguously // Processing parameters void consistencyChecks(); void descrambleLiris(); void getCurrentExtensionData(); void getDetectorSections(); float polynomialSum(float x, QVector coefficients); void printCfitsioError(QString funcName, int status); void readPrimaryHeader(); void readExtHeader(); void xtalk_method1(); void xtalk_method2(); void xtalk_method3(); void xtalk_method4(); void xtalk_method5(); void xtalk_method6(); void xtalk_method7(); void xtalk_method8(); void xtalk_method9(); void xtalk_method10(); void writeImage(int chipMapped); void retainMandatoryKeywords(); void buildTheliHeader(); void buildTheliHeaderWCS(int chip); void buildTheliHeaderFILTER(int chip); void buildTheliHeaderEXPTIME(); void buildTheliHeaderMJDOBS(); void buildTheliHeaderAIRMASS(); void buildTheliHeaderDATEOBS(); void buildTheliHeaderGAIN(int chip); void buildTheliHeaderSATURATION(); bool searchKey(const QString &searchKeyName, const QStringList &possibleKeyNames, QStringList &outputHeader); bool searchKeyInHeader(const QString &searchKey, const QStringList &possibleKeyNames, const QStringList &inputHeader, QStringList &outputHeader); bool searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, int &value); bool searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, float &value); bool searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, double &value); bool searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, QString &keyValue); bool searchKeyValue(const QStringList &possibleKeyNames, int &value); bool searchKeyValue(const QStringList &possibleKeyNames, float &value); bool searchKeyValue(const QStringList &possibleKeyNames, double &value); bool searchKeyValue(const QStringList &possibleKeyNames, QString &value); double dateobsToMJD(); double dateobsToLST(); double calcAirmass(double ahourangle); double localSiderealTimeToAirmass(); bool checkFormatDATEOBS(); bool searchKeyInHeaderCRVAL(const QString searchKey, const QStringList &possibleKeyNames, const QStringList &inputHeader, QStringList &outputHeader); void searchKeyCRVAL(const QString searchKey, const QStringList &possibleKeyNames, QStringList &outputHeader); bool searchKeyLST(const QStringList &possibleKeyNames); bool searchKeyInHeaderLST(const QStringList &possibleKeyNames, const QStringList &inputHeader); void importRAW(); void buildHeaderRAW(); void extractImagesFITS(); void extractImagesRAW(); void overwriteCameraIniRAW(); void backupRawFile(); bool checkChipGeometry(); int getNorXtalkMethod(); int getRowXtalkMethod(); void correctXtalk(); void correctNonlinearity(int chip); void correctOverscan(); // void doOverscan(float (*combineFunction_ptr)(const QVector &, const QVector &, long), // const QVector &overscanXArea, const QVector &overscanYArea, const QVector vertices); void cropDataSection(QVector dataSection); void initMyImage(int chip); void getDataInFirstCubeSlice(); void getDataInCube(); void sliceCube(long slice); void writeImageSlice(int chip, long slice); void stackCube(); void manualWCSfix(int chip); void WCSbuildCRVAL(); void WCSbuildCDmatrix(int chip); void WCSbuildRADESYS(); void WCSbuildEQUINOX(); void WCSbuildCRPIX(int chip); void WCSbuildCTYPE(); bool individualFixCDmatrix(int chip); bool individualFixCRVAL(); void uncompress(); int inferChipID(int chip); void convertToElectrons(int chip); float harmonicGain(QVector detectorGains); bool individualFixGAIN(int chip); bool isDetectorAlive(int &chipMapped); void individualFixOutName(const int chipID); void applyMask(int chip); bool individualFixWriteImage(int chipMapped); bool isImageUsable(int &chipMapped); QVector extractVertices(QString vertexString); QVector extractVerticesFromKeyword(QString keyword); // void pasteMultiPortDataSections(QVector dataSection); void getMultiportInformation(int chip); void doOverscanVertical(float (*combineFunction_ptr)(const QVector &, const QVector &, long), const QVector &overscanArea, const QVector dataVertices, float &overscanEstimate); void doOverscanHorizontal(float (*combineFunction_ptr)(const QVector &, const QVector &, long), const QVector &overscanArea, const QVector dataVertices, float &overscanEstimate); void pasteMultiportIlluminatedSections(int chip); void pasteSubArea(QVector &dataT, const QVector &dataS, const QVector §on, const float corrFactor, const long nT, const long mT, const long nS); void pasteSubArea(QVector &dataT, const QVector &dataS, const QVector §ion, const float corrFactor, const long offx, const long offy, const long nT, const long mT, const long nS); void testGROND(); QVector extractVerticesFromKeyword(QString keyword1, QString keyword2, QString keyword3, QString keyword4); QVector extractReducedOverscanFromKeyword(QString keyword1, QString keyword2, int value3, int value4); QVector extractReducedIlluminationFromKeyword(QString keyword1, QString keyword2, int value3, int value4); void updateMEFpastingStatus(int chip); bool individualFixCRPIX(int chip); void getNumberOfAmplifiers(); void resetInstrumentData(); void initAltInstrumentData(QString instrumentNameFullPath); void testOverscan(QVector &overscan); void to_EN_US(QString &keyName, QString &keyValue); bool checkCorrectMaskSize(const int chip); QString mjdobsToDATEOBS(double mjd); bool individualFixDATEOBS(); bool checkInstrumentConsistency(QString foundInstrumentName); void updateMinGainValue(float gainValue); void overrideDetectorSections(int chip); bool individualFixFILTER(int chip); bool individualFixEQUINOX(); // bool CDfromCDELTandPC(const QString cdeltstr, const QString pcstr, double &cd); QVector CDfromCDELT(); signals: void messageAvailable(QString message, QString type); void warning(); void critical(); void showMessageBox(QString trigger, QString part1, QString part2); public slots: }; #endif // SPLITTER_H THELI-3.1.3/src/tools/splitter_RAW.cc000066400000000000000000000224511417631501300172050ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../functions.h" #include "libraw/libraw.h" #include "libraw/libraw_version.h" #include #include #include #include #include // Handles RAW files from CMOS-type cameras void Splitter::importRAW() { if (!successProcessing) return; // The file has been opened successfully already by Splitter::determineFileType() #define S rawProcessor.imgdata.sizes // TODO: check what that means. Do we have to return? if (!(rawProcessor.imgdata.idata.filters || rawProcessor.imgdata.idata.colors == 1)) { emit messageAvailable(fileName + " : Only Bayer-pattern RAW files supported.", "warning"); emit warning(); // return; } // Extract pixels naxis1Raw = S.raw_width; naxis2Raw = S.raw_height; naxis1 = S.iwidth; naxis2 = S.iheight; // if (!checkChipGeometry()) return; long dim = naxis1Raw*naxis2Raw; dataRaw.clear(); dataRaw.resize(dim); dataRaw.squeeze(); for (int i=0; i= 20 #define P3 rawProcessor.imgdata.makernotes.common #endif QString timeStamp = ctime(&(P2.timestamp)); timeStamp = timeStamp.simplified(); QStringList timeStampList = timeStamp.split(' '); if (timeStampList.length() < 5) { dateObsValue = "2020-01-01T00:00:00.0"; } else { QString yy = timeStampList[4]; QString mm = timeStampList[1]; QString dd = timeStampList[2]; QString hours = timeStampList[3]; if (mm == "Jan") mm = "01"; else if (mm == "Feb") mm = "02"; else if (mm == "Mar") mm = "03"; else if (mm == "Apr") mm = "04"; else if (mm == "May") mm = "05"; else if (mm == "Jun") mm = "06"; else if (mm == "Jul") mm = "07"; else if (mm == "Aug") mm = "08"; else if (mm == "Sep") mm = "09"; else if (mm == "Oct") mm = "10"; else if (mm == "Nov") mm = "11"; else if (mm == "Dec") mm = "12"; dateObsValue = yy+"-"+mm+"-"+dd+"T"+hours; if (!checkFormatDATEOBS()) dateObsValue = "2020-01-01T00:00:00.0"; } mjdobsValue = dateobsToMJD(); exptimeValue = P2.shutter; #if defined(LIBRAW_MAJOR_VERSION) && LIBRAW_MAJOR_VERSION == 0 && defined(LIBRAW_MINOR_VERSION) && LIBRAW_MINOR_VERSION >= 20 sensorTemp = P3.SensorTemperature; cameraTemp = P3.CameraTemperature; #else sensorTemp = P2.SensorTemperature; cameraTemp = P2.CameraTemperature; #endif isoSpeed = QString::number(int(P2.iso_speed)); saturationValue = pow(2,12)-1; // 12 bit // From RAW data (unreliable, because of potential trimming) /* bayerPattern = ""; if (P1.filters) { if (!P1.cdesc[3]) P1.cdesc[3] = 'G'; for (int i=0; i<4; ++i) { bayerPattern.append(P1.cdesc[rawProcessor.fcol(i >> 1, i & 1)]); } } */ // Rather, take user-defined setup bayerPattern = instData.bayer; } // UNUSED // For RAW files we force the SIZE settings in the camera.ini bool Splitter::checkChipGeometry() { if (!successProcessing) return false; for (int chip=0; chip #include #include #include #include /* // TODO Instrument slike FORS1/2 come with different collimators, changing the plate scale but not the detector geometries. What to do with PIXSCALE in this respect/ Do we still need it in the instrument.ini files, or is it better derived from the CD matrix directly? Binning: include as separate option? need to check various instruments whether their overscan and gain stay the same or not. Could alternatively offer separate overscan / size vectors in the .ini files. Or even better: automatic detection of the binning mode Take CRPIX from .ahead file for multi-chip cameras. Don't take CD matrix from ahead file because of changing position angles ... */ void Splitter::buildTheliHeader() { if (!successProcessing) return; // The following keywords must be present in the THELI headers, // AND the values taken from the raw data QStringList mandatoryKeys = {"OBJECT"}; // Loop over all mandatory keywords and try to find a match. // Certainly not the most efficient way of doing it, but the overhead should be small // as we operate on QStringLists and not FITS files QString fallback = ""; for (auto &mandatoryKey : mandatoryKeys) { // Search key in primary and extension header, and append it to 'headerTHELI' if found bool keyFound = searchKey(mandatoryKey, headerDictionary.value(mandatoryKey), headerTHELI); // Default fallback values if (mandatoryKey == "OBJECT" && !keyFound) fallback = "OBJECT = 'Unknown'"; if (!keyFound) { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+mandatoryKey+", using default: "+fallback, "ignore"); fallback.resize(80, ' '); headerTHELI.append(fallback); } } // Append geographic coordinates QString geolon = "GEOLON = "+QString::number(instData.obslon, 'f', 4); QString geolat = "GEOLAT = "+QString::number(instData.obslat, 'f', 4); geolon.resize(80, ' '); geolat.resize(80, ' '); headerTHELI.append(geolon); headerTHELI.append(geolat); // Instrument-specific optional keys bool keyFoundOptional = true; QString instSpecificKey = ""; if (instData.name == "SPARTAN@SOAR") instSpecificKey = "ROTATOR"; if (!instSpecificKey.isEmpty()) keyFoundOptional = searchKey(instSpecificKey, {instSpecificKey}, headerTHELI); if (!keyFoundOptional) emit messageAvailable(fileName + " : Could not determine instrument-specific keyword: "+instSpecificKey, "warning"); // Propagate Bayer matrix ID for color CCD chips if (!instData.bayer.isEmpty()) { QString card = "BAYER = '"+instData.bayer+"'"; card.resize(80, ' '); headerTHELI.append(card); } // Append DUMMY keywords headerTHELI.append(dummyKeys); // Append the THELIPRO keyword to indicate that this FITS file underwent initial THELI processing QString card = "THELIPRO= 1 / Processed by THELI"; card.resize(80, ' '); headerTHELI.append(card); } void Splitter::buildTheliHeaderMJDOBS() { if (!successProcessing) return; // List of instruments for which MJD-OBS is not reliable and should be constructed from DATE-OBS QStringList instruments = {"GSAOI@GEMINI", "GSAOI_CHIP1@GEMINI", "GSAOI_CHIP2@GEMINI", "GSAOI_CHIP3@GEMINI", "GSAOI_CHIP4@GEMINI", "FLAMINGOS2@GEMINI", "SAMI_2x2@SOAR" // integer }; if (instruments.contains(instData.name)) { if (!dateObsValue.isEmpty()) { mjdobsValue = dateobsToMJD(); QString mjdCard = "MJD-OBS = "+QString::number(mjdobsValue,'f',7); mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); } else { mjdobsValue = 58849.000000; QString mjdCard = "MJD-OBS = 58849.000000"; mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); emit messageAvailable(fileName + " : Could not determine keyword: MJD-OBS, set to 58849.000000 (2020-01-01)
"+ "Some processing tasks (background modeling, proper motion correction) will not work correctly.", "warning"); emit warning(); } return; } // Search key in primary and extension header, and append it to 'headerTHELI' if found bool keyFound = searchKey("MJD-OBS", headerDictionary.value("MJD-OBS"), headerTHELI); if (keyFound) return; // Calculate MJD-OBS from DATE-OBS if not found if (!keyFound && !dateObsValue.isEmpty()) { mjdobsValue = dateobsToMJD(); QString mjdCard = "MJD-OBS = "+QString::number(mjdobsValue,'f',7); mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); } else { mjdobsValue = 58849.000000; QString mjdCard = "MJD-OBS = 58849.000000"; mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); emit messageAvailable(fileName + " : Could not determine keyword: MJD-OBS, set to 58849.000000 (2020-01-01)
"+ "Some processing tasks (background modeling, proper motion correction) will not work correctly.", "warning"); emit warning(); } } // UNUSED void Splitter::buildTheliHeaderSATURATION() { QString card = "SATURATE= " + QString::number(saturationValue, 'f', 6) + " / Saturation level for this image"; card.resize(80, ' '); headerTHELI.append(card); } void Splitter::buildTheliHeaderWCS(int chip) { if (!successProcessing) return; // Each of the following handles their own exceptions for specific instruments // (which don't carry a proper and consistent FITS header) WCSbuildCTYPE(); WCSbuildCRVAL(); WCSbuildCRPIX(chip); WCSbuildCDmatrix(chip); WCSbuildRADESYS(); WCSbuildEQUINOX(); } void Splitter::WCSbuildCRPIX(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCRPIX(chip)) return; if (chip >= instData.crpix1.length()) { QString nfound = QString::number(chip+1); QString nexpected = QString::number(instData.numChips); emit messageAvailable(fileName + ": " + nfound + " detectors found, " + nexpected + " expected. Check instrument selection." , "error"); emit critical(); successProcessing = false; return; } QStringList headerWCS; // Use dedicated lookup if (instData.name == "HSC@SUBARU") { searchKeyCRVAL("CRPIX1", headerDictionary.value("CRPIX1"), headerWCS); searchKeyCRVAL("CRPIX2", headerDictionary.value("CRPIX2"), headerWCS); } else { // CRPIXi: Rely on instrument.ini (Todo: scan .ahead files directly for multi-chip cameras) QString crpix1_card = "CRPIX1 = "+QString::number(instData.crpix1[chip]); QString crpix2_card = "CRPIX2 = "+QString::number(instData.crpix2[chip]); crpix1_card.resize(80, ' '); crpix2_card.resize(80, ' '); headerWCS.append(crpix1_card); headerWCS.append(crpix2_card); } headerTHELI.append(headerWCS); } // Instrument dependent void Splitter::WCSbuildCRVAL() { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCRVAL()) return; QStringList headerWCS; // Use dedicated lookup searchKeyCRVAL("CRVAL1", headerDictionary.value("CRVAL1"), headerWCS); searchKeyCRVAL("CRVAL2", headerDictionary.value("CRVAL2"), headerWCS); headerTHELI.append(headerWCS); } void Splitter::WCSbuildCTYPE() { if (!successProcessing) return; QStringList headerWCS; // CTYPEi are fixed no matter what! QString ctype1_card = "CTYPE1 = 'RA---TAN'"; QString ctype2_card = "CTYPE2 = 'DEC--TAN'"; ctype1_card.resize(80, ' '); ctype2_card.resize(80, ' '); headerWCS.append(ctype1_card); headerWCS.append(ctype2_card); headerTHELI.append(headerWCS); } // Instrument dependent /* void Splitter::WCSbuildCDmatrix(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCDmatrix(chip)) return; QStringList headerWCS; QString fallback = ""; QStringList wcsKeys = {"CD1_1", "CD1_2", "CD2_1", "CD2_2"}; float flipcd11 = 1.0; float flipcd22 = 1.0; if (instData.flip == "FLIPX") flipcd11 = -1.0; else if (instData.flip == "FLIPY") flipcd22 = -1.0; else if (instData.flip == "ROT180") { flipcd11 = -1.0; flipcd22 = -1.0; } for (auto &wcsKey : wcsKeys) { bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); // fallback double cd = 0.0; if (!keyFound && wcsKey == "CD1_1") { bool success = CDfromCDELTandPC("CDELT1", "PC1_1", cd); if (success) fallback = "CD1_1 = "+QString::number(cd, 'g', 6); else fallback = "CD1_1 = "+QString::number(-1.*flipcd11*instData.pixscale/3600., 'g', 6); } if (!keyFound && wcsKey == "CD2_2") { bool success = CDfromCDELTandPC("CDELT2", "PC2_2", cd); if (success) fallback = "CD2_2 = "+QString::number(cd, 'g', 6); else fallback = "CD2_2 = "+QString::number(flipcd22*instData.pixscale/3600., 'g', 6); } if (!keyFound && wcsKey == "CD1_2") { bool success = CDfromCDELTandPC("CDELT2", "PC1_2", cd); if (success) fallback = "CD1_2 = "+QString::number(cd, 'g', 6); else fallback = "CD1_2 = 0.0"; } if (!keyFound && wcsKey == "CD2_1") { bool success = CDfromCDELTandPC("CDELT1", "PC2_1", cd); if (success) fallback = "CD2_1 = "+QString::number(cd, 'g', 6); else fallback = "CD2_1 = 0.0"; } if (!keyFound) { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+fallback, "ignore"); fallback.resize(80, ' '); headerWCS.append(fallback); } } headerTHELI.append(headerWCS); } */ // Instrument dependent void Splitter::WCSbuildCDmatrix(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCDmatrix(chip)) return; QStringList headerWCS; QString fallback = ""; QStringList wcsKeys = {"CD1_1", "CD1_2", "CD2_1", "CD2_2"}; // Create fallback CD matrix from CDELT keywords, if later determination of CDij fails QVector cd_fallback; cd_fallback = CDfromCDELT(); // Try reading CDij matrix directly, sue fallback if failing for (auto &wcsKey : wcsKeys) { bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); // fallback if (!keyFound && wcsKey == "CD1_1") fallback = "CD1_1 = "+QString::number(cd_fallback[0], 'g', 6); if (!keyFound && wcsKey == "CD1_2") fallback = "CD1_2 = "+QString::number(cd_fallback[1], 'g', 6); if (!keyFound && wcsKey == "CD2_1") fallback = "CD2_1 = "+QString::number(cd_fallback[2], 'g', 6); if (!keyFound && wcsKey == "CD2_2") fallback = "CD2_2 = "+QString::number(cd_fallback[3], 'g', 6); if (!keyFound) { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+fallback, "ignore"); fallback.resize(80, ' '); headerWCS.append(fallback); } } headerTHELI.append(headerWCS); } /* bool Splitter::CDfromCDELTandPC(const QString cdeltstr, const QString pcstr, double &cd) { double cdelt = -1.0; double pc = -1.0; bool cdtest = searchKeyValue(headerDictionary.value(cdeltstr), cdelt); bool pctest = searchKeyValue(headerDictionary.value(pcstr), pc); if (cdtest && pctest) { cd = cdelt*pc; if (fabs(cd) > 0.5) cd *= instData.pixscale/3600.; // recover plate scale if not available return true; } else if (cdtest && !pctest) { cd = cdelt; if (fabs(cd) > 0.5) cd *= instData.pixscale/3600.; qDebug() << cdeltstr << cd; return true; } else { cd = 0.; return false; } } */ QVector Splitter::CDfromCDELT() { double cdelt1 = 0.; double cdelt2 = 0.; double pc11 = 1.; // matching crota2 = 0. double pc12 = 0.; // matching crota2 = 0. double pc21 = 0.; // matching crota2 = 0. double pc22 = 1.; // matching crota2 = 0. double crota2 = 0.; bool cdelt1test = searchKeyValue(headerDictionary.value("CDELT1"), cdelt1); bool cdelt2test = searchKeyValue(headerDictionary.value("CDELT2"), cdelt2); bool crota2test = searchKeyValue(headerDictionary.value("CROTA2"), crota2); bool pc11test = searchKeyValue(headerDictionary.value("PC1_1"), pc11); bool pc12test = searchKeyValue(headerDictionary.value("PC1_2"), pc12); bool pc21test = searchKeyValue(headerDictionary.value("PC2_1"), pc21); bool pc22test = searchKeyValue(headerDictionary.value("PC2_2"), pc22); bool pctest = true; pctest = pc11test & pc12test & pc21test & pc22test; if (!pctest) { // check for really old convention pc11test = searchKeyValue(headerDictionary.value("PC001001"), pc11); pc12test = searchKeyValue(headerDictionary.value("PC001002"), pc12); pc21test = searchKeyValue(headerDictionary.value("PC002001"), pc21); pc22test = searchKeyValue(headerDictionary.value("PC002002"), pc22); pctest = pc11test & pc12test & pc21test & pc22test; } // Only if no CD matrix information is present in the raw FITS headers: float flipcd11 = 1.0; float flipcd22 = 1.0; if (instData.flip == "FLIPX") flipcd11 = -1.0; else if (instData.flip == "FLIPY") flipcd22 = -1.0; else if (instData.flip == "ROT180") { flipcd11 = -1.0; flipcd22 = -1.0; } double cd11 = 0.; double cd12 = 0.; double cd21 = 0.; double cd22 = 0.; // Now build the CD matrix QVector cd; // No information whatsoever: return standard "North up East left" if (!cdelt1test || !cdelt2test) { cd11 = -flipcd11*instData.pixscale/3600.; cd22 = flipcd22*instData.pixscale/3600.; cd << cd11 << cd12 << cd21 << cd22; return cd; } // CDELT yes, but no information about sky position angle if (!pctest && !crota2test) { cd11 = cdelt1; cd22 = cdelt2; cd << cd11 << cd12 << cd21 << cd22; return cd; } // CROTA2 but no PC matrix else if (!pctest && crota2test) { pc11 = cos(crota2*rad); pc12 = -sin(crota2*rad); pc21 = sin(crota2*rad); pc22 = cos(crota2*rad); } // PC matrix and CROTA2 // According to the FITS standard, this combination is not allowed, but still some headers have it else if (pctest && crota2test) { pc11 = cos(crota2*rad); pc12 = -sin(crota2*rad); pc21 = sin(crota2*rad); pc22 = cos(crota2*rad); emit messageAvailable(name + " : PC matrix and CROTA2 found. Using CROTA2 to compute CD matrix.", "warning"); } else { // (pctest && !crota2test) { // already handled above by determining the PCij elements directly from FITS header } // Compute the CD matrix cd11 = cdelt1 * pc11; cd12 = cdelt2 * pc12; cd21 = cdelt1 * pc21; cd22 = cdelt2 * pc22; // safety check if (fabs(cd11) > 0.5 || fabs(cd11) > 0.5 || fabs(cd21) > 0.5 || fabs(cd22) > 0.5) { cd11 = -flipcd11*instData.pixscale/3600.; cd22 = flipcd22*instData.pixscale/3600.; cd12 = 0.; cd21 = 0.; } cd << cd11 << cd12 << cd21 << cd22; return cd; } void Splitter::WCSbuildRADESYS() { if (!successProcessing) return; QStringList headerWCS; QString wcsKey = "RADESYS"; bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); if (!keyFound) { QString card = "RADESYS = 'ICRS'"; if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+card, "ignore"); card.resize(80, ' '); headerWCS.append(card); } headerTHELI.append(headerWCS); } void Splitter::WCSbuildEQUINOX() { if (!successProcessing) return; if (individualFixEQUINOX()) return; QStringList headerWCS; QString wcsKey = "EQUINOX"; bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); if (!keyFound) { QString card = "EQUINOX = 2000.0"; if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+card, "ignore"); card.resize(80, ' '); headerWCS.append(card); } headerTHELI.append(headerWCS); } bool Splitter::individualFixEQUINOX() { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; QString equinoxCard = ""; if (instData.name == "SITe3_SWOPE@LCO") { equinoxCard = equinoxCard = "EQUINOX = 2000.0"; // SITe3_SWOPE@LCO has EPOCH written to EQUINOX, which makes scamp fail since the coords are in J2000. individualFixDone = true; } if (individualFixDone) { equinoxCard.resize(80, ' '); headerWCS.append(equinoxCard); headerTHELI.append(headerWCS); } return individualFixDone; } bool Splitter::individualFixCRVAL() { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; QString crval1_card = ""; QString crval2_card = ""; QString crval1 = ""; QString crval2 = ""; // List of instruments that we have to consider QStringList list = {"WFC@INT", "SUSI1@NTT", "PISCO@LCO"}; // Leave if no individual fix is required. if (!list.contains(instData.name)) return false; // Prepare fix. // First, read coords and fix format (sometimes we have 'HH MM SS' instead of 'HH:MM:SS') // Convert to decimal format if necessary searchKeyValue(headerDictionary.value("CRVAL1"), crval1); searchKeyValue(headerDictionary.value("CRVAL2"), crval2); crval1.replace(' ', ':'); crval2.replace(' ', ':'); if (crval1.contains(':')) crval1 = hmsToDecimal(crval1); if (crval2.contains(':')) crval2 = dmsToDecimal(crval2); // Here are the individual fixes if (instData.name == "WFC@INT") { double alpha = crval1.toDouble(); double delta = crval2.toDouble(); // reset the coordinates such that scamp does not get confused (optical axis != crpix by ~4 arcminutes) alpha = alpha - 0.0733 / cos(delta*rad); if (alpha > 360.) alpha -= 360.; if (alpha < 0.) alpha += 360.; delta = delta - 0.02907; crval1_card = "CRVAL1 = "+QString::number(alpha, 'f', 6); crval2_card = "CRVAL2 = "+QString::number(delta, 'f', 6); individualFixDone = true; } if (instData.name == "SUSI1@NTT") { searchKeyValue(QStringList() << "RA", crval1); searchKeyValue(QStringList() << "DEC", crval2); crval1_card = "CRVAL1 = "+crval1; crval2_card = "CRVAL2 = "+crval2; individualFixDone = true; } if (instData.name == "PISCO@LCO") { searchKeyValue(QStringList() << "TELRA", crval1); // CRVALij in FITS extensions are highly inaccurate searchKeyValue(QStringList() << "TELDC", crval2); if (crval1.contains(":")) crval1 = hmsToDecimal(crval1); if (crval2.contains(":")) crval2 = dmsToDecimal(crval2); crval1_card = "CRVAL1 = "+crval1; crval2_card = "CRVAL2 = "+crval2; individualFixDone = true; } if (individualFixDone) { crval1_card.resize(80, ' '); crval2_card.resize(80, ' '); headerWCS.append(crval1_card); headerWCS.append(crval2_card); headerTHELI.append(headerWCS); } return individualFixDone; } bool Splitter::individualFixCRPIX(int chip) { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; QString crpix1_card = ""; QString crpix2_card = ""; float crpix1 = 0.; float crpix2 = 0.; // Leave if no individual fix is required. if (!multiChannelMultiExt.contains(instData.name)) return false; // Prepare fix. // Convert to decimal format if necessary searchKeyValue(headerDictionary.value("CRPIX1"), crpix1); searchKeyValue(headerDictionary.value("CRPIX2"), crpix2); // Solutions per individual channel (will be ignored) crpix1_card = "CRPIX1 = "+QString::number(crpix1, 'f', 2); crpix2_card = "CRPIX2 = "+QString::number(crpix2, 'f', 2); // Here are the individual fixes if (instData.name == "GMOS-N-HAM_1x1@GEMINI" || instData.name == "GMOS-S-HAM_1x1@GEMINI") { if (chip == 3) crpix1_card = "CRPIX1 = 3180"; if (chip == 7) crpix1_card = "CRPIX1 = 1088"; if (chip == 11) crpix1_card = "CRPIX1 = -1004"; crpix2_card = "CRPIX2 = 2304"; individualFixDone = true; } if (instData.name == "GMOS-N-HAM@GEMINI" || instData.name == "GMOS-S-HAM@GEMINI") { if (chip == 3) crpix1_card = "CRPIX1 = 1589"; if (chip == 7) crpix1_card = "CRPIX1 = 544"; if (chip == 11) crpix1_card = "CRPIX1 = -502"; crpix2_card = "CRPIX2 = 1152"; individualFixDone = true; } if (instData.name == "GMOS-S-HAM_4x4@GEMINI") { if (chip == 3) crpix1_card = "CRPIX1 = 794"; if (chip == 7) crpix1_card = "CRPIX1 = 272"; if (chip == 11) crpix1_card = "CRPIX1 = -251"; crpix2_card = "CRPIX2 = 576"; individualFixDone = true; } if (instData.name == "SOI@SOAR") { if (chip == 1) crpix1_card = "CRPIX1 = 1051"; if (chip == 3) crpix1_card = "CRPIX1 = -26"; crpix2_card = "CRPIX2 = 1024"; individualFixDone = true; } if (instData.name == "DEIMOS_2AMP@KECK") { if (chip == 1) crpix1_card = "CRPIX1 = 4253"; if (chip == 3) crpix1_card = "CRPIX1 = 2097"; if (chip == 5) crpix1_card = "CRPIX1 = -53"; if (chip == 7) crpix1_card = "CRPIX1 = -2200"; crpix2_card = "CRPIX2 = 1301"; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { if (chip == 1) crpix1_card = "CRPIX1 = 2099"; if (chip == 3) crpix1_card = "CRPIX1 = -52"; crpix2_card = "CRPIX2 = 2052"; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { if (chip == 1) crpix1_card = "CRPIX1 = -126"; if (chip == 3) crpix1_card = "CRPIX1 = 1835"; crpix2_card = "CRPIX2 = 1260"; individualFixDone = true; } if (instData.name == "MOSAIC-II_16@CTIO") { if (chip == 1) crpix1_card = "CRPIX1 = 4219"; if (chip == 3) crpix1_card = "CRPIX1 = 2078"; if (chip == 5) crpix1_card = "CRPIX1 = -33"; if (chip == 7) crpix1_card = "CRPIX1 = -2166"; if (chip == 9) crpix1_card = "CRPIX1 = 4221"; if (chip == 11) crpix1_card = "CRPIX1 = 2081"; if (chip == 13) crpix1_card = "CRPIX1 = -31"; if (chip == 15) crpix1_card = "CRPIX1 = -2169"; if (chip == 1) crpix2_card = "CRPIX2 = 4148"; if (chip == 3) crpix2_card = "CRPIX2 = 4121"; if (chip == 5) crpix2_card = "CRPIX2 = 4119"; if (chip == 7) crpix2_card = "CRPIX2 = 4136"; if (chip == 9) crpix2_card = "CRPIX2 = -34"; if (chip == 11) crpix2_card = "CRPIX2 = -24"; if (chip == 13) crpix2_card = "CRPIX2 = -26"; if (chip == 15) crpix2_card = "CRPIX2 = -56"; individualFixDone = true; } if (instData.name == "PISCO@LCO") { if (chip == 1) crpix1_card = "CRPIX1 = 1500"; if (chip == 3) crpix1_card = "CRPIX1 = 1500"; if (chip == 5) crpix1_card = "CRPIX1 = 1500"; if (chip == 7) crpix1_card = "CRPIX1 = 1500"; if (chip == 1) crpix2_card = "CRPIX2 = 3000"; if (chip == 3) crpix2_card = "CRPIX2 = 3000"; if (chip == 5) crpix2_card = "CRPIX2 = 3000"; if (chip == 7) crpix2_card = "CRPIX2 = 3000"; individualFixDone = true; } if (instData.name == "MOSAIC-III_4@KPNO_4m") { if (chip == 3) crpix1_card = "CRPIX1 = 4219"; if (chip == 7) crpix1_card = "CRPIX1 = 2078"; if (chip == 11) crpix1_card = "CRPIX1 = -33"; if (chip == 15) crpix1_card = "CRPIX1 = -2166"; if (chip == 3) crpix2_card = "CRPIX2 = 4148"; if (chip == 7) crpix2_card = "CRPIX2 = 4121"; if (chip == 11) crpix2_card = "CRPIX2 = 4119"; if (chip == 15) crpix2_card = "CRPIX2 = 4136"; individualFixDone = true; } if (instData.name == "SAMI_2x2@SOAR") { if (chip == 3) { crpix1_card = "CRPIX1 = 1024"; crpix1_card = "CRPIX1 = 1024"; } individualFixDone = true; } // Append only when all channels of one chip have been read (i.e., 'individualFixDone' == true) if (individualFixDone) { crpix1_card.resize(80, ' '); crpix2_card.resize(80, ' '); headerWCS.append(crpix1_card); headerWCS.append(crpix2_card); headerTHELI.append(headerWCS); } return individualFixDone; } bool Splitter::individualFixCDmatrix(int chip) { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; double cd11 = 0.; double cd12 = 0.; double cd21 = 0.; double cd22 = 0.; QString cd11_card = ""; QString cd12_card = ""; QString cd21_card = ""; QString cd22_card = ""; if (instData.name == "Direct_2k_DUPONT@LCO") { cd11_card = "CD1_1 = 0.0"; cd12_card = "CD1_2 = -7.2273e-5"; cd21_card = "CD2_1 = -7.2273e-5"; cd22_card = "CD2_2 = 0.0"; individualFixDone = true; } if (instData.name == "SITe3_SWOPE@LCO") { cd11_card = "CD1_1 = -1.2083e-4"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = -1.2083e-4"; individualFixDone = true; } if (instData.name == "Direct_4k_SWOPE@LCO") { if (chip == 0) { cd11_card = "CD1_1 = 8.839493716E-07"; cd12_card = "CD1_2 = -1.209379295E-04"; cd21_card = "CD2_1 = -1.209379295E-04"; cd22_card = "CD2_2 = -8.839493716E-07"; } if (chip == 1) { cd11_card = "CD1_1 = -8.861927404E-07"; cd12_card = "CD1_2 = -1.209344868E-04"; cd21_card = "CD2_1 = 1.209344868E-04"; cd22_card = "CD2_2 = -8.861927404E-07"; } if (chip == 2) { cd11_card = "CD1_1 = -7.788683939E-07"; cd12_card = "CD1_2 = 1.211132665E-04"; cd21_card = "CD2_1 = 1.211132665E-04"; cd22_card = "CD2_2 = 7.788683939E-07"; } if (chip == 3) { cd11_card = "CD1_1 = 8.755109826E-07"; cd12_card = "CD1_2 = 1.208828016E-04"; cd21_card = "CD2_1 = -1.208828016E-04"; cd22_card = "CD2_2 = 8.755109826E-07"; } individualFixDone = true; } if (instData.name == "LDSS3_from201402@LCO") { if (chip == 0) { cd11_card = "CD1_1 = -5.213e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 5.213e-5"; } if (chip == 1) { cd11_card = "CD1_1 = 5.230e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 5.230e-5"; } individualFixDone = true; } if (instData.name == "WFI@MPGESO") { cd11_card = "CD1_1 = -6.611e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 6.611e-5"; individualFixDone = true; } if (instData.name == "DEIMOS_1AMP@KECK" || instData.name == "DEIMOS_2AMP@KECK") { cd11_card = "CD1_1 = 0.0"; cd12_card = "CD1_2 = 3.28000e-5"; cd21_card = "CD2_1 = 3.28000e-5"; cd22_card = "CD2_2 = 0.0"; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { cd11_card = "CD1_1 = 0.0"; cd12_card = "CD1_2 = -3.76e-5"; cd21_card = "CD2_1 = 3.76e-5"; cd22_card = "CD2_2 = 0.0"; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { cd11_card = "CD1_1 = -3.76e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = -3.76e-5"; individualFixDone = true; } if (instData.name == "ESI@KECK") { cd11_card = "CD1_1 = -4.28333e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = -4.28333e-5"; individualFixDone = true; } if (instData.name.contains("WFI_2x2") && instData.name.contains("MPGESO") ) { cd11_card = "CD1_1 = -1.322e-4"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 1.322e-4"; individualFixDone = true; } if (instData.name == "WFC@INT") { if (chip == 0) { cd11_card = "CD1_1 = -1.186589131599E-06"; cd12_card = "CD1_2 = -9.208350034543E-05"; cd21_card = "CD2_1 = -9.202558574925E-05"; cd22_card = "CD2_2 = 9.373099270996E-07"; } if (chip == 1) { cd11_card = "CD1_1 = 9.158969785153E-05"; cd12_card = "CD1_2 = 1.000429584977E-07"; cd21_card = "CD2_1 = -8.707577386754E-08"; cd22_card = "CD2_2 = -9.204121646891E-05"; } if (chip == 2) { cd11_card = "CD1_1 = -1.101867868104E-06"; cd12_card = "CD1_2 = -9.186460105657E-05"; cd21_card = "CD2_1 = -9.119982231051E-05"; cd22_card = "CD2_2 = 1.393090409586E-06"; } if (chip == 3) { cd11_card = "CD1_1 = -9.862265741128E-07"; cd12_card = "CD1_2 = -9.221689418834E-05"; cd21_card = "CD2_1 = -9.224461667406E-05"; cd22_card = "CD2_2 = 1.077599414761E-06"; } individualFixDone = true; } if (instData.name == "FourStar@LCO") { // FourStar has no CD matrix in the header if (!searchKeyValue(QStringList() << "ROTANGLE", positionAngle)) { emit messageAvailable(name + " : Could not find ROTANGLE keyword, set to zero! CD matrix might have wrong orientation.", "warning"); emit warning(); positionAngle = 0.0; } cd11 = -1.*instData.pixscale / 3600.; cd12 = 0.0; cd21 = 0.0; cd22 = instData.pixscale / 3600.; rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name.contains("IMACS")) { // IMACS has no CD matrix in the header if (!searchKeyValue(QStringList() << "ROTATORE", positionAngle)) { emit messageAvailable(name + " : Could not find ROTANGLE keyword, set to zero! CD matrix might have wrong orientation.", "warning"); emit warning(); positionAngle = 0.0; } cd11 = instData.pixscale / 3600.; cd12 = 0.; cd21 = 0.; cd22 = -instData.pixscale / 3600.; // Chips 1-4 are rotated by 180 degrees if (chip >= 4) rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle); else rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle+180.); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "LIRIS@WHT" || instData.name == "LIRIS_POL@WHT") { // LIRIS has no CD matrix in the header if (!searchKeyValue(QStringList() << "ROTSKYPA", positionAngle)) { emit messageAvailable(name + " : Could not find ROTSKYPA keyword, set to zero! CD matrix might have wrong orientation.", "warning"); emit warning(); positionAngle = 0.0; } cd11 = -1.*instData.pixscale / 3600.; cd12 = 0.0; cd21 = 0.0; cd22 = instData.pixscale / 3600.; rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "SUSI1@NTT") { cd11 = -3.611e-5; cd12 = 0.; cd21 = 0.; cd22 = 3.611e-5; cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instNameFromData == "GROND_OPT@MPGESO") { // GROND optical data has both the NIR and OPT CD matrices in the header. // With the current scheme, the NIR matrix in the HDU gets picked over // OPT matrix in the extension searchKeyValue(QStringList() << "CD1_1", cd11); searchKeyValue(QStringList() << "CD1_2", cd12); searchKeyValue(QStringList() << "CD2_1", cd21); searchKeyValue(QStringList() << "CD2_2", cd22); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instNameFromData == "GROND_NIR@MPGESO") { // just double tapping searchKeyValue(QStringList() << "J_CD1_1", cd11); searchKeyValue(QStringList() << "J_CD1_2", cd12); searchKeyValue(QStringList() << "J_CD2_1", cd21); searchKeyValue(QStringList() << "J_CD2_2", cd22); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "PFC_old@WHT") { cd11 = 6.55e-5; cd12 = 5.0e-7; cd21 = 5.0e-7; cd22 = -6.55e-5; cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "PISCO@LCO") { cd11 = -instData.pixscale / 3600.; cd12 = 0.; cd21 = 0.; cd22 = -instData.pixscale / 3600.; // headers appear unreliable (pixel scale wrong by a factor of two) /* searchKeyValue(QStringList() << "CD1_1", cd11); searchKeyValue(QStringList() << "CD1_2", cd12); searchKeyValue(QStringList() << "CD2_1", cd21); searchKeyValue(QStringList() << "CD2_2", cd22); // readout amplifiers are flipped, depending on chip if (chip == 1 || chip == 2) {cd11 *= -1.; cd21 *= -1.;} if (chip == 4 || chip == 7) {cd12 *= -1.; cd22 *= -1.;} if (chip == 5 || chip == 6) {cd11 *= -1.; cd21 *= -1.; cd12 *= -1.; cd22 *= -1.;} */ cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (individualFixDone) { cd11_card.resize(80, ' '); cd12_card.resize(80, ' '); cd21_card.resize(80, ' '); cd22_card.resize(80, ' '); headerWCS.append(cd11_card); headerWCS.append(cd12_card); headerWCS.append(cd21_card); headerWCS.append(cd22_card); headerTHELI.append(headerWCS); } return individualFixDone; } // Build the EXPTIME keyword void Splitter::buildTheliHeaderEXPTIME() { if (!successProcessing) return; // List of instruments that have separate DITs and NDITs QStringList nditInstruments = {"GSAOI@GEMINI", "GSAOI_CHIP1@GEMINI", "GSAOI_CHIP2@GEMINI", "GSAOI_CHIP3@GEMINI", "GSAOI_CHIP4@GEMINI", "HAWKI@VLT", "INGRID@WHT", "IRCS_HIGHRES@SUBARU", "IRCS_LOWRES@SUBARU", "ISAAC@VLT", "ISPI@CTIO", "LIRIS@WHT", "LIRIS_POL@WHT", "MOIRCS@SUBARU", "MOSFIRE@KECK", "NEWFIRM@CTIO", "NICS@TNG", "NIRC2@KECK", "NIRI@GEMINI", "PISCES@LBT", "SOFI@NTT", "VIRCAM@VISTA"}; // The following instruments also have DITs and NDITs, but they are coadded instead of coaveraged and thus can be treated normally: // MOIRCS QString exptimeKey; // Instruments for which we don't have to do anything special if (!nditInstruments.contains(instData.name)) { bool keyFound = searchKey("EXPTIME", headerDictionary.value("EXPTIME"), headerTHELI); if (!keyFound) { exptimeKey = "EXPTIME = 1.0"; exptimeKey.resize(80, ' '); headerTHELI.append(exptimeKey); emit messageAvailable(fileName + " : Could not determine keyword: EXPTIME, set to 1.0", "warning"); emit warning(); } return; } // Instruments (see list above) for which we have to determine the true total EXPTIME keyword, and rescale the data. // In THELI, EXPTIME always represents the total effective integration time. If images are averaged from several coadds, // they also need to be rescaled. float dit = -1.0; float ndit = -1.0; bool foundDIT = searchKeyValue(headerDictionary.value("DIT"), dit); bool foundNDIT = searchKeyValue(headerDictionary.value("NDIT"), ndit); // default values if failed if (!foundDIT) { emit messageAvailable(fileName + " : Could not determine keyword: DIT, set to 1.0", "warning"); dit = 1.0; } if (!foundNDIT) { emit messageAvailable(fileName + " : Could not determine keyword: NDIT, set to 1", "warning"); ndit = 1.0; } if (!foundDIT || !foundNDIT) { emit messageAvailable("This is a serious issue with data from "+instData.name+" .
The true exposure time is unknown."+ "You can continue, but a correct calibration of the stacked image is not guaranteed.", "warning"); emit warning(); } exptimeValue = dit*ndit; exptimeKey = "EXPTIME = "+QString::number(exptimeValue, 'f', 5); QString ditKey = "DIT = "+QString::number(dit, 'f', 5); QString nditKey = "NDIT = "+QString::number(int(ndit)); exptimeKey.resize(80, ' '); ditKey.resize(80, ' '); nditKey.resize(80, ' '); headerTHELI.append(exptimeKey); headerTHELI.append(ditKey); headerTHELI.append(nditKey); // Rescale the pixels. NDIT is actually an integer and must be >= 1. // The following cameras DO NOT average the NDITs but add them directly, hence we must not rescale them. // TODO: this list must be verified! QStringList directCoaddition = {"IRCS_HIGHRES@SUBARU", "IRCS_LOWRES@SUBARU", "ISPI@CTIO", "MOSFIRE@KECK", "NIRC2@KECK", "NIRI@GEMINI", "PISCES@LBT", "VIRCAM@VISTA"}; if (!directCoaddition.contains(instData.name)) { if (ndit > 1.) { for (auto &pixel : dataCurrent) pixel *= ndit; } } } // Build the DATE-OBS keyword void Splitter::buildTheliHeaderDATEOBS() { if (!successProcessing) return; if (individualFixDATEOBS()) return; bool found = false; // Loop over all possible dateobs keywords, and break once we found one that is valid. // This is different from the general strategy to go over all possible keyword variants and take the first one that exists for (auto &keyword : headerDictionary.value("DATE-OBS")) { dateObsValue = ""; searchKeyValue(QStringList() << keyword, dateObsValue); if (!dateObsValue.isEmpty() && checkFormatDATEOBS()) { found = true; break; } } // bool keyFound = searchKey("DATE-OBS", headerDictionary.value("DATE-OBS"), headerTHELI); // if (keyFound && checkFormatDATEOBS()) return; // Fallback: Try and reconstruct DATE-OBS keyword from other keywords // DATE-OBS has not been appended yet by searchKey() child function if format is wrong if (!found) { QString dateValue; QString timeValue; bool foundDATE = searchKeyValue(headerDictionary.value("DATE"), dateValue); bool foundTIME = searchKeyValue(headerDictionary.value("TIME"), timeValue); if (foundDATE && foundTIME) { if (timeValue.contains(" ")) timeValue.replace(" ",":"); // E.g. SITe_SWOPE@LCO has a time stamp without colons if (dateValue.contains("-") && timeValue.contains(":")) { dateObsValue = dateValue+"T"+timeValue; } else { // Construct a unique dummy DATE-OBS keyword, incremented by 0.1 seconds. #pragma omp critical { *dateObsIncrementor += 0.1; QString timeStamp = decimalSecondsToHms(*dateObsIncrementor); dateObsValue = "2020-01-01T"+timeStamp; } emit messageAvailable(fileName + " : Could not determine keyword: DATE-OBS, set to "+dateObsValue, "warning"); emit warning(); // dateObsValue = "2020-01-01T00:00:00.000"; // dateObsValid = false; } } } QString card = "DATE-OBS= '"+dateObsValue+"'"; card.resize(80, ' '); headerTHELI.append(card); } bool Splitter::individualFixDATEOBS() { bool individualFixDone = false; if (instData.name == "WHIRC@WIYN") { double mjdValue = 0; bool foundMJDOBS = searchKeyValue(headerDictionary.value("MJD-OBS"), mjdValue); // DATE-OBS has the start time of a sequence if (foundMJDOBS) { dateObsValue = mjdobsToDATEOBS(mjdValue); individualFixDone = true; } } if (instData.name == "PISCO@LCO") { // wrong order of DATE and DATEOBS keyword QString dateValue; QString timeValue; bool foundDATE = searchKeyValue(QStringList() << "DATEOBS", dateValue); bool foundTIME = searchKeyValue(QStringList() << "TELUT", timeValue); if (foundDATE && foundTIME) { if (dateValue.contains("-") && timeValue.contains(":")) { dateObsValue = dateValue+"T"+timeValue; } else { // Construct a unique dummy DATE-OBS keyword, incremented by 0.1 seconds. #pragma omp critical { *dateObsIncrementor += 0.1; QString timeStamp = decimalSecondsToHms(*dateObsIncrementor); dateObsValue = "2020-01-01T"+timeStamp; } emit messageAvailable(fileName + " : Could not determine keyword: DATE-OBS, set to "+dateObsValue, "warning"); emit warning(); } } individualFixDone = true; } if (individualFixDone) { QString card = "DATE-OBS= '"+dateObsValue+"'"; card.resize(80, ' '); headerTHELI.append(card); } return individualFixDone; } // Build the GAIN keyword void Splitter::buildTheliHeaderGAIN(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixGAIN(chip)) return; // normal cases chipGain = 1.0; if (!searchKeyValue(headerDictionary.value("GAIN"), chipGain)) { // if (instData.name != "GROND_NIR@MPGESO") { // GROND: gain determined in writeImageIndividual() if (instNameFromData != "GROND_NIR@MPGESO") { // GROND: gain determined in writeImageIndividual() emit messageAvailable(fileName + " : Could not determine keyword: GAIN, set to 1.0.", "warning"); emit warning(); } chipGain = 1.0; } // Consistency checks if (chipGain < 0.02 || chipGain > 30.) { emit messageAvailable(fileName + " : GAIN keyword outside plausible range (0.02-30 e-/ADU): " + QString::number(chipGain)+", set to 1.0.", "warning"); emit warning(); chipGain = 1.0; } QString card1 = "GAINORIG= "+QString::number(chipGain, 'f', 6) + " / Original gain in the raw data for this image"; QString card2 = "GAIN = 1.0 / ADUs were converted to e- in this image using GAINORIG"; card1.resize(80, ' '); card2.resize(80, ' '); headerTHELI.append(card1); headerTHELI.append(card2); gainForSaturation = chipGain; gain[chip] = chipGain; // used to convert the pixel data from ADU to electrons } bool Splitter::individualFixGAIN(int chip) { if (!successProcessing) return false; bool individualFixDone = false; chipGain = 1.0; if (instData.name == "HAWKI@VLT") { // https://www.eso.org/sci/facilities/paranal/instruments/hawki/inst.html if (chip == 0) chipGain = 1.705; if (chip == 1) chipGain = 1.870; if (chip == 2) chipGain = 1.735; if (chip == 3) chipGain = 2.110; individualFixDone = true; } if (instData.name == "SOFI@NTT") { // https://www.eso.org/sci/facilities/lasilla/instruments/sofi/inst/setup/Detector_characteristic.html chipGain = 5.3; individualFixDone = true; } if (instData.name == "NEWFIRM@KPNO_4m") { // https://www.noao.edu/ets/newfirm/documents/ORION_SCA_lab_tests_final.pdf chipGain = 7.6; // same for all 4 chips individualFixDone = true; } if (instData.name == "HDI@KPNO_0.9m") { // https://www.noao.edu/0.9m/observe/hdi/hdi_manual.html chipGain = 1.3; individualFixDone = true; } if (instData.name == "INOLA@INO") { // https://www.sbig.de/stf-8300/stf-8300-techdat.pdf chipGain = 0.37; individualFixDone = true; } if (instData.name == "WHIRC@WIYN") { // https://www.noao.edu/kpno/manuals/whirc/whirc.user.html chipGain = 3.4; individualFixDone = true; } else if (instData.name == "NIRI@GEMINI") { // https://www.gemini.edu/sciops/instruments/niri/imaging/detector-array chipGain = 12.3; // No gain keyword in FITS header individualFixDone = true; } /* * UPDATE: The gain in the LIRIS headers follows the actual gain setting, might not be accurate to the decimal, though. * (email from R. Karjalainen, ING, 2019-11-07) else if (instData.name == "LIRIS@WHT" || instData.name == "LIRIS_POL@WHT") { // http://www.ing.iac.es/astronomy/instruments/liris/detector.html chipGain = 3.6; // Wrong gain in header individualFixDone = true; } */ else if (instData.name == "MOIRCS_200807-201505@SUBARU") { // https://www.naoj.org/Observing/Instruments/MOIRCS/OLD/inst_detector_oldMOIRCS.html if (chip == 0) chipGain = 3.50; // Wrong in headers between August 2008 and April 2010 if (chip == 1) chipGain = 3.30; individualFixDone = true; } else if (instData.name.contains("WFI") && instData.name.contains("MPGESO")) { // http://www.ls.eso.org:8081/sci/facilities/lasilla/sciops/CCDs/WFI/qc_suite/plots/plot1.png if (chip == 0) chipGain = 1.99; // Does not have GAIN keywords for all detectors if (chip == 1) chipGain = 2.02; if (chip == 2) chipGain = 2.29; if (chip == 3) chipGain = 2.68; if (chip == 4) chipGain = 2.24; if (chip == 5) chipGain = 2.25; if (chip == 6) chipGain = 2.16; if (chip == 7) chipGain = 2.03; individualFixDone = true; } else if (instData.name == "DEIMOS_1AMP@KECK") { if (chip == 0) chipGain = 1.206; if (chip == 1) chipGain = 1.200; if (chip == 2) chipGain = 1.167; if (chip == 3) chipGain = 1.217; individualFixDone = true; } // multi-amp cameras where the gain is NOT available in the header else if (instData.name == "DEIMOS_2AMP@KECK") { // https://www2.keck.hawaii.edu/inst/obsdata/inst/deimos/www/detector_data/deimos_detector_data.html if (chip == 0) chipGain = 1.206; if (chip == 1) chipGain = 1.221; if (chip == 2) chipGain = 1.200; if (chip == 3) chipGain = 1.188; if (chip == 4) chipGain = 1.167; if (chip == 5) chipGain = 1.250; if (chip == 6) chipGain = 1.217; if (chip == 7) chipGain = 1.228; chipGain = harmonicGain(multiportGains); individualFixDone = true; } // multi-amp cameras where the gain is available in the header else if (instData.name == "SuprimeCam_200808-201705@SUBARU" || instData.name == "HSC@SUBARU" || instData.name.contains("GMOS-N-HAM") || instData.name.contains("GMOS-S-HAM") || instData.name.contains("SAMI") // have not added yet 1x1 confog || instData.name.contains("SOI@SOAR") || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "MOSAIC-III_4@KPNO_4m" || instData.name == "PISCO@LCO" ) { chipGain = harmonicGain(multiportGains); individualFixDone = true; } else if (instData.name == "FORS1_199904-200703@VLT" || instData.name == "FORS2_200004-200203@VLT") { // 1-port read mode or 4-port read mode? numReadoutChannels = 0; if (!searchKeyValue(QStringList() << "HIERARCH ESO DET OUTPUTS", numReadoutChannels)) { emit messageAvailable(baseName + " : Could not determine number of readout channels!", "error"); emit critical(); successProcessing = false; } else { if (numReadoutChannels == 4) { float gain1 = 0.0; float gain2 = 0.0; float gain3 = 0.0; float gain4 = 0.0; searchKeyValue(QStringList() << "HIERARCH ESO DET OUT1 CONAD", gain1); searchKeyValue(QStringList() << "HIERARCH ESO DET OUT2 CONAD", gain2); searchKeyValue(QStringList() << "HIERARCH ESO DET OUT3 CONAD", gain3); searchKeyValue(QStringList() << "HIERARCH ESO DET OUT4 CONAD", gain4); channelGains.clear(); channelGains << gain1 << gain2 << gain3 << gain4; chipGain = harmonicGain(channelGains); individualFixDone = true; } } } else if (instData.name.contains("NOTcam")) { float gain1 = 0.0; float gain2 = 0.0; float gain3 = 0.0; float gain4 = 0.0; searchKeyValue(QStringList() << "GAIN1", gain1); searchKeyValue(QStringList() << "GAIN2", gain2); searchKeyValue(QStringList() << "GAIN3", gain3); searchKeyValue(QStringList() << "GAIN4", gain4); channelGains.clear(); channelGains << gain1 << gain2 << gain3 << gain4; chipGain = harmonicGain(channelGains); individualFixDone = true; } if (individualFixDone) { QString card1 = "GAINORIG= "+QString::number(chipGain, 'f', 6) + " / Original gain in the raw data for this image"; QString card2 = "GAIN = 1.0 / ADUs were converted to e- in this image using GAINORIG"; card1.resize(80, ' '); card2.resize(80, ' '); headerTHELI.append(card1); headerTHELI.append(card2); if (instData.name.contains("GMOS-N-HAM") || instData.name.contains("GMOS-S-HAM") || instData.name.contains("SAMI") || instData.name.contains("SOI@SOAR") || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "MOSAIC-III_4@KPNO_4m" ) { gain[chip/numAmpPerChip] = chipGain; } // multichannel imagers have less chips than gain.length() ('chip' counts higher than gain.length() ) else if (instData.name == "PISCO@LCO") { gain[0] = chipGain; gain[1] = chipGain; } else { gain[chip] = chipGain; // not applied for e.g. SuprimeCam_200808-201705 and the others (why?) } gainForSaturation = chipGain; } return individualFixDone; } // Build the AIRMASS keyword void Splitter::buildTheliHeaderAIRMASS() { if (!successProcessing) return; bool keyFound = searchKey("AIRMASS", headerDictionary.value("AIRMASS"), headerTHELI); if (keyFound) return; // Fallback: Calculate airmass from RA, DEC, OBSLAT and LST bool foundLST = searchKeyLST(headerDictionary.value("LST")); if (!foundLST) lstValue = dateobsToLST(); double airmass = 1.0; if (foundLST && lstValue != 58849.0000) airmass = localSiderealTimeToAirmass(); // numeric value indicates that dateobs is unknown else airmass = 1.0; QString card = "AIRMASS = "+QString::number(airmass, 'f', 4); card.resize(80, ' '); headerTHELI.append(card); if (!foundLST || lstValue != 58849.0000) { if (dataType == "SCIENCE" || dataType == "SKY" || dataType == "STD") { emit messageAvailable(fileName + " : Could not determine keyword: AIRMASS, set to 1.0", "warning"); } } } void Splitter::buildTheliHeaderFILTER(int chip) { // Exceptions. Return if successful. if (individualFixFILTER(chip)) return; QStringList filterKeywordList; QStringList possibleKeyNames = headerDictionary.value("FILTER"); QList headers = {primaryHeader, extHeader}; bool keyFound = false; bool clearFound = false; bool darkFound = false; // Loop over headers for (auto &header : headers) { for (auto &possibleKey : possibleKeyNames) { for (auto &card : header) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString filterName = card.split("=")[1]; if (filterName.contains("'")) { // FILTER keyword is a string starting with a single quote filterName = filterName.split("'").at(1); } else { int slashPosition = filterName.lastIndexOf('/'); // TODO: the slash might occur further in front! In particular for HIERARCH ESO cards if (slashPosition > 12) filterName.truncate(slashPosition); } filterName = filterName.simplified(); // Clean the string filterName.remove("'"); filterName.remove("#"); filterName.remove("["); filterName.remove("]"); filterName.remove("("); filterName.remove(")"); filterName.remove("/"); filterName.remove(";"); filterName.remove("$"); filterName.remove(" "); // Skip if filter name suggests that the slot was empty if (filterName.contains("clear", Qt::CaseInsensitive) || filterName.contains("empty", Qt::CaseInsensitive) || filterName.contains("clr", Qt::CaseInsensitive) || filterName.contains("csl", Qt::CaseInsensitive) // MOIRCS || filterName.contains("hole", Qt::CaseInsensitive) // MOIRCS || filterName.contains("unavailable", Qt::CaseInsensitive) // SAMI || filterName.contains("open", Qt::CaseInsensitive)) { clearFound = true; continue; } // Skip if filter name suggests that a dark was taken if (filterName.contains("dark", Qt::CaseInsensitive) || filterName.contains("close", Qt::CaseInsensitive) || filterName.contains("blocked", Qt::CaseInsensitive)) { darkFound = true; continue; } // Seems we found a valid FILTER keyword filterKeywordList.append(filterName); keyFound = true; } } } } QString filterCard = ""; if (!keyFound && darkFound) filterCard = "FILTER = 'Dark'"; else if (!keyFound && !darkFound && clearFound) filterCard = "FILTER = 'Clear'"; else if (!keyFound && !darkFound && !clearFound) { if (dataType != "BIAS" && dataType != "DARK") { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: FILTER, set to 'Unknown'", "warning"); } filter = "Unknown"; filterCard = "FILTER = '"+filter+"'"; } else { filterKeywordList.removeDuplicates(); filter = filterKeywordList.join("+"); // Replace by short filter name (if mapped) QString replacement = filterDictionary.value(filter); if (!replacement.isEmpty()) filter = replacement; filterCard = "FILTER = '"+filter+"'"; } filterCard.resize(80, ' '); headerTHELI.append(filterCard); } bool Splitter::individualFixFILTER(int chip) { if (!successProcessing) return false; bool individualFixDone = false; QString filterCard = ""; if (instData.name == "PISCO@LCO") { if (chip == 0 || chip == 1) filter = "g"; if (chip == 2 || chip == 3) filter = "r"; if (chip == 4 || chip == 5) filter = "i"; if (chip == 6 || chip == 7) filter = "z"; filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { searchKeyValue(QStringList() << "BLUFILT", filter); filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { searchKeyValue(QStringList() << "REDFILT", filter); filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (individualFixDone) { filterCard.resize(80, ' '); headerTHELI.append(filterCard); } return individualFixDone; } bool Splitter::checkFormatDATEOBS() { // dateobs format: YYYY-MM-DDTHH:MM:SS.sss if (!dateObsValue.contains("T") || !dateObsValue.contains(":") || !dateObsValue.contains("-")) { return false; } QStringList list = dateObsValue.split("T"); QString date = list[0]; QString time = list[1]; QStringList datelist = date.split("-"); QStringList timelist = time.split(":"); if (datelist.length() != 3 || timelist.length() != 3) { return false; } return true; } QString Splitter::mjdobsToDATEOBS(double mjd) { // Code taken and adjusted from: // https://api.kde.org/4.12-api/kdeedu-apidocs/marble/html/astrolib_8cpp_source.html // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright : Gerhard HOLTKAMP 11-JAN-2012 long jd0 = long(mjd + 2400001.0); long b = long ((jd0 - 1867216.25) / 36524.25); // Gregorian calendar long c = jd0 + b - (b/4) + 1525; // Gregorian calendar long d = long ((c - 122.1) / 365.25); long e = 365 * d + (d/4); long f = long ((c - e) / 30.6001); int day = c - e - long(30.6001 * f); int month = f - 1 - 12 * (f / 14); int year = d - 4715 - ((7 + month) / 10); double hour = 24.0 * (mjd - floor(mjd)); QString date = QString::number(year)+"-"+QString::number(month)+"-"+QString::number(day)+"T"; QString time = decimalToDms(hour); return date+time; } double Splitter::dateobsToMJD() { if (!checkFormatDATEOBS()) { emit messageAvailable(fileName + " : Splitter::dateobsToMJD(): Invalid DATE-OBS format:" + dateObsValue + "Setting MJD-OBS to 58849.000000 (2020-01-01).
" + "Background modeling and proper motion correction will not work correctly.", "warning"); emit warning(); return 58849.000000; } QStringList list = dateObsValue.split("T"); QString date = list[0]; QString time = list[1]; QStringList datelist = date.split("-"); QStringList timelist = time.split(":"); double year = datelist[0].toDouble(); double month = datelist[1].toDouble(); double day = datelist[2].toDouble(); double hh = timelist[0].toDouble(); double mm = timelist[1].toDouble(); double ss = timelist[2].toDouble(); // Explanation: See http://aa.usno.navy.mil/faq/docs/JD_Formula.html // UT in decimal hours double ut = hh + mm / 60.0 + ss / 3600.0; double A = year * 367.0; double B = floor((month + 9.0) / 12.0); double C = floor(((year + B) * 7.0) / 4.0); double D = floor((275.0 * month) / 9.0); double E = day + 1721013.5 + (ut / 24.0); double F = (((100.0 * year) + month - 190002.5) >= 0) ? 1.0 : -1.0; double julian_date = A - C + D + E - (0.5 * F) + 0.5; double mjd = julian_date - 2400000.5; return mjd; } double Splitter::dateobsToLST() { if (!checkFormatDATEOBS()) { emit messageAvailable(fileName + " : Splitter::dateobsToMJD(): Invalid DATE-OBS format:" + dateObsValue + "Setting MJD-OBS to 58849.000000 (2020-01-01).
" + "Background modeling and proper motion correction will not work correctly.", "warning"); emit warning(); return 58849.000000; } QStringList list = dateObsValue.split("T"); QString date = list[0]; QString time = list[1]; QStringList datelist = date.split("-"); QStringList timelist = time.split(":"); double year = datelist[0].toDouble(); double month = datelist[1].toDouble(); double day = datelist[2].toDouble(); double hh = timelist[0].toDouble(); double mm = timelist[1].toDouble(); double ss = timelist[2].toDouble(); // Explanation: See http://www.xylem.f2s.com/kepler/index.html#top // UT in decimal hours double ut = hh + mm/60. + ss/3600.; // The integer and fractional days from J2000 double dwhole = 367 * year - (int)(7*(year+(int)((month+9)/12))/4) + (int)(275*month/9) + day - 730531.5; double dfrac = ut / 24.; double d = dwhole + dfrac; double lst = 100.46 + 0.985647*d + instData.obslon + 15.*ut; // LST must be between 0 and 360 degrees int idummy = (int)(lst/360.); if(lst > 0) lst -= (float)(idummy*360.); else lst -= (float)((idummy-1)*360.); // Convert to seconds lst = (lst/15.)*3600.; return lst; } double Splitter::localSiderealTimeToAirmass() { double LSTbegin = lstValue; double LSTmiddle = lstValue + 0.5 * exptimeValue; double LSTend = lstValue + exptimeValue; // double lst = lstValue * RAD; double hourangle_begin = (LSTbegin/240. - crval1) * rad; double hourangle_middle = (LSTmiddle/240. - crval1) * rad; double hourangle_end = (LSTend/240. - crval1) * rad; // The effective airmass is estimated using the 'mean airmass' estimator in // "Some Factors Affecting the Accuracy of Stellar Photometry with CCDs" (P. Stetson, DAO preprint, September 1988) double airmass_begin = calcAirmass(hourangle_begin); double airmass_middle = calcAirmass(hourangle_middle); double airmass_end = calcAirmass(hourangle_end); double airmass = (airmass_begin + 4.0*airmass_middle + airmass_end) / 6.0; return airmass; } // ahourangle is already in [rad] double Splitter::calcAirmass(double ahourangle) { double sh = sin(ahourangle); double ch = cos(ahourangle); double sd = sin(crval2 * rad); double cd = cos(crval2 * rad); double sp = sin(instData.obslat * rad); double cp = cos(instData.obslat * rad); double x = ch*cd*sp - sd*cp; double y = sh*cd; double z = ch*cd*cp + sd*sp; double zn = sqrt(x*x+y*y); double zf = zn/z; double zd = atan(zf); double seczm = 1.0 / (cos(std::min(1.52, zd))) - 1.0; // Convert zenith distance to airmass following // "R.H. Hardie in _Astronomical Techniques_ (W.A. Hiltner, ed.) (Chicago: U. Chicago Press), p. 180 (1962)." double airmass = 1.0 + seczm * (0.9981833 - seczm * (0.002875 + seczm * 0.008083)); return airmass; } THELI-3.1.3/src/tools/splitter_multiport.cc000066400000000000000000001321161417631501300206130ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "tools.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "../functions.h" #include "fitsio.h" #include #include #include #include // The functions below make a fork of the overscan / cropping part for detectors with multiple readout channels // Ultimately, this should become generic enough to also work with "normal" detectors /* void Splitter::pasteMultiPortDataSections(QVector dataSect) { if (!successProcessing) return; if (instData.name == "LIRIS_POL@WHT") { naxis1 = naxis1Raw; naxis2 = naxis2Raw; dataCurrent = dataRaw; return; } // The image that enters this function has the same geometry as the raw data, including all overscan areas. // New image geometry; here, naxis1/2 refers to the total size of the image (after pasting one or more readout channels) // This should match what is given in instrument.ini naxis1 = dataSect[1] - dataSect[0] + 1; naxis2 = dataSect[3] - dataSect[2] + 1; if (*verbosity > 1) emit messageAvailable(baseName + " : Cropping to data section, size = " + QString::number(naxis1)+"x"+QString::number(naxis2)+" pixel", "image"); dataCurrent.resize(naxis1*naxis2); // Loop over readout channels int numChannels = multiportOverscanDirections.length(); // the number of readout channels per detector for (int channel=0; channel section = {0, naxis1-1, 0, naxis2-1}; // all three channels at the same time. Cutting happens separately during writeImage(); multiportIlluminatedSections << section; multiportChannelSections << section; multiportGains << 1.0; individualFixDone = true; } if (instData.name == "SuprimeCam_200808-201705@SUBARU") { // contains 4 vertical data slices, separated by overscans, in a single FITS extension naxis1 = 2048; naxis2 = 4224; // NOTE: The y coordinates of the illuminated sections and overscan sections in the SuprimeCam raw data are wrong. // They are normally contained in keywords "S_EFMN11", "S_EFMX11", "S_EFMN12", "S_EFMX12" for channel 1, etc multiportOverscanDirections << "vertical" << "vertical" << "vertical" << "vertical"; multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN11", "S_OSMX11", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN21", "S_OSMX21", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN31", "S_OSMX31", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN41", "S_OSMX41", 1, naxis2Raw); /* multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN11", "S_EFMX11", "S_EFMN12", "S_EFMX12"); multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN21", "S_EFMX21", "S_EFMN22", "S_EFMX22"); multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN31", "S_EFMX31", "S_EFMN32", "S_EFMX32"); multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN41", "S_EFMX41", "S_EFMN42", "S_EFMX42"); */ int ymin = 49; // in pixel coords (not accounting for C++ indexing starting at 0) int ymax = 4273; // in pixel coords (not accounting for C++ indexing starting at 0) if (chip == 3 || chip == 4 || chip == 5 || chip == 8 || chip == 9) { ymin = 1; ymax = 4225; } multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN11", "S_EFMX11", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN21", "S_EFMX21", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN31", "S_EFMX31", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN41", "S_EFMX41", ymin, ymax); if (chip == 0 || chip == 1 || chip == 2 || chip == 6 || chip == 7) { multiportChannelSections << QVector({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); // These nunmbers are not directly accessible in the FITS headers multiportChannelSections << QVector({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); } else { multiportChannelSections << QVector({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); // reversed order in FITS headers multiportChannelSections << QVector({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); } float gainValue1 = 1.0; float gainValue2 = 1.0; float gainValue3 = 1.0; float gainValue4 = 1.0; searchKeyValue(QStringList() << "S_GAIN1", gainValue1); searchKeyValue(QStringList() << "S_GAIN2", gainValue2); searchKeyValue(QStringList() << "S_GAIN3", gainValue3); searchKeyValue(QStringList() << "S_GAIN4", gainValue4); multiportGains << gainValue1 << gainValue2 << gainValue3 << gainValue4; channelGains.clear(); channelGains << 1.0 << 1.0 << 1.0 << 1.0; // dummy; not used anywhere else for SuprimeCam_200808-201705 individualFixDone = true; } if (instData.name == "HSC@SUBARU") { // contains 4 vertical data slices, separated by overscans, in a single FITS extension naxis1 = 2048; naxis2 = 4224; // NOTE: The y coordinates of the illuminated sections and overscan sections in the SuprimeCam raw data are wrong. // They are normally contained in keywords "T_EFMN11", "T_EFMX11", "T_EFMN12", "T_EFMX12" for channel 1, etc multiportOverscanDirections << "vertical" << "vertical" << "vertical" << "vertical"; multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN11", "T_OSMX11", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN21", "T_OSMX21", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN31", "T_OSMX31", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN41", "T_OSMX41", 1, naxis2Raw); /* multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN11", "T_EFMX11", "T_EFMN12", "T_EFMX12"); multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN21", "T_EFMX21", "T_EFMN22", "T_EFMX22"); multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN31", "T_EFMX31", "T_EFMN32", "T_EFMX32"); multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN41", "T_EFMX41", "T_EFMN42", "T_EFMX42"); */ int ymin = 1; // in pixel coords (not accounting for C++ indexing starting at 0) int ymax = 4224; // in pixel coords (not accounting for C++ indexing starting at 0) multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN11", "T_EFMX11", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN21", "T_EFMX21", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN31", "T_EFMX31", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN41", "T_EFMX41", ymin, ymax); // if (chip == 0 || chip == 1 || chip == 2 || chip == 6 || chip == 7) { multiportChannelSections << QVector({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); // These numbers are not directly accessible in the FITS headers multiportChannelSections << QVector({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); // } // else { // multiportChannelSections << QVector({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); // reversed order in FITS headers // multiportChannelSections << QVector({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); // multiportChannelSections << QVector({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); // multiportChannelSections << QVector({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); // } float gainValue1 = 1.0; float gainValue2 = 1.0; float gainValue3 = 1.0; float gainValue4 = 1.0; searchKeyValue(QStringList() << "T_GAIN1", gainValue1); searchKeyValue(QStringList() << "T_GAIN2", gainValue2); searchKeyValue(QStringList() << "T_GAIN3", gainValue3); searchKeyValue(QStringList() << "T_GAIN4", gainValue4); multiportGains << gainValue1 << gainValue2 << gainValue3 << gainValue4; channelGains.clear(); channelGains << 1.0 << 1.0 << 1.0 << 1.0; // dummy; not used anywhere else for SuprimeCam_200808-201705 individualFixDone = true; } if (instData.name == "LIRIS_POL@WHT") { naxis1 = 1024; naxis2 = 1024; multiportOverscanDirections << "dummy"; QVector section = {0, naxis1-1, 0, naxis2-1}; // all four channels at the same time. Cutting happens separately during writeImage(); multiportIlluminatedSections << section; multiportChannelSections << section; multiportGains << 1.0; individualFixDone = true; } // All Hamamatsu Gemini GMOS configurations. Single channel in single FITS extension if (multiChannelMultiExt.contains(instData.name) && instData.name.contains("GMOS")) { int binning = 1; QString binString = ""; searchKeyValue(QStringList() << "CCDSUM", binString); if (binString.simplified() == "1 1") binning = 1; else if (binString.simplified() == "2 2") binning = 2; else if (binString.simplified() == "4 4") binning = 4; else { emit messageAvailable(fileName + ": Invalid binning encountered: "+binString.simplified(), "error"); emit critical(); successProcessing = false; return; } naxis1 = 2048 / binning; naxis2 = 4224 / binning; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates // for (auto §ion : multiportChannelSections) { // for (auto &it : section) it /= binning; // maapping unbinned pixel space to binned pixel space // } if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; if (instData.name == "GMOS-S-HAM@GEMINI" || instData.name == "GMOS-S-HAM_1x1@GEMINI" || instData.name == "GMOS-S-HAM_4x4@GEMINI") { // Accurate amplifier gains are not available in the GMOS FITS headers if (mjdobsValue < 57265.999988) { // before 2015-08-31 // WARNING: these are the LOW gain modes. High gain mode is hardly used if (chip == 0) gainValue = 1.626; else if (chip == 1) gainValue = 1.700; else if (chip == 2) gainValue = 1.720; else if (chip == 3) gainValue = 1.652; else if (chip == 4) gainValue = 1.739; else if (chip == 5) gainValue = 1.673; else if (chip == 6) gainValue = 1.691; else if (chip == 7) gainValue = 1.664; else if (chip == 8) gainValue = 1.613; else if (chip == 9) gainValue = 1.510; else if (chip == 10) gainValue = 1.510; else if (chip == 11) gainValue = 1.519; } else { // after 2015-08-31 if (chip == 0) gainValue = 1.834; else if (chip == 1) gainValue = 1.874; else if (chip == 2) gainValue = 1.878; else if (chip == 3) gainValue = 1.852; else if (chip == 4) gainValue = 1.908; else if (chip == 5) gainValue = 1.933; else if (chip == 6) gainValue = 1.840; else if (chip == 7) gainValue = 1.878; else if (chip == 8) gainValue = 1.813; else if (chip == 9) gainValue = 1.724; else if (chip == 10) gainValue = 1.761; else if (chip == 11) gainValue = 1.652; } } if (instData.name == "GMOS-N-HAM@GEMINI" || instData.name == "GMOS-N-HAM_1x1@GEMINI") { if (chip == 0) gainValue = 1.66; else if (chip == 1) gainValue = 1.63; else if (chip == 2) gainValue = 1.62; else if (chip == 3) gainValue = 1.57; else if (chip == 4) gainValue = 1.68; else if (chip == 5) gainValue = 1.65; else if (chip == 6) gainValue = 1.64; else if (chip == 7) gainValue = 1.68; else if (chip == 8) gainValue = 1.61; else if (chip == 9) gainValue = 1.63; else if (chip == 10) gainValue = 1.58; else if (chip == 11) gainValue = 1.65; } multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "SOI@SOAR") { naxis1 = 1024; naxis2 = 2048; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 2.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) gainValue = 2.0; else if (chip == 1) gainValue = 2.0; else if (chip == 2) gainValue = 2.0; else if (chip == 3) gainValue = 2.0; multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "DEIMOS_2AMP@KECK") { naxis1 = 2048; naxis2 = 2601; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector oscan = {1040,1110,0,2600}; // Bias section not present in header multiportOverscanSections << oscan; multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) gainValue = 1.206; if (chip == 1) gainValue = 1.221; if (chip == 2) gainValue = 1.200; if (chip == 3) gainValue = 1.188; if (chip == 4) gainValue = 1.167; if (chip == 5) gainValue = 1.250; if (chip == 6) gainValue = 1.217; if (chip == 7) gainValue = 1.228; multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { naxis1 = 2048; naxis2 = 4096; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector oscan = {1080,1150,0,4095}; // Bias section not present in header; Must respect 0-indexing explicitly multiportOverscanSections << oscan; multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 2.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) searchKeyValue(QStringList() << "CCDGN00", gainValue); if (chip == 1) searchKeyValue(QStringList() << "CCDGN01", gainValue); if (chip == 2) searchKeyValue(QStringList() << "CCDGN02", gainValue); if (chip == 3) searchKeyValue(QStringList() << "CCDGN03", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { if (chip == 0) { naxis1 = 1648; naxis2 = 2520; } if (chip == 2) { naxis1 = 1752; naxis2 = 2520; } int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector oscan; if (chip == 0) oscan = {1040,1100,0,4095}; // Bias section not present in header if (chip == 1) oscan = {650,710,0,4095}; // Bias section not present in header if (chip == 2) oscan = {750,810,0,4095}; // Bias section not present in header if (chip == 3) oscan = {1040,1100,0,4095}; // Bias section not present in header multiportOverscanSections << oscan; multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) searchKeyValue(QStringList() << "CCDGN01", gainValue); if (chip == 1) searchKeyValue(QStringList() << "CCDGN02", gainValue); if (chip == 2) searchKeyValue(QStringList() << "CCDGN03", gainValue); if (chip == 3) searchKeyValue(QStringList() << "CCDGN04", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "MOSAIC-II_16@CTIO") { naxis1 = 2048; naxis2 = 4096; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; searchKeyValue(QStringList() << "GAIN", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "PISCO@LCO") { naxis1 = 3092; naxis2 = 6147; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector oscan; oscan << 1547 << 1577 << 0 << 6146; QVector illum; illum << 0 << 1545 << 0 << 6146; multiportOverscanSections << oscan; multiportIlluminatedSections << illum; QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; searchKeyValue(QStringList() << "EGAIN", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "MOSAIC-III_4@KPNO_4m") { naxis1 = 4112; naxis2 = 4096; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; searchKeyValue(QStringList() << "GAIN", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "SAMI_2x2@SOAR") { naxis1 = 2048; naxis2 = 2056; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 2.1; // http://www.soartelescope.org/soar/sites/default/files/SAM/archive/sami-manual.pdf searchKeyValue(QStringList() << "GAIN", gainValue); if (gainValue == 0.) { if (chip == 0) gainValue = 2.10000; if (chip == 1) gainValue = 2.20456; if (chip == 2) gainValue = 2.09845; if (chip == 3) gainValue = 2.19494; } multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } // If any instrument-specific stuff happened above, then we do a consistency check if (individualFixDone) { // if (multiportGains.length() != multiportOverscanSections.length() // crashes GROND-NIR data if (multiportGains.length() != multiportIlluminatedSections.length()) { emit messageAvailable("Splitter::getMultiportInformation : Inconsistent number of channels for gain, overscan and data section: " + QString::number(multiportGains.length()) + " " + QString::number(multiportIlluminatedSections.length()), "error"); emit critical(); successProcessing = false; } } else { // What to do for detectors that are not split up by several readout channels and overscans naxis1 = dataSection[chip][1] - dataSection[chip][0] + 1; naxis2 = dataSection[chip][3] - dataSection[chip][2] + 1; // Append the overscan strips from the instrument.ini files, and padd the missing dimension QVector overscan; if (!overscanX[chip].isEmpty()) { overscan << overscanX[chip][0] << overscanX[chip][1] << 0 << naxis2Raw-1; multiportOverscanDirections << "vertical"; } if (!overscanY[chip].isEmpty()) { overscan << 0 << naxis1Raw-1 << overscanY[chip][0] << overscanY[chip][1]; multiportOverscanDirections << "horizontal"; } multiportOverscanSections << overscan; multiportIlluminatedSections << dataSection[chip]; // image section = data section minus the left and bottom overscan pixels (right and upper overscan pixels not counted) // QVector imageSection = {0, dataSection[chip][1] - dataSection[chip][0], 0, dataSection[chip][3] - dataSection[chip][2]}; QVector channelSection = {0, naxis1Raw - 1, 0, naxis2Raw - 1}; multiportChannelSections << channelSection; multiportGains << 1.0; // i.e. leave gain unchanged } } void Splitter::pasteMultiportIlluminatedSections(int chip) { if (!successProcessing) return; // NOTE: multiportGains[channel] does not contain a Vector, just a scalar. Pasting is done one amp at a time // Paste the data sections into a single image of dimensions naxis1, naxis2 if (!multiChannelMultiExt.contains(instData.name)) { dataCurrent.resize(naxis1*naxis2); // long k = 0; // the running 1D index in the pasted image int channel = 0; for (auto §ion : multiportIlluminatedSections) { if (section.length() != 4) continue; // skip wrong vertices, for whatever reason they might be here pasteSubArea(dataCurrent, dataRaw, multiportIlluminatedSections[channel], multiportGains[channel], naxis1, naxis2, naxis1Raw); ++channel; } } // Individual exceptions (currently: GMOS, SOI, MOSAIC-II only) else { int channel = 0; for (auto §ion : multiportIlluminatedSections) { if (section.length() != 4) continue; // skip wrong vertices, for whatever reason they might be here long offx = 0; long offy = 0; // detectors where the amps form two or more vertical stripes from left to right if (instData.name == "SOI@SOAR" || instData.name.contains("GMOS") || instData.name == "MOSAIC-II_16@CTIO") { offx = (chip % numAmpPerChip) * naxis1 / numAmpPerChip; offy = 0; } if (instData.name == "MOSAIC-III_4@KPNO_4m") { QVector ampsec; ampsec << extractVerticesFromKeyword("CCDSEC"); // unused if (chip == 0) {offx = naxis1 / 2; offy = 0;} if (chip == 1) {offx = 0; offy = 0;} if (chip == 2) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 3) {offx = 0; offy = naxis2 / 2;} if (chip == 4) {offx = naxis1 / 2; offy = 0;} if (chip == 5) {offx = 0; offy = 0;} if (chip == 6) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 7) {offx = 0; offy = naxis2 / 2;} if (chip == 8) {offx = 0; offy = naxis2 / 2;} if (chip == 9) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 10) {offx = 0; offy = 0;} if (chip == 11) {offx = naxis1/2; offy = 0;} if (chip == 12) {offx = 0; offy = naxis2 / 2;} if (chip == 13) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 14) {offx = 0; offy = 0;} if (chip == 15) {offx = naxis1 / 2; offy = 0;} } if (instData.name == "SAMI_2x2@SOAR") { QVector ampsec; ampsec << extractVerticesFromKeyword("CCDSEC"); //unused if (chip == 0) {offx = 0; offy = 0;} if (chip == 1) {offx = naxis1 / 2; offy = 0;} if (chip == 2) {offx = 0; offy = naxis2 / 2;} if (chip == 3) {offx = naxis1 / 2; offy = naxis2 / 2;} } if (instData.name == "DEIMOS_2AMP@KECK") { offy = 0; if (chip % 2 == 0) { offx = naxis1 / 2; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } if (chip % 2 == 1) { offx = 0; } } if (instData.name == "LRIS_BLUE@KECK") { offy = 0; if (chip % 2 == 0) { offx = 0; } if (chip % 2 == 1) { offx = naxis1 / 2; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } } if (instData.name == "LRIS_RED@KECK") { offy = 0; if (chip % 2 == 0) { offx = 0; } if (chip % 2 == 1) { offx = 1024; // HARDCODED, because the amplifier sections have unequal sizes!!! (so far, that's the only detector ever I have seen this) flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } } if (instData.name == "PISCO@LCO") { if (chip == 0) { offx = 0; offy = 0; } if (chip == 1) { offx = naxis1 / 2; offy = 0; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } if (chip == 2) { offx = naxis1 / 2; offy = -172; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } if (chip == 3) { offx = 0; offy = -172; } if (chip == 4) { offx = 0; offy = 150; flipData(dataRaw, "y", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "y", naxis1Raw, naxis2Raw); } if (chip == 5) { offx = naxis1 / 2; offy = 150; flipData(dataRaw, "xy", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "xy", naxis1Raw, naxis2Raw); } if (chip == 6) { offx = naxis1 / 2; offy = -70; flipData(dataRaw, "xy", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "xy", naxis1Raw, naxis2Raw); } if (chip == 7) { offx = 0; offy = -70; flipData(dataRaw, "y", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "y", naxis1Raw, naxis2Raw); } } pasteSubArea(dataPasted, dataRaw, multiportIlluminatedSections[channel], multiportGains[channel], offx, offy, naxis1, naxis2, naxis1Raw); ++channel; } if ( (chip+1) % numAmpPerChip == 0) { // all channels have been pasted. Transfer the data to dataCurrent. MEFpastingFinished = true; dataCurrent.swap(dataPasted); dataPasted.clear(); dataPasted.squeeze(); dataCurrent.squeeze(); } } } // paste a subarea 'sector' (xmin, xmax, ymin, ymax) from source image "dataS" to target image "dataT", // Offsets are calculated internally, assuming that data sections have equal sizes void Splitter::pasteSubArea(QVector &dataT, const QVector &dataS, const QVector §ion, const float corrFactor, const long nT, const long mT, const long nS) { long iminS = section.at(0); long imaxS = section.at(1); long jminS = section.at(2); long jmaxS = section.at(3); long dimS = dataS.length(); // S = source image long dimT = dataT.length(); // T = target image // The x- and y-offsets for the illuminated sections. Calculated by taking the lower x (or y) value, // and checking how many equally sized sections can fit (safe, as we have usually not more than 4 sections, and the overscan areas are comparatively small) long sizex = section.at(1) - section.at(0) + 1; // section x-size long sizey = section.at(3) - section.at(2) + 1; // section y-size long nsecx = section.at(0) / sizex; // number of sections found to the left, using integer division long nsecy = section.at(2) / sizey; // number of sections found below the botton, using integer division // if the offsets are relatively large, i.e. the detector is very large but only a small part is usually read out, then we need manual resets: if (instData.name == "WFCCD_WF4K_DUPONT@LCO") nsecy = 0; long offx = nsecx * sizex; // The offset for the current section in the pasted output geometry long offy = nsecy * sizey; // The offset for the current section in the pasted output geometry for (long jS=jminS; jS<=jmaxS; ++jS) { for (long iS=iminS; iS<=imaxS; ++iS) { long iT = offx+iS-iminS; long jT = offy+jS-jminS; long sIndex = iS+nS*jS; long tIndex = iT+nT*jT; if (!instData.name.contains("GROND") && !instData.name.contains("DUMMY")) { if (sIndex >= dimS || tIndex >= dimT) { qDebug() << tIndex << dimT << iminS << imaxS << jminS << jmaxS << sizex << sizey; emit messageAvailable("Inconsistent image geometry. " + instData.name + " not fully tested in THELI.", "error"); emit critical(); successProcessing = false; break; } } if (iT>=nT || iT<0 || jT>=mT || jT<0) continue; // don't paste pixels falling outside target area if (!instData.name.contains("DUMMY")) { dataT[tIndex] = dataS[sIndex] * corrFactor; // correcting for gain differences } } } } // paste a subarea 'sector' (xmin, xmax, ymin, ymax) from source image "dataS" to target image "dataT", // offsets dx and dy are given explicitly void Splitter::pasteSubArea(QVector &dataT, const QVector &dataS, const QVector §ion, const float corrFactor, const long offx, const long offy, const long nT, const long mT, const long nS) { long iminS = section[0]; long imaxS = section[1]; long jminS = section[2]; long jmaxS = section[3]; long dimS = dataS.length(); long dimT = dataT.length(); for (long jS=jminS; jS<=jmaxS; ++jS) { if (!successProcessing) break; for (long iS=iminS; iS<=imaxS; ++iS) { long iT = offx+iS-iminS; long jT = offy+jS-jminS; if (iT>=nT || iT<0 || jT>=mT || jT<0) continue; // don't paste pixels falling outside target area long sIndex = iS+nS*jS; long tIndex = iT+nT*jT; if (sIndex >= dimS || tIndex >= dimT) { emit messageAvailable("Inconsistent image geometry. " + instData.name + " not fully tested in THELI.", "error"); emit critical(); successProcessing = false; break; } dataT[tIndex] = dataS[sIndex] * corrFactor; // correcting for gain differences } } } // splitting "[xmin:xmax,ymin:ymax]" QVector Splitter::extractVertices(QString vertexString) { vertexString = vertexString.replace(":"," "); vertexString = vertexString.replace(","," "); vertexString = vertexString.replace("[",""); vertexString = vertexString.replace("]",""); vertexString = vertexString.replace("'",""); vertexString = vertexString.simplified(); QStringList list = vertexString.split(" "); QVector vertices; // for loop also works for one-dimensional vertices for (int i=0; i Splitter::extractVerticesFromKeyword(QString keyword) { QString section = ""; searchKeyValue(QStringList() << keyword, section); return extractVertices(section); } QVector Splitter::extractVerticesFromKeyword(QString keyword1, QString keyword2, QString keyword3, QString keyword4) { int value1 = 0; int value2 = 0; int value3 = 0; int value4 = 0; searchKeyValue(QStringList() << keyword1, value1); searchKeyValue(QStringList() << keyword2, value2); searchKeyValue(QStringList() << keyword3, value3); searchKeyValue(QStringList() << keyword4, value4); QVector vertices; vertices << value1 - 1 << value2 - 1 << value3 - 1 << value4 - 1; // The -1 accounts for C++ indexing starting at zero return vertices; } // For SuprimeCam_200808-201705, only QVector Splitter::extractReducedOverscanFromKeyword(QString keyword1, QString keyword2, int value3, int value4) { int value1 = 0; int value2 = 0; searchKeyValue(QStringList() << keyword1, value1); searchKeyValue(QStringList() << keyword2, value2); QVector vertices; vertices << value1 - 1 << value2 - 1 << value3 - 1 << value4 - 1; // The -1 accounts for C++ indexing starting at zero return vertices; } // For SuprimeCam_200808-201705, only QVector Splitter::extractReducedIlluminationFromKeyword(QString keyword1, QString keyword2, int value3, int value4) { int value1 = 0; int value2 = 0; searchKeyValue(QStringList() << keyword1, value1); searchKeyValue(QStringList() << keyword2, value2); QVector vertices; vertices << value1 - 1 << value2 - 1 << value3 - 1 << value4 - 1; // The -1 accounts for C++ indexing starting at zero return vertices; } void Splitter::updateMEFpastingStatus(int chip) { MEFpastingFinished = false; if (!multiChannelMultiExt.contains(instData.name)) { MEFpastingFinished = true; return; } // The following instruments store the multiple readout channels of their detectors in separate FITS extensions, and must be pasted back together: // Once the last channel has been read, we can paste the chips together if (instData.name.contains("GMOS")) { if ( (chip + 1) % numAmpPerChip == 0) MEFpastingFinished = true; // if (chip == 3 || chip == 7 || chip == 11) MEFpastingFinished = true; } // CHECK: I think SAMI and MOSAIC-III are missing here! if (instData.name == "SOI@SOAR" || instData.name == "DEIMOS_2AMP@KECK" || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "PISCO@LCO") { if ( (chip + 1) % numAmpPerChip == 0) MEFpastingFinished = true; } } THELI-3.1.3/src/tools/splitter_processingGeneric.cc000066400000000000000000001150331417631501300222240ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "tools.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "../functions.h" #include "fitsio.h" #include #include #include #include void Splitter::correctOverscan() { if (!cdw->ui->overscanCheckBox->isChecked()) return; if (multiportOverscanDirections.isEmpty()) return; int numOverscans = multiportOverscanSections.length(); // the number of overscan sections per detector int numDataSections = multiportChannelSections.length(); // the number of data sections per detector. A data section might have a horizontal and a vertical overscan // One overscan per data section // We keep track of the estimate of the overscan value per detector float overscanEffectiveVertical = 0.; float overscanEffectiveHorizontal = 0.; float overscanEffective = 0.; if (numOverscans == numDataSections) { for (int i=0; i &, const QVector &, long), const QVector &overscanXArea, const QVector &overscanYArea, const QVector vertices) { if (!successProcessing) return; if (!cdw->ui->overscanCheckBox->isChecked()) return; // Overscan correction is done only for optical CCDs if (instData.type != "OPT") return; long i, j, k; long n = naxis1Raw; long m = naxis2Raw; // Overscan correction is applied to a subregion of the detector (including the overscan itself!). // If the detector has a single readout port only (or we can ignore them), then the overscan applies to the full array. // Otherwise, to the subarray defined by 'vertices' long imin; long imax; long jmin; long jmax; if (vertices.isEmpty()) { imin = 0; imax = naxis1Raw; jmin = 0; jmax = naxis2Raw; } else { imin = vertices[0]; imax = vertices[1]; jmin = vertices[2]; jmax = vertices[3]; } // PART 1: Correct vertical overscan if (!overscanXArea.isEmpty()) { QVector spectral(overscanXArea[1]-overscanXArea[0]+1,0); QVector spatial(m,0); // extract representative line for (j=0; j(), 0); // spatialv[j] = straightMedianInline(spectralv); } if (*verbosity > 1) emit messageAvailable(baseName + " : Mean vertical overscan = " + QString::number(meanMask(spatial), 'f', 3), "image"); // subtract overscan for (i=imin; i spectral(overscanYArea[1]-overscanYArea[0]+1,0); QVector spatial(n,0); // extract representative line for (i=0; i(), 0); } // subtract overscan if (*verbosity > 1) emit messageAvailable(baseName + " : Mean horizontal overscan = " + QString::number(meanMask(spatial), 'f', 3), "image"); for (j=jmin; j &, const QVector &, long), const QVector &overscanArea, const QVector dataVertices, float &overscanEstimate) { if (!successProcessing) return; if (overscanArea.isEmpty()) return; long n = naxis1Raw; long m = naxis2Raw; overscanEstimate = 0.; QVector spectral(overscanArea[1]-overscanArea[0]+1,0); // select (xmin, xmax) from [xmin:xmax, ymin:ymax] QVector spatial(m,0); // Line by line correction if (combineFunction_ptr != nullptr) { // extract representative line for (long j=0; j(), 0); // spatialv[j] = straightMedianInline(spectralv); } overscanEstimate = meanMask(spatial); if (*verbosity > 1) emit messageAvailable(baseName + " : Mean vertical overscan = " + QString::number(overscanEstimate, 'f', 3), "image"); } // Global correction with constant value else { QVector tmp; tmp.reserve((overscanArea[1]-overscanArea[0]+1)*m); for (long j=0; j 1) emit messageAvailable(baseName + " : Global median overscan = " + QString::number(constOverscan, 'f', 1), "image"); for (long j=0; j &, const QVector &, long), const QVector &overscanArea, const QVector dataVertices, float &overscanEstimate) { if (!successProcessing) return; if (overscanArea.isEmpty()) return; long n = naxis1Raw; overscanEstimate = 0.; QVector spectral(overscanArea[3]-overscanArea[2]+1,0); // select (ymin, ymax) from [xmin:xmax, ymin:ymax] QVector spatial(n,0); // Line by line correction if (combineFunction_ptr != nullptr) { // extract representative line for (long i=0; i(), 0); } overscanEstimate = meanMask(spatial); if (*verbosity > 1) emit messageAvailable(baseName + " : Mean horizontal overscan = " + QString::number(meanMask(spatial), 'f', 3), "image"); } // Global correction with constant value else { QVector tmp; tmp.reserve((overscanArea[3]-overscanArea[2]+1)*n); for (long i=0; i 1) emit messageAvailable(baseName + " : Global median overscan = " + QString::number(constOverscan, 'f', 1), "image"); for (long i=0; i 1) emit messageAvailable(baseName + " : Applying mask ...", "image"); long i = 0; if (!instData.name.contains("GROND")) { for (auto &pixel : dataCurrent) { if (mask->globalMask[chip].at(i)) pixel = 0.; ++i; } } // Resolve a mask conflict (two different masks, but only one instrument can be selected at a time) else if (instNameFromData == "GROND_OPT@MPGESO" && instData.name == "GROND_NIR@MPGESO" && altMask != nullptr) { for (auto &pixel : dataCurrent) { if (altMask->globalMask[chip].at(i)) pixel = 0.; ++i; } } } // dataSect contains the exposed (desired) illuminated pixels, [min:max], starting counting at zero, // correctly converted from the camera.ini CUTON_X and SIZE_X parameterization void Splitter::cropDataSection(QVector dataSect) { if (!successProcessing) return; if (instData.name == "LIRIS_POL@WHT") { naxis1 = naxis1Raw; naxis2 = naxis2Raw; dataCurrent = dataRaw; return; } // new image geometry naxis1 = dataSect[1] - dataSect[0] + 1; naxis2 = dataSect[3] - dataSect[2] + 1; if (*verbosity > 1) emit messageAvailable(baseName + " : Cropping to data section, size = " + QString::number(naxis1)+"x"+QString::number(naxis2)+" pixel", "image"); dataCurrent.resize(naxis1*naxis2); dataCurrent.squeeze(); long k = 0; for (long j=dataSect[2]; j<=dataSect[3]; ++j) { for (long i=dataSect[0]; i<=dataSect[1]; ++i) { dataCurrent[k] = dataRaw[i+naxis1Raw*j]; ++k; } } // TODO /* int crpix1 = getKeyword("CRPIX1").toFloat() - dataSection[0]; int crpix2 = getKeyword("CRPIX2").toFloat() - dataSection[2]; updateKeywordInHeader("CRPIX1", QString::number(crpix1)); updateKeywordInHeader("CRPIX2", QString::number(crpix2)); */ // successProcessing = true; } void Splitter::correctNonlinearity(int chip) { if (!successProcessing) return; if (!MEFpastingFinished) return; if (!cdw->ui->nonlinearityCheckBox->isChecked()) return; // Leave if no correction polynomial is known if (nonlinearityCoefficients.isEmpty()) return; if (*verbosity > 1) emit messageAvailable(baseName + " : Nonlinearity correction ...", "image"); // Extract coefficients for the current chip QVector coeffs = nonlinearityCoefficients[chip]; // Apply nonlinearity correction for (auto &pixel : dataCurrent) { pixel = polynomialSum(pixel, coeffs); } // Update saturation value saturationValue = polynomialSum(saturationValue, coeffs); // Individual implementations // Average nonlinearity correction // http://instrumentation.obs.carnegiescience.edu/FourStar/Documents/FourStar_Documentation.pdf if (instData.name == "FourStar@LCO") { float A = 0.; // High gain if (channelGains[0] > 2.) { if (chip == 0) A = 1.203e-8; if (chip == 1) A = 1.337e-8; if (chip == 2) A = 1.157e-8; if (chip == 3) A = 1.195e-8; } // Low gain else { if (chip == 0) A = 5.344e-9; if (chip == 1) A = 7.514e-9; if (chip == 2) A = 3.645e-9; if (chip == 3) A = 5.923e-9; } for (auto &pixel : dataCurrent) { pixel = pixel * (1.+A*pow(pixel,1.5)); } saturationValue *= (1.+A*pow(saturationValue,1.5)); } // http://csp2.lco.cl/manuals/dup_dc_linearity.php if (instData.name == "Direct_2k_DUPONT@LCO") { QString speed = ""; searchKeyValue(headerDictionary.value("SPEED"), speed); float c1 = 1.0; float c2 = 0.0; float c3 = 0.0; float c4 = 0.0; if (speed == "Turbo") { c2 = 0.09907; c3 = -0.06151; c4 = 0.01522; } if (speed == "Fast") { c2 = 0.05022; c3 = -0.02814; c4 = 0.00733; } for (auto &pixel : dataCurrent) { float x = c1 + c2*(pixel/32000.0) + c3*pow(pixel/32000.0,2) + c4*pow(pixel/32000.0,3); pixel /= x; } float x = c1 + c2*(saturationValue/32000.0) + c3*pow(saturationValue/32000.0,2) + c4*pow(saturationValue/32000.0,3); saturationValue /= x; } // http://csp2.lco.cl/manuals/swo_nc_linearity.php (using mean values) // NOTE: linearity test page does not specify for which readout mode it applies if (instData.name == "Direct_4k_SWOPE@LCO") { float c1 = 1.0; float c2 = 0.0; float c3 = 0.0; if (chip == 0) { c2 = -0.03443; c3 = 0.006657; } if (chip == 1) { c2 = -0.01557; c3 = 0.003386; } if (chip == 2) { c2 = -0.01329; c3 = 0.003314; } if (chip == 3) { c2 = -0.01971; c3 = 0.004700; } for (auto &pixel : dataCurrent) { float x = c1 + c2*(pixel/32000.0) + c3*pow(pixel/32000.0,2); pixel /= x; } float x = c1 + c2*(saturationValue/32000.0) + c3*pow(saturationValue/32000.0,2); saturationValue /= x; } } void Splitter::convertToElectrons(int chip) { if (!successProcessing) return; if (!MEFpastingFinished) return; // Update saturation value // done in buildTheliHeaderGAIN(int chip) // saturationValue *= gain[chip]; // cameras with multiple readout channels AND different gain per channel (but no overscan pasted into the data section) // WARNING: ASSUMPTIONS: applies to the size defined in camera.ini if (numReadoutChannels > 1) { // qDebug() << channelGains; if (instData.name == "FORS1_199904-200703@VLT" || instData.name == "FORS2_200004-200203@VLT") { for (long j=0; j=1023 && j<=1023) pixel *= channelGains[1]; // lower right quadrant if (i<=1022 && j>=1024) pixel *= channelGains[2]; // upper left quadrant if (i>=1023 && j>=1024) pixel *= channelGains[3]; // upper right quadrant } } gainForSaturation = minVec_T(channelGains); // SATURATE keyword shall reflect lowest number at which saturation occurs } } // if (instData.name == "GROND_NIR@MPGESO") { if (instNameFromData == "GROND_NIR@MPGESO") { gain[chip] = 1.0; // Gain is fixed in writeImageIndividual(); saturationValue *= gainForSaturation; return; } if (instData.name == "SuprimeCam_200808-201705@SUBARU") { saturationValue *= gainForSaturation; return; } if (multiChannelMultiExt.contains(instData.name)) { // GMOS, SOI, MOSAIC-II_16@CTIO, etc saturationValue *= gainForSaturation; return; } saturationValue *= gainForSaturation; for (auto &pixel : dataCurrent) { pixel *= gain[chip]; } } // Calculate the effective gain for a detector with different readout channels. // When we divide the data by the flat field, the effective gain is the harmonic mean float Splitter::harmonicGain(QVector detectorGains) { float harmGain = 0.; for (auto &gain : detectorGains) { harmGain += 1./gain; } harmGain = float(detectorGains.length()) / harmGain; return harmGain; } float Splitter::polynomialSum(float x, QVector coefficients) { // Coefficients contains the coeffs of a polynomial, starting with the lowest term // e.g., for p(x) = c0 + c1*x + c2*x*x we have coefficients = [c0, c1, c2] float sum = 0.; int k = 0; for (auto & it : coefficients) { sum += it * pow(x, k); ++k; } return sum; } // IMPORTANT: xtalk correction assumes NO inter-chip crosstalk, and that the amplitudes are the same for all intra-chip crosstalk int Splitter::getNorXtalkMethod() { int xtalkMethod = -1; if (cdw->ui->normalxtalkCheckBox->isChecked()) { if (cdw->ui->xtalk_nor_2x2ToolButton->isChecked()) xtalkMethod = 1; if (cdw->ui->xtalk_nor_1x2ToolButton->isChecked()) xtalkMethod = 2; if (cdw->ui->xtalk_nor_2x1ToolButton->isChecked()) xtalkMethod = 3; } return xtalkMethod; } int Splitter::getRowXtalkMethod() { int xtalkMethod = -1.; if (cdw->ui->rowxtalkCheckBox->isChecked()) { if (cdw->ui->xtalk_row_2x2ToolButton->isChecked()) xtalkMethod = 4; if (cdw->ui->xtalk_row_1x2ToolButton->isChecked()) xtalkMethod = 5; if (cdw->ui->xtalk_row_2x1ToolButton->isChecked()) xtalkMethod = 6; if (cdw->ui->xtalk_col_2x2ToolButton->isChecked()) xtalkMethod = 7; if (cdw->ui->xtalk_col_1x2ToolButton->isChecked()) xtalkMethod = 8; if (cdw->ui->xtalk_col_2x1ToolButton->isChecked()) xtalkMethod = 9; } return xtalkMethod; } void Splitter::correctXtalk() { if (!successProcessing) return; if (!MEFpastingFinished) return; // Xtalk type bool doXtalkNor = cdw->ui->normalxtalkCheckBox->isChecked(); bool doXtalkRow = cdw->ui->rowxtalkCheckBox->isChecked(); if (!doXtalkNor && !doXtalkRow) return; // Xtalk Amplitudes xtalkNorAmpString = cdw->ui->normalxtalkAmplitudeLineEdit->text(); xtalkRowAmpString = cdw->ui->rowxtalkAmplitudeLineEdit->text(); if (xtalkNorAmpString.isEmpty() && xtalkRowAmpString.isEmpty()) return; if ( (doXtalkNor && xtalkNorAmpString.isEmpty()) || ((doXtalkRow && xtalkRowAmpString.isEmpty()))) { emit messageAvailable("Incomplete cross-talk input. The cross-talk type must be checked as well as an amplitude given.", "warning"); emit messageAvailable("Cross-talk correction will not take place", "warning"); emit warning(); return; } // Ok, proceed with xtalk correction xtalkNorAmp = xtalkNorAmpString.toFloat(); xtalkRowAmp = xtalkRowAmpString.toFloat(); xtalkKappa = 1e6; // No rejection in x-talk correction when doing collapse correction // Holds the pixel corrected data dataXcorr.fill(0, naxis1*naxis2); // Correct point xtalk xtalkNorMethod = getNorXtalkMethod(); if (xtalkNorMethod != -1 && *verbosity > 1) emit messageAvailable(baseName + " : Normal crosstalk correction ...", "image"); if (xtalkNorMethod == 1) xtalk_method1(); // 2x2 quadrants, point xtalk else if (xtalkNorMethod == 2) xtalk_method2(); // 1x2 quadrants, point xtalk, top half bottom half else if (xtalkNorMethod == 3) xtalk_method3(); // 2x1 quadrants, point xtalk, left half right half // Make the corrected data the current data if (xtalkNorMethod != -1) dataCurrent.swap(dataXcorr); // Correct row xtalk xtalkRowMethod = getRowXtalkMethod(); if (xtalkRowMethod != -1 && *verbosity > 1) emit messageAvailable(baseName + " : Row crosstalk correction ...", "image"); if (xtalkRowMethod == 4) xtalk_method4(); // 2x2 quadrants, row xtalk else if (xtalkRowMethod == 5) xtalk_method5(); // 1x2 quadrants, row xtalk, top half bottom half else if (xtalkRowMethod == 6) xtalk_method6(); // 2x1 quadrants, row xtalk, left half right half else if (xtalkRowMethod == 7) xtalk_method7(); // 2x2 quadrants, col xtalk else if (xtalkRowMethod == 8) xtalk_method8(); // 1x2 quadrants, col xtalk, top half bottom half else if (xtalkRowMethod == 9) xtalk_method9(); // 2x1 quadrants, col xtalk, left half right half // Make the corrected data the current data if (xtalkRowMethod != -1) dataCurrent.swap(dataXcorr); dataXcorr.clear(); dataXcorr.squeeze(); // if (method == 10) xtalk_method10(); // Multi-xtalk, HAWAII-2RGs (rudimentary implementation, not supported by the GUI) } // The crosstalk images. We subtract from each quadrant the other quadrants, scaled by the xtalk amplitude. // The amplitude is assumed to be the same for all quadrants void Splitter::xtalk_method1() { int n = naxis1; int m = naxis2; long i, j, ih, jh, il, jl; int xlow1 = 0; // 1 for a 1024x1024 chip int xlow2 = n/2-1; // 512 int xhigh1 = n/2; // 513 int xhigh2 = n-1; // 1024 int ylow1 = 0; // 1 int ylow2 = m/2-1; // 512 int yhigh1 = m/2; // 513 int yhigh2 = m-1; // 1024 for (j=0; j=xlow1 && i<=xlow2 && j>=ylow1 && j<=ylow2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[ih+n*j] + dataCurrent[i+n*jh] + dataCurrent[ih+n*jh]); // lr = ll + ul + ur if (i>=xhigh1 && i<=xhigh2 && j>=ylow1 && j<=ylow2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[il+n*j] + dataCurrent[il+n*jh] + dataCurrent[i+n*jh]); // ul = lr + ll + ur if (i>=xlow1 && i<=xlow2 && j>=yhigh1 && j<=yhigh2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[ih+n*jl] + dataCurrent[i+n*jl] + dataCurrent[ih+n*j]); // ur = lr + ul + ll if (i>=xhigh1 && i<=xhigh2 && j>=yhigh1 && j<=yhigh2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[i+n*jl] + dataCurrent[il+n*j] + dataCurrent[il+n*jl]); } } } void Splitter::xtalk_method2() { int n = naxis1; int m = naxis2; long i, j, jh, jl; int xlow1 = 0; // 1 int xhigh1 = n-1; // 1024 int ylow1 = 0; // 1 int ylow2 = m/2; // 513 int yhigh1 = m/2-1; // 512 int yhigh2 = m-1; // 1024 for (j=0; j=xlow1 && i<=xhigh1 && j>=ylow1 && j<=yhigh1) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[i+n*jh]; // fix upper quadrant if (i>=xlow1 && i<=xhigh1 && j>=ylow2 && j<=yhigh2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[i+n*jl]; } } } void Splitter::xtalk_method3() { int n = naxis1; int m = naxis2; long i, j, ih, il; int xlow1 = 0; // 1 int xlow2 = n/2; // 513 int xhigh1 = n/2-1; // 512 int xhigh2 = n-1; // 1024 int ylow1 = 0; // 1 int yhigh1 = m-1; // 1024 for (j=0; j=xlow1 && i<=xhigh1 && j>=ylow1 && j<=yhigh1) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[ih+n*j]; // fix right quadrant if (i>=xlow2 && i<=xhigh2 && j>=ylow1 && j<=yhigh1) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[il+n*j]; } } } void Splitter::xtalk_method4() { int n = naxis1; int m = naxis2; long i, j, ih, jh, t; int xlow2 = n/2; // 513 int ylow2 = m/2; // 513 QVector ll_input(n/2*m/2,0); QVector lr_input(n/2*m/2,0); QVector ul_input(n/2*m/2,0); QVector ur_input(n/2*m/2,0); t = 0; for (j=0; j mask(n/2*m/2,false); QVector ll_mean = collapse_x(ll_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); QVector lr_mean = collapse_x(lr_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); QVector ul_mean = collapse_x(ul_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); QVector ur_mean = collapse_x(ur_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); // ll = ll - xtalkRowAmp * mean(ll+lr+ul+ur) for (j=0; j bo_input(n*m/2,0); QVector up_input(n*m/2,0); t = 0; for (j=0; j maskLocal(n*m/2,false); QVector bo_mean = collapse_x(bo_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); QVector up_mean = collapse_x(up_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); // bo = bo - xtalkRowAmp * mean(bo+up) for (j=0; j le_input(n/2*m,0); QVector ri_input(n/2*m,0); t = 0; for (j=0; j maskLocal(n/2*m,false); QVector le_mean = collapse_x(le_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); QVector ri_mean = collapse_x(ri_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); // le = le - xtalkRowAmp * mean(le+ri) for (j=0; j ll_input(n/2*m/2,0); QVector lr_input(n/2*m/2,0); QVector ul_input(n/2*m/2,0); QVector ur_input(n/2*m/2,0); t = 0; for (j=0; j maskLocal(n/2*m/2,false); QVector ll_mean = collapse_y(ll_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); QVector lr_mean = collapse_y(lr_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); QVector ul_mean = collapse_y(ul_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); QVector ur_mean = collapse_y(ur_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); // ll = ll - xtalkRowAmp * mean(ll+lr+ul+ur) for (j=0; j bo_input(n*m/2,0); QVector up_input(n*m/2,0); t = 0; for (j=0; j maskLocal(n*m/2,false); QVector bo_mean = collapse_y(bo_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); QVector up_mean = collapse_y(up_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); // bo = bo - xtalkRowAmp * mean(bo+up) for (j=0; j le_input(n/2*m,0); QVector ri_input(n/2*m,0); t = 0; for (j=0; j maskLocal(n/2*m,false); QVector le_mean = collapse_y(le_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); QVector ri_mean = collapse_y(ri_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); // le = le - xtalkRowAmp * mean(le+ri) for (j=0; j h2_median(n*m,0); QVector h2_sample(xtalkNsection,0); if (xtalkDirection.compare("x") == 0) { width = m/xtalkNsection; for (j=0; j #include #include #include // This source file contains instrument-specific processing routines. // Mainly to deal with peculiarities of the data void Splitter::descrambleLiris() { if (!successProcessing) return; int n = naxis1Raw; // Must use Raw size because we trim it in polarimetry mode int m = naxis2Raw; QVector> image2D(n); QVector> image2Dmod(n); int i = 0; int j = 0; for(i=0; i #include #include #include #include // These routines do not query the FITS header itself, but rather the QStringList version // Retrieve the key and update the output header bool Splitter::searchKey(const QString &searchKeyName, const QStringList &possibleKeyNames, QStringList &outputHeader) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, primaryHeader, outputHeader); if (!inPrimaryHeader) inExtHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, extHeader, outputHeader); // bool inPrimaryHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, extHeader, outputHeader); // if (!inPrimaryHeader) inExtHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, primaryHeader, outputHeader); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the floating point value of a key, don't update output header void Splitter::searchKeyCRVAL(const QString searchKey, const QStringList &possibleKeyNames, QStringList &outputHeader) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, primaryHeader, outputHeader); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, extHeader, outputHeader); // bool inPrimaryHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, extHeader, outputHeader); // if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, primaryHeader, outputHeader); // Fallback: if (!inPrimaryHeader && !inExtHeader) { QString card; if (searchKey == "CRVAL1") card = "CRVAL1 = 0.0"; if (searchKey == "CRVAL2") card = "CRVAL2 = 0.0"; card.resize(80, ' '); outputHeader.append(card); } } // Retrieve the floating point value of a key, don't update output header bool Splitter::searchKeyLST(const QStringList &possibleKeyNames) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderLST(possibleKeyNames, primaryHeader); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderLST(possibleKeyNames, extHeader); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the int value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, int &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (possibleKeyNames.contains("NAMPS")) qDebug() << __func__ << fileName << possibleKeyNames << primaryHeader.length() << inPrimaryHeader << value; if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the floating point value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, float &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the double value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, double &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the QString value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, QString &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } bool Splitter::searchKeyInHeader(const QString &searchKey, const QStringList &possibleKeyNames, const QStringList &inputHeader, QStringList &outputHeader) { // TODO: enforce that numeric values are numeric, and string values have single quotes // some raw data don't obey this rule // TODO: preference to key in EXT if also found in PHDU, or the other way round? // Right now it will take the PHDU value if present there (because PHDU is searched first) bool keyFound = false; // Loop over list of possible key names to find match for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); keyFound = true; int slashPosition = keyValue.lastIndexOf('/'); // (can be -1 if not found, treated as 0 by truncate(), i.e. entire string is set to empty if (searchKey == "DATE-OBS") { if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); dateObsValue = keyValue.simplified(); if (!checkFormatDATEOBS()) break; // do not append wrong format to output header! dealing with this elsewhere } if (searchKey == "MJD-OBS") { if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); mjdobsValue = keyValue.simplified().toDouble(); } QString newCard = searchKey; // If input is numeric and has decimal comma, replace it with a decimal dot newCard.resize(8, ' '); // Keyword must be 8 chars long newCard.append("= "+keyValue); newCard.resize(80, ' '); // Header card must be 80 chars long outputHeader.append(newCard); // if (searchKey == "CD1_1" && possibleKey == "CDELT1") qDebug() << card << "\n" << keyValue << slashPosition << "\n" << newCard; break; } } if (keyFound) break; } return keyFound; } bool Splitter::searchKeyInHeaderCRVAL(const QString searchKey, const QStringList &possibleKeyNames, const QStringList &inputHeader, QStringList &outputHeader) { bool keyFound = false; // Loop over list of possible key names to find match for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // Isolate CRVAL value int slashPosition = keyValue.lastIndexOf('/'); if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); keyValue = keyValue.simplified(); // Fix format (sometimes we have 'HH MM SS' instead of 'HH:MM:SS') keyValue.replace(' ', ':'); // Convert to decimal format if necessary QString crval = keyValue; if (keyValue.contains(':')) { if (searchKey == "CRVAL1") crval = hmsToDecimal(keyValue); if (searchKey == "CRVAL2") crval = dmsToDecimal(keyValue); } // Some instruments store CRVAL1 in decimal hours, oh well ... if (possibleKey == "RA-HOURS" || instData.name == "SITe@TLS") { crval = QString::number(15.*crval.toDouble(), 'f', 12); } // And sometimes it may under- or overrun the [0,360] degree boundary if (searchKey == "CRVAL1") { if (crval.toDouble() > 360.) crval = QString::number(crval.toDouble()-360., 'f', 12); else if (crval.toDouble() < 0.) crval = QString::number(crval.toDouble()+360., 'f', 12); } if (searchKey == "CRVAL2") { if (crval.toDouble() > 90.) crval = "90.0"; else if (crval.toDouble() < -90.) crval = "-90.0"; } // The William Herschel Telescope has its own funny "apertures" ... if (instData.name.contains("@WHT") && !instData.name.contains("PF_QHY")) { double ra_off1 = 0.; double ra_off2 = 0.; double dec_off1 = 0.; double dec_off2 = 0.; QStringList ra1 = {"XAPNOM"}; QStringList ra2 = {"XAPOFF"}; QStringList dec1 = {"YAPNOM"}; QStringList dec2 = {"YAPOFF"}; searchKeyInHeaderValue(ra1, inputHeader, ra_off1); searchKeyInHeaderValue(ra2, inputHeader, ra_off2); searchKeyInHeaderValue(dec1, inputHeader, dec_off1); searchKeyInHeaderValue(dec2, inputHeader, dec_off2); if (searchKey == "CRVAL1") crval = QString::number(crval.toDouble() + ra_off1 + ra_off2, 'f', 12); if (searchKey == "CRVAL2") crval = QString::number(crval.toDouble() + dec_off1 + dec_off2, 'f', 12); } // GSAOI must apply offsets, too if (instData.name.contains("GSAOI")) { double ra_off = 0.; double dec_off = 0.; QStringList ra = {"RAOFFSET"}; QStringList dec = {"DECOFFSE"}; searchKeyInHeaderValue(ra, inputHeader, ra_off); searchKeyInHeaderValue(dec, inputHeader, dec_off); if (searchKey == "CRVAL1") { double dec_pointing = 0.; QStringList decpoint = {"DEC"}; searchKeyInHeaderValue(decpoint, inputHeader, dec_pointing); crval = QString::number(crval.toDouble() + ra_off / 3600. / cos(dec_pointing*rad), 'f', 12); } if (searchKey == "CRVAL2") crval = QString::number(crval.toDouble() + dec_off/3600., 'f', 12); } // Construct the key card QString newCard = searchKey; newCard.resize(8, ' '); // Keyword must be 8 chars long newCard.append("= "+crval); newCard.resize(80, ' '); // Header card must be 80 chars long outputHeader.append(newCard); keyFound = true; break; } } if (keyFound) break; } return keyFound; } bool Splitter::searchKeyInHeaderLST(const QStringList &possibleKeyNames, const QStringList &inputHeader) { bool keyFound = false; // Loop over list of possible key names to find match for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // Isolate LST value int slashPosition = keyValue.lastIndexOf('/'); if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); keyValue = keyValue.simplified(); // Fix format (sometimes we have 'HH MM SS' instead of 'HH:MM:SS') keyValue.replace(' ', ':'); // Convert to decimal format (decimal hours and then to seconds) // So far, I never found different units // TODO: check PANIC@LCO and CFH12K99@CFHT QString lst = keyValue; if (keyValue.contains(':')) { lst = dmsToDecimal(keyValue); // use dmstodecimal instead of hmstodecimal because we need LST in seconds } lstValue = 3600.*lst.toDouble(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // int version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, int &value) { bool keyFound = false; // Loop over possible keywords for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // We are looking for a numeric value: remove quotes, simplify white space keyValue.remove("'"); keyValue = keyValue.simplified(); // Split (/, and potential comment), take the first element value = keyValue.split(' ').at(0).toInt(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // float version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, float &value) { bool keyFound = false; // Loop over possible keywords for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // We are looking for a numeric value: remove quotes, simplify white space keyValue.remove("'"); keyValue = keyValue.simplified(); // Split (/, and potential comment), take the first element value = keyValue.split(' ').at(0).toFloat(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // double version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, double &value) { bool keyFound = false; // Loop over possible keywords for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // We are looking for a numeric value: remove quotes, simplify white space keyValue.remove("'"); keyValue = keyValue.simplified(); // Split (/, and potential comment), take the first element value = keyValue.split(' ').at(0).toDouble(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // QString version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, QString &value) { bool keyFound = false; // Loop over possible keywords // WARNING: Assume we look for DATE-OBS, and the header contains both DATE-OBS and DATE keywords. // DATE-OBS is found first and is assumed to be correct (compared to DATE) // If we loop first over the header, DATE would be taken if it appears first in the header for (auto &possibleKey : possibleKeyNames) { // Loop over header to find a match for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; // Correct header: string value enclosed in single quotes if (keyValue.contains("'")) { keyValue = keyValue.split("'").at(1); } else { int slashPosition = keyValue.lastIndexOf('/'); // TODO: the slash might occur further in front! In particular for HIERARCH ESO cards if (slashPosition > 12) keyValue.truncate(slashPosition); } keyValue.replace('/', '_'); // Some filter names contain a slash keyValue.remove("'"); // Remove potential quotes from string value keyValue = keyValue.simplified(); value = keyValue; keyFound = true; break; } } if (keyFound) break; } return keyFound; } void Splitter::to_EN_US(QString &keyName, QString &keyValue) { // If a key value, that can be potentially expressed as a decimal number, has a decimal comma, replace the comma with a decimal dot. // Actually, keyValue is everything following the "=" char in the header card, hence just replace the first comma before the / comment starts if (numericKeyNames.contains(keyName) && keyValue.contains(",")) { int commaPosition = keyValue.indexOf(','); int commentPosition = keyValue.indexOf('/'); // replace if no comment field, or if comma occurs before comment field starts if (commentPosition == -1 || commaPosition < commentPosition) { keyValue.replace(commaPosition, 1, '.'); commaDetected = true; } } } THELI-3.1.3/src/tools/swarpfilter.cc000066400000000000000000000610611417631501300171700ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include #include #include "swarpfilter.h" #include "../myimage/myimage.h" #include "../functions.h" #include #include #include SwarpFilter::SwarpFilter(QString coadddirname, QString kappaString, QString clustersizeString, QString borderwidthString, int maxCPU, int *verbose) { // Probably not needed, unless to case distinct linux and mac initEnvironment(thelidir, userdir); coaddDirName = coadddirname; nthreads = maxCPU; verbosity = verbose; if (!kappaString.isEmpty()) kappa = kappaString.toInt(); if (!borderwidthString.isEmpty()) maskWidth = borderwidthString.toInt(); if (!clustersizeString.isEmpty()) clusterSize = clustersizeString.toInt(); if (clusterSize > 9) clusterSize = 9; // upper limit coaddDir.setPath(coaddDirName); if (!coaddDir.exists()) { qDebug() << "QDEBUG: SwarpFilter(): Could not find coadd directory" << coaddDirName; return; } omp_init_lock(&lock); } void SwarpFilter::init() { // Collect information about the coadded image and the resampled images getImages(); getCoaddInfo(); getGeometries(); // RAM considerations getBlocksize(); // Set the size for the containers initStorage(); } SwarpFilter::~SwarpFilter() { omp_destroy_lock(&lock); } void SwarpFilter::freeMemoryVectors() { images.clear(); weights.clear(); naxis1.clear(); naxis2.clear(); crpix1.clear(); crpix2.clear(); sky.clear(); fluxscale.clear(); xoffset.clear(); yoffset.clear(); images.squeeze(); weights.squeeze(); naxis1.squeeze(); naxis2.squeeze(); crpix1.squeeze(); crpix2.squeeze(); sky.squeeze(); fluxscale.squeeze(); xoffset.squeeze(); yoffset.squeeze(); } void SwarpFilter::freeMemoryBlocks() { for (long i=0; i() QVector dummyMask; dummyMask.clear(); MyImage *myImage = new MyImage(coaddDirName, base+"resamp.fits", "", 0, dummyMask, verbosity); MyImage *myWeight = new MyImage(coaddDirName, base+"resamp.weight.fits", "", 0, dummyMask, verbosity); images.append(myImage); weights.append(myWeight); } emit messageAvailable("Including "+QString::number(num_images)+" images ...", "config"); } void SwarpFilter::getCoaddInfo() { if (!successProcessing) return; QFile coaddHead(coaddDirName+"/coadd.head"); if (!coaddHead.open(QIODevice::ReadOnly)) { emit messageAvailable("ERROR: SwarpFilter::getCoaddInfo(): "+coaddHead.fileName() + " " +coaddHead.errorString(), "error"); successProcessing = false; return; } QTextStream in(&coaddHead); while(!in.atEnd()) { QString line = in.readLine(); if (line.contains("NAXIS1 =")) coadd_naxis1 = line.split("=")[1].simplified().split(" ")[0].toLong(); if (line.contains("NAXIS2 =")) coadd_naxis2 = line.split("=")[1].simplified().split(" ")[0].toLong(); if (line.contains("CRPIX1 =")) coadd_crpix1 = line.split("=")[1].simplified().split(" ")[0].toFloat(); if (line.contains("CRPIX2 =")) coadd_crpix2 = line.split("=")[1].simplified().split(" ")[0].toFloat(); } coaddHead.close(); emit messageAvailable("coadd.head found ...", "config"); } void SwarpFilter::getGeometries() { if (!successProcessing) return; double crpix1tmp = 0.; double crpix2tmp = 0.; long naxis1tmp = 0; long naxis2tmp = 0; double skytmp = 0.; double fluxscaletmp = 0.; crpix1.reserve(num_images); crpix2.reserve(num_images); naxis1.reserve(num_images); naxis2.reserve(num_images); sky.reserve(num_images); fluxscale.reserve(num_images); for (auto &it : images) { if (!it->informSwarpfilter(naxis1tmp, naxis2tmp, crpix1tmp, crpix2tmp, skytmp, fluxscaletmp)) { // TODO: This error does not lead to an abort in the stack of swarp command threads. QString message = "SwarpFilter::loadGeometries(): One or more keywords not found in resampled images:\nNAXIS1, NAXIS2, CRPIX1, CRPIX2, SKYVALUE, FLXSCALE"; emit messageAvailable(message, "error"); emit critical(); successProcessing = false; return; } naxis1.append(naxis1tmp); naxis2.append(naxis2tmp); crpix1.append(crpix1tmp); crpix2.append(crpix2tmp); sky.append(skytmp * fluxscaletmp); // rescaled sky values (corrected for relative transparency) fluxscale.append(fluxscaletmp); xoffset.append(coadd_crpix1 - crpix1tmp); yoffset.append(coadd_crpix2 - crpix2tmp); } emit messageAvailable("Geometries of the resampled images loaded ...", "config"); } // The maximum number of lines that can be read without filling up the RAM void SwarpFilter::getBlocksize() { if (!successProcessing) return; long systemRAM = 1024 * get_memory(); // maxmimum memory used: 50% of the available RAM blocksize = 0.5 * systemRAM / (coadd_naxis1 * sizeof(float) * num_images * 2); blocksize = blocksize > coadd_naxis2 ? coadd_naxis2 : blocksize; // upper limit if (blocksize < 1) { emit messageAvailable("ERROR: SwarpFilter::getBlocksize(): Not enough memory available for SwarpFilter", "error"); return; } // TODO: introduce upper limit, like naxis2[i]? Variable between images. // What happens if larger than naxis2[i]? if (blocksize > 300) blocksize = 300; // upper limit (can probably be dropped after some testing) chunksize = coadd_naxis1 * blocksize; nblocks = long(coadd_naxis2 / blocksize + 1.); emit messageAvailable("Block size = "+QString::number(blocksize) + ", Number of blocks = "+QString::number(nblocks), "config"); } void SwarpFilter::initStorage() { if (!successProcessing) return; block_coadd_image.resize(num_images); block_coadd_index.resize(num_images); sky.resize(num_images); badpixindex.resize(num_images); for (long i=0; i presentImages; presentImages.reserve(num_images); if (*verbosity >= 2) emit messageAvailable("Processing block " + QString::number(block+1) + "/" + QString::number(nblocks)+" ...", "output"); // read a chunk of data from the images #pragma omp parallel num_threads(nthreads) { // two private temporary containers QVector resampledData; QVector resampledCoaddIndex; // loop over resampled images #pragma omp for for (long i=0; i> bpp; bpp.reserve(100000); QVector gooddata; // The pixel values of the images contributing to a coadded pixel QVector gooddataind; // The index of an image contributing to a coadded pixel gooddata.reserve(num_images); // maximally num_images will contribute to a coadded pixel gooddataind.reserve(num_images); #pragma omp for for (long l=0; l= 0) { // Negative if image does not overlap with current pixel float value = block_coadd_image[pi][pixpos]; if (value != 0.) { // If a pixel has value zero then it was most likely masked gooddata.append(value); // pixel value gooddataind.append(pi); // image index } } } long ngoodweight = gooddata.length(); // Number of pixels contributing to a coadded pixel long currentpixel = l + block*chunksize; identify_bad_pixels(gooddata, gooddataind, currentpixel, ngoodweight, bpp); gooddata.clear(); gooddataind.clear(); } #pragma omp critical (updateBadPixels) { updateBadPixelIndex(bpp); } } // Reset the block data. Not sure why this is necessary. Perhaps caused by swap()? for (long i=0; i> bpp) { if (!successProcessing) return; for (auto &pair : bpp) { badpixindex[pair.first].append(pair.second); } } //*************************************************************************************** // Load a section of one of the resampled images // (a block naxis1 wide and some rows high) //*************************************************************************************** bool SwarpFilter::get_coaddblock(const int index, const long block, QVector &resampledData, QVector &resampledCoaddIndex) { // index == current image long bbs0 = block * blocksize; long bbs1 = bbs0 + blocksize; // nothing to do if the image is entirely below or above the current coadd block if (yoffset[index] + naxis2[index] <= bbs0 || yoffset[index] >= bbs1) { return false; } // The image overlaps with the current coadd block // assume that the image covers the block entirely: long firstline2read = bbs0 - yoffset[index]; // we start counting at 0! long lastline2read = firstline2read + blocksize - 1; // we start counting at 0! // if the image does not cover the lower part of the block // but the upper part entirely if (firstline2read < 0 && yoffset[index] + naxis2[index] >= bbs1) { lastline2read = bbs1 - yoffset[index] - 1; firstline2read = 0; } // if the image does not cover the upper part of the block // but the lower part entirely if (yoffset[index] + naxis2[index] < bbs1 && yoffset[index] <= bbs0) { lastline2read = naxis2[index] - 1; firstline2read = bbs0 - yoffset[index]; } // if the image is entirely contained in the block // without touching its borders if (yoffset[index] > bbs0 && yoffset[index] + naxis2[index] < bbs1) { firstline2read = 0; lastline2read = naxis2[index] - 1; } int nsub = naxis1[index]; int msub = lastline2read - firstline2read + 1; float *data_in = new float[nsub*msub]; // Load the data sections; // One could load the weights too, but that would double the memory load for very little return // We later on reject image pixels with zero value; likely they have zero weight; what would be missed is manually masked areas, such as satellites. // But the algorithm is supposed to detect them anyway, so no harm done by skipping the weights. images[index]->loadDataSection(0, naxis1[index]-1, firstline2read, lastline2read, data_in); long l = 0; // the running index of the image long k = 0; // the running index of the coadd [0,chunksize) resampledData.reserve(naxis1[index]*(lastline2read-firstline2read+1)); // Contains valid data points, only resampledCoaddIndex.resize(coadd_naxis1*blocksize); // Must stretch over the entire chunksize for (auto &it: resampledCoaddIndex) it = -1; // Initialize with invalid index // Map the image pixels onto the coadded image block. // Save some CPU cycles and do array calculations outside the loop long xoff = xoffset[index]; long yoff = yoffset[index]; long nax1 = naxis1[index]; long nax2 = naxis2[index]; float fluxcorr = fluxscale[index]; for (long j=0; j= 0 && yi >= 0 && xi < nax1 && yi < nax2) { resampledData.append(data_in[l] * fluxcorr); resampledCoaddIndex[k] = l; ++l; } ++k; } } if (l==0) { emit messageAvailable("SwarpFilter:getCoaddBlock(): No overlap was found
" +images[index]->name + " : First line / last line: " + QString::number(firstline2read) + " " + QString::number(lastline2read), "error"); return false; } delete [] data_in; data_in = nullptr; return true; } //*************************************************************************************** // Identify the bad pixels in a stack //*************************************************************************************** void SwarpFilter::identify_bad_pixels(const QVector &gooddata, const QVector &gooddataind, const long ¤tpixel, const long &ngoodweight, QVector> &bpp) { if (!successProcessing) return; // no rejection if less than 2 pixels contributing to a coadded pixel if (ngoodweight < 2 ) return; float mean = 0.; float rms = 0.; float thresh = 0.; // we could determine ngoodweight from gooddata itself, but the length is already known // and thus it is cheaper to just take it as an argument // long ngoodweight = gooddata.length(); // NOTE: I tried to compare (it-mean)^2 against thresh*thresh // instead of fabs(it-mean) against thresh, to avoid the expensive sqrt(). // However, the overall performance gain is on the order of 2-3%, hence I drop this for code clarity // 2 pixels in the stack: use poisson rms estimated from sky noise if (ngoodweight == 2) { float sum = gooddata[0] + gooddata[1]; mean = 0.5 * sum; rms = sum + (sky[gooddataind[0]] + sky[gooddataind[1]]); if (rms > 0.) { thresh = sqrt(0.5 * rms); } else return; // no rejection of bad pixels } // 3-4 pixels in the stack: reject max pixel else if (ngoodweight <= 4) { stackfilter_rejectmax(gooddata, mean, rms); if (rms > 0.) { mean /= ngoodweight - 1; rms = sqrt(((ngoodweight - 1) / (ngoodweight - 2)) * (rms / (ngoodweight - 1) - mean * mean)); thresh = 6. * kappa / ngoodweight * rms; } else return; // no rejection of bad pixels } // 5 or more pixels in the stack: reject min and max pixel else { stackfilter_rejectminmax(gooddata, mean, rms); if (rms > 0.) { mean /= ngoodweight - 2; rms = sqrt(((ngoodweight - 2) / (ngoodweight - 3)) * (rms / (ngoodweight - 2) - mean * mean)); // adaptive rms threshold if (ngoodweight < 6) thresh = 6. * kappa / ngoodweight * rms; else thresh = kappa * rms; } else return; // no rejection of bad pixels } if (ngoodweight > 2) { long i=0; for (auto &it : gooddata) { if (fabs(it - mean) > thresh) { bpp.append(std::make_pair(gooddataind[i], currentpixel)); } ++i; } } else { long i=0; for (auto &it : gooddata) { if (fabs(it - mean) > thresh) { // reject pixel only if it is the brighter one if ((i == 0 && gooddata[0] > gooddata[1]) || (i == 1 && gooddata[1] > gooddata[0])) { bpp.append(std::make_pair(gooddataind[i], currentpixel)); } } ++i; } } } //*************************************************************************************** // ID the max value in the stack, reject it, and calculate meansq and rmssq //*************************************************************************************** void SwarpFilter::stackfilter_rejectmax(const QVector &gooddata, float &meanval, float &rmsval) { if (!successProcessing) return; float maxval = gooddata[0]; meanval = 0.; rmsval = 0.; for (auto &it : gooddata) { if (it > maxval) maxval = it; meanval += it; rmsval += it*it; } meanval -= maxval; rmsval -= (maxval*maxval); } //*************************************************************************************** // ID the min and max values in the stack, reject them, and calculate meansq and rmssq //*************************************************************************************** void SwarpFilter::stackfilter_rejectminmax(const QVector &gooddata, float &meanval, float &rmsval) { if (!successProcessing) return; float minval = gooddata[0]; float maxval = gooddata[0]; meanval = 0.; rmsval = 0.; for (auto &it : gooddata) { if (it < minval) minval = it; else if (it > maxval) maxval = it; meanval += it; rmsval += it*it; } meanval -= (minval + maxval); rmsval -= (minval*minval + maxval*maxval); } //************************************************************** void SwarpFilter::writeWeight() { if (!successProcessing) return; // cout << "This is thread " << args->th << endl; emit messageAvailable("Writing updated weight maps ...", "output"); progressStepSize = 34. / num_images; #pragma omp parallel for num_threads(nthreads) for (long i=0; i weight_out(n*m, 1); // 1 = pixel is good, 0 = pixel is bad QVector weight_cpy(n*m, 1); long s = 0; long t = 0; long nbadpix = badpixindex[i].size(); // mask all bad pixels found for (long j=yoffset[i]; j<(yoffset[i] + m); ++j) { if (t==nbadpix) break; for (long l=xoffset[i]; l<(xoffset[i] + n); ++l) { if (t==nbadpix) break; long k = l + coadd_naxis1 * j; // WARNING: THIS IS FAST, BUT ASSUMES A SORTED BADPIX INDEX! if (k == badpixindex[i][t]) { weight_out[s] = 0; if (clusterSize < 2) weight_cpy[s] = 0; ++t; } ++s; } } // NOTE: // There could be many more masked pixels in badpixindex[i] than visibly marked in the end, // if the clustersize is larger than 1. // mask only clusters consisting of at least 'clustersize' pixels if (clusterSize > 1) { // we ignore the 1 pixel wide border of the image for (long j=1; j= clusterSize) { for (long l=j-1; l<=j+1; ++l) { for (long o=k-1; o<=k+1; ++o) { weight_cpy[o+(l*n)] = weight_out[o+(l*n)]; } } } } } } // copy the vectors weight_out = weight_cpy; } // if a border of width 'width' pixels should be masked around a // bad pixel, too if (maskWidth > 0) { for (long j=0; j (m - 1) ? (m - 1) : jmW1; long maskcolmax = kmW1 > (n - 1) ? (n - 1) : kmW1; for (long l=masklinemin; l <= masklinemax; ++l) { for (long o=maskcolmin; o <= maskcolmax; ++o) { weight_out[o+(l*n)] = 0; } } } } } } QString outName = weights[i]->path + "/" + weights[i]->name; // Modify the resampled weight and write it weights[i]->readImage(outName); long k=0; for (auto &pixel : weights[i]->dataCurrent) { pixel *= weight_out[k]; ++k; } weights[i]->writeImage(outName); weights[i]->freeData(); #pragma omp atomic *progress += progressStepSize; emit progressUpdate(*progress); } } THELI-3.1.3/src/tools/swarpfilter.h000066400000000000000000000073241417631501300170340ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef SWARPFILTER_H #define SWARPFILTER_H #include "../instrumentdata.h" #include "../myimage/myimage.h" #include #include #include #include class SwarpFilter : public QObject { Q_OBJECT public: SwarpFilter(QString coadddirname, QString kappaString, QString clustersizeString, QString borderwidthString, int maxCPU, int *verbose); ~SwarpFilter(); float *progress = nullptr; void runCosmicFilter(); void init(); signals: void messageAvailable(QString message, QString type); void progressUpdate(float progress); void critical(); private: omp_lock_t lock; float progressStepSize = 0; int nthreads = 1; bool successProcessing = true; QVector images; QVector weights; long coadd_naxis1 = 0; long coadd_naxis2 = 0; float coadd_crpix1 = 0; float coadd_crpix2 = 0; long num_images = 0; // Number of resampled images float kappa = 4.0; // Detection threshold (outliers in units of sigma) int clusterSize = 1; // Minimum size of a cluster of bad pixels to trigger masking int maskWidth = 0; // Width of an extra border around a detected bad pixel cluster long blocksize = 0; // Number of lines read at a time long chunksize = 0; // Number of pixels analysed in one step long nblocks = 0; // The total number of blocks to process QVector naxis1; QVector naxis2; QVector crpix1; // CRPIX is integer if stacked with swarp QVector crpix2; // CRPIX is integer if stacked with swarp QVector fluxscale; QVector sky; // rescaled sky values (corrected for relative transparency by 'fluxscale') QVector xoffset; // number of pixels between the left border of coadd.fits and the resampled image QVector yoffset; // number of pixels between the lower border of coadd.fits and the resampled image QVector< QVector > badpixindex; QVector< QVector > block_coadd_index; QVector< QVector > block_coadd_image; QDir coaddDir; QString coaddDirName = ""; QString thelidir; QString userdir; int *verbosity; void freeMemoryBlocks(); void freeMemoryVectors(); void getCoaddInfo(); void getGeometries(); void getImages(); void getBlocksize(); bool get_coaddblock(const int index, const long block, QVector &resampledData, QVector &resampledCoaddIndex); void identify_bad_pixels(const QVector &gooddata, const QVector &gooddataind, const long ¤tpixel, const long &ngoodweight, QVector> &bpp); void initStorage(); void stackfilter_rejectmax(const QVector &gooddata, float &meanval, float &rmsval); void stackfilter_rejectminmax(const QVector &gooddata, float &meanval, float &rmsval); void updateBadPixelIndex(const QVector > bpp); void writeWeight(); }; #endif // SWARPFILTER_H THELI-3.1.3/src/tools/tools.cc000066400000000000000000000762431417631501300157760ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "tools.h" #include "instrumentdata.h" #include "../functions.h" #include "../myimage/myimage.h" #include #include #include #include // Get the max size of a mosaic-ed exposure void getBinnedSize(const instrumentDataType *instData, const QVector> Tmatrices, int &n_bin, int &m_bin, int binFactor, int &xminOffset, int &yminOffset) { // The extreme vertices of a mosaic-ed image QVector xLimits; QVector yLimits; for (int chip=0; chipnumChips; ++chip) { if (instData->badChips.contains(chip)) continue; QVector T = Tmatrices[chip]; int x0 = -instData->crpix1[chip] + 0; int x1 = -instData->crpix1[chip] + instData->sizex[chip]; int y0 = -instData->crpix2[chip] + 0; int y1 = -instData->crpix2[chip] + instData->sizey[chip]; // Push the x and y coords of the four corners xLimits.push_back(T[0]*x0 + T[2]*y0); // lower left xLimits.push_back(T[0]*x1 + T[2]*y0); // lower right xLimits.push_back(T[0]*x0 + T[2]*y1); // upper left xLimits.push_back(T[0]*x1 + T[2]*y1); // upper right yLimits.push_back(T[1]*x0 + T[3]*y0); // lower left yLimits.push_back(T[1]*x1 + T[3]*y0); // lower right yLimits.push_back(T[1]*x0 + T[3]*y1); // upper left yLimits.push_back(T[1]*x1 + T[3]*y1); // upper right } // We need these for later use outside this function xminOffset = minVec_T(xLimits) / binFactor; yminOffset = minVec_T(yLimits) / binFactor; // The size of the binned image, with a safety margin of 10 pixels on each side n_bin = (maxVec_T(xLimits) - minVec_T(xLimits)) / binFactor + 20; m_bin = (maxVec_T(yLimits) - minVec_T(yLimits)) / binFactor + 20; } // Remove the plate scale and position angle component from a CD matrix // (required to create binned images) QVector CDmatrixToTransformationMatrix(QVector CD, QString instName) { if (instName != "WFC@INT" && instName != "WFC_2x2@INT") rotateCDmatrix(CD, 0.); double pscale = sqrt(CD[0]*CD[0] + CD[2]*CD[2]); QVector T; T.push_back(round(CD[0]/pscale)); T.push_back(round(CD[1]/pscale)); T.push_back(round(CD[2]/pscale)); T.push_back(round(CD[3]/pscale)); if (instName != "WFC@INT" && instName != "WFC_2x2@INT") { // Take out any flips. Only rotations are allowed for binned mosaics if (T[0] == -1 && T[3] == 1) T[0] = 1; else if (T[0] == 1 && T[3] == -1) T[3] = 1; else if (T[1] == -1 && T[2] == 1) T[1] = 1; else if (T[1] == 1 && T[2] == -1) T[2] = 1; } return T; } // Rotate a CD matrix to a new position angle // input angle in [deg] void rotateCDmatrix(QVector &CD, float pa_new) { double cd11 = CD[0]; double cd12 = CD[1]; double cd21 = CD[2]; double cd22 = CD[3]; double rad = 3.1415926535 / 180.; // is the matrix flipped (det(CD) > 0 if flipped) double det = cd11*cd22 - cd12*cd21; double f11; if (det < 0) f11 = 1.; else f11 = -1.; double f12 = 0.; double f21 = 0.; double f22 = 1.; // unflip the matrix matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22); // rotate the matrix to the new position angle // the current position angle of the CD matrix double pa_old = posangle(CD); // in [deg] double pa_diff = rad * (pa_new - pa_old); matrixMult_T(cos(pa_diff), -sin(pa_diff), sin(pa_diff), cos(pa_diff), cd11, cd12, cd21, cd22); // flip the matrix matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22); CD[0] = cd11; CD[1] = cd12; CD[2] = cd21; CD[3] = cd22; } // Get the position angle of a CD matrix [deg] float posangle(const QVector CD) { double cd11 = CD[0]; double cd12 = CD[1]; double cd21 = CD[2]; double cd22 = CD[3]; // the pixel scale double pscale1 = sqrt(cd11 * cd11 + cd21 * cd21); double pscale2 = sqrt(cd12 * cd12 + cd22 * cd22); // take out the pixel scale cd11 /= pscale1; cd12 /= pscale2; cd21 /= pscale1; cd22 /= pscale2; // sqrt(CD elements) is very close to one, but not perfectly // as coordinate system is not necessarily orthogonal (shear + contraction) double nfac1 = sqrt(cd11 * cd11 + cd21 * cd21); double nfac2 = sqrt(cd12 * cd12 + cd22 * cd22); // make sure sqrt(CD elements) = 1, // so that we can do the inverse trig functions cd11 /= nfac1; cd21 /= nfac1; cd12 /= nfac2; cd22 /= nfac2; // due to flipping the rotation angle is ambiguous. // possibly, the following could be simplified with det(CD), // but at the moment I don't see how to identify the additional 2*PI easily double pa; double PI = 3.1415926535; // normal if (cd11 < 0 && cd12 <= 0 && cd21 <= 0 && cd22 > 0) pa = acos(-cd11); // 0 <= phi < 90 else if (cd11 >= 0 && cd12 < 0 && cd21 < 0 && cd22 <= 0) pa = acos(-cd11); // 90 <= phi < 180 else if (cd11 > 0 && cd12 >= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(-cd11); // 180 <= phi < 270 else if (cd11 <= 0 && cd12 > 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(-cd11); // 270 <= phi < 360 // flipped else if (cd11 >= 0 && cd12 >= 0 && cd21 <= 0 && cd22 >= 0) pa = acos(cd11); // 0 <= phi < 90 else if (cd11 < 0 && cd12 > 0 && cd21 < 0 && cd22 < 0) pa = acos(cd11); // 90 <= phi < 180 else if (cd11 < 0 && cd12 <= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(cd11); // 180 <= phi < 270 else if (cd11 >= 0 && cd12 < 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(cd11); // 270 <= phi < 360 else { // we are very likely close to 0, 90, 180 or 270 degrees, and the CD matrix is slightly non-orthogonal. // In this case, lock onto 0, 90, 180 or 270 degrees. Otherwise, exit with an error. double cd11cd12 = fabs(cd11/cd12); double cd22cd21 = fabs(cd22/cd21); if (cd11cd12 > 20. && cd22cd21 > 20.) { if (cd11 > 0. && cd22 > 0.) pa = 0.*PI/2.; if (cd11 < 0. && cd22 > 0.) pa = 0.*PI/2.; if (cd11 > 0. && cd22 < 0.) pa = 2.*PI/2.; if (cd11 < 0. && cd22 < 0.) pa = 2.*PI/2.; } else if (cd11cd12 < 0.05 && cd22cd21 < 0.05) { if (cd12 > 0. && cd21 < 0.) pa = 1.*PI/2.; if (cd12 < 0. && cd21 < 0.) pa = 1.*PI/2.; if (cd12 > 0. && cd21 > 0.) pa = 3.*PI/2.; if (cd12 < 0. && cd21 > 0.) pa = 3.*PI/2.; } else { qDebug() << "Tools::posangle(): ERROR: Could not determine position angle from CD matrix!"; pa = 0.; } } double rad = PI / 180.; return pa / rad; } // Calculate binned image (using median filter) void binData(const QVector &data, QVector &dataBinned, const int n, const int nb, const int mb, const int binX, const int binY) { long bsq = binX * binY; QVector chunk(bsq,0); // Do the binning for (long j=0; j &data, QVector &dataBinned, const int n, const int nb, const int mb, const int binX, const int binY) { long bsq = binX * binY; QVector chunk(bsq,0); // Do the binning for (long j=0; j=bsq) qDebug() << "error1" << k << bsq; if (it+n*jt >= data.length()) qDebug() << "error2" << it << n << jt << it+n*jt << data.length(); chunk[k] = data[it+n*jt]; ++k; } } // Median filter dataBinned[i+nb*j] = meanMask(chunk); } } } // Map an individual binned image onto a global output image, using // the transformation matrix void mapBinnedData(QVector &dataBinnedGlobal, const QVector &dataBinnedIndividual, const QVector T, const int nGlobal, const int mGlobal, const int nInd, const int mInd, const long crpix1, const long crpix2, const int xminOffset, const int yminOffset, const QString instName) { // Transformation matrix, derived from CD matrix, for relative positioning int T0 = T[0]; int T1 = T[1]; int T2 = T[2]; int T3 = T[3]; for (int j=0; j= nGlobal) iBin = nGlobal - 1; if (jBin >= mGlobal) jBin = mGlobal - 1; if (iBin < 0) iBin = 0; if (jBin < 0) jBin = 0; // if (!instName.contains("MOIRCS")) { // dataBinnedGlobal[iBin+nGlobal*jBin] = dataBinnedIndividual[i+nInd*j]; // } // else { // "Adding" instead of replacing. MOIRCS detectors are partially masked and these areas // do overlap because of the beam splitter (masking valid pixels) // And that holds for quite a few other others as well, e.g. LRIS@KECK, so let's do it like this by default dataBinnedGlobal[iBin+nGlobal*jBin] += dataBinnedIndividual[i+nInd*j]; // } } } } QVector collapse_x(QVector &data, const QVector &globalMask, QVector &objectMask, const float kappa, const long n, const long m, const QString returnMode) { long i, j; int iterMax = 5; // average columns / rows QVector row; QVector col; row.reserve(n); col.reserve(m); // Object mask can be empty if defect detection is the first step after launching the GUI if (objectMask.isEmpty()) objectMask.fill(false, n*m); // extract representative line for (j=0; j collapsed(n*m); for (i=0; i(); // return value ignored. Updating data directly } } // Keeping a functor version as comments for future reference QVector collapse_y(QVector &data, const QVector &globalMask, QVector &objectMask, // float (*statisticsMode)(QVector, float, int), const float kappa, const long n, const long m, const QString returnMode) { long i, j; int iterMax = 5; // average columns / rows QVector row; QVector col; row.reserve(n); col.reserve(m); if (objectMask.isEmpty()) objectMask.fill(false, n*m); // extract representative line for (i=0; i collapsed(n*m); for (j=0; j(); // return value ignored. Updating data directly } } // collapse along vhhv (vertical, horizontal, horizontal, // vertical readout quadrants) or hvvh, hhhh, vvvv directions QVector collapse_quad(QVector &data, const QVector &globalMask, QVector &objectMask, const float kappa, const long n, const long m, const QString direction, const QString returnMode) { long i, j; if (n % 2 != 0 || m % 2 != 0) { qDebug() << "ERROR: image must have even numbered dimensions for this operation!\n"; qDebug() << " Dimensions: " << n << "x" << m; return QVector(); } long n1 = 0; long m1 = 0; long nh = n/2; long mh = m/2; QVector quadrant(nh*mh, 0); QVector collquad(nh*mh, 0); QVector collapsed2D(n*m, 0); QVector globalMaskquad(nh*mh, false); QVector objectMaskquad(nh*mh, false); if (objectMask.isEmpty()) objectMask.fill(false, n*m); // do the four quadrants long loop = 0; while (loop <= 3) { // the four quadrants // lower left if (loop == 0) { n1 = 0; m1 = 0; } // lower right if (loop == 1) { n1 = nh; m1 = 0; } // upper left if (loop == 2) { n1 = 0; m1 = mh; } // upper right if (loop == 3) { n1 = nh; m1 = mh; } // copy the quadrant and the mask for (j=0; j(); } } // Sort a 2D QVector by its first element // UNUSED; implemented explicitly in function void sort2DVector(QVector> &data) { std::sort(data.begin(), data.end(), [](const QVector& left, const QVector& right)->bool { // if (left.empty()) return true; // if (right.empty()) return true; // return left.first() < right.first(); if (left.empty() && right.empty()) return false; if (left.empty()) return true; if (right.empty()) return false; return left.first() < right.first(); } ); } // returns distance between two points on the sky [deg] double haversine(double ra1, double ra2, double dec1, double dec2) { double rad = 3.1415926535 / 180.; ra1 *= rad; ra2 *= rad; dec1 *= rad; dec2 *= rad; double ddec = dec2 - dec1; double dra = ra2 - ra1; return 2. * asin( sqrt( pow(sin(ddec/2.),2) + cos(dec1) * cos(dec2) * pow(sin(dra/2.),2) ) ) / rad; } /* // Copy magnitudes and mag errors from a {DEC, RA, , } vector to another {DEC, RA, , } vector (matching) // can be one or more numbers, e.g. 2 ref mags, or several aperture mags // tolerance is in [deg] void match2D(const QVector> vec1, const QVector> vec2, QVector> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads) { if (vec1.isEmpty() || vec2.isEmpty()) return; // Only the reference vector needs to be sorted, using the first column (DEC) sort2DVector(vec2); long dim1 = vec1.length(); // Objects long dim2 = vec2.length(); // Reference sources matched.reserve(dim1); QVector numMatched1; QVector numMatched2; numMatched1.fill(0, dim1); // How many times an object got matched with different reference sources numMatched2.fill(0, dim2); // How many times a reference source got matched with different objects omp_lock_t lock; omp_init_lock(&lock); // First pass: identify ambiguous sources and references //#pragma omp parallel for num_threads(nthreads) for (long i=0; i1) ++multiple1; } for (auto &mult : numMatched2) { if (mult>1) ++multiple2; } // Second pass, match unambiguous sources, only #pragma omp parallel for num_threads(nthreads) for (long i=0; i 1) continue; bool inside_previous = false; bool inside_current = false; QVector dummy; for (long j=0; j, } vector to another {DEC, RA, , } vector (matching) // can be one or more numbers, e.g. 2 ref mags, or several aperture mags // tolerance is in [d/data1/TESTDATA/ST10/NGC4651/NGC4651_ALL/coadd_Redeg] void match2D(const QVector> vec1, QVector> vec2, QVector> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads) { if (vec1.isEmpty() || vec2.isEmpty()) return; // Only the reference vector needs to be sorted, using the first column (DEC) std::sort(vec2.begin(), vec2.end(), [](const QVector& left, const QVector& right)->bool { if (left.empty() && right.empty()) return false; if (left.empty()) return true; if (right.empty()) return false; return left.first() < right.first(); } ); // sort2DVector(vec2); long dim1 = vec1.length(); // Objects long dim2 = vec2.length(); // Reference sources matched.reserve(dim1); QVector numMatched1; QVector numMatched2; numMatched1.fill(0, dim1); // How many times an object got matched with different reference sources numMatched2.fill(0, dim2); // How many times a reference source got matched with different objects omp_lock_t lock; omp_init_lock(&lock); // First pass: identify ambiguous sources and references //#pragma omp parallel for num_threads(nthreads) for (long i=0; i1) ++multiple1; } for (auto &mult : numMatched2) { if (mult>1) ++multiple2; } // qDebug() << multiple1 << multiple2; // Second pass, match unambiguous sources, only #pragma omp parallel for num_threads(nthreads) for (long i=0; i 1) continue; bool inside_previous = false; bool inside_current = false; QVector dummy; for (long j=0; j 1) continue; // calc DEC offset and see if we are "within reach" double ddec = fabs(vec2.at(j)[0] - vec1.at(i)[0]); if (ddec < tolerance) inside_current = true; else inside_current = false; // Leave if we passed the plausible matching zone if (inside_previous && !inside_current) break; if (inside_current) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); if (distance < tolerance) { dummy << vec1.at(i)[0]; // DEC OBJ dummy << vec1.at(i)[1]; // RA OBJ for (int k=2; k> vec1, QVector> vec2, QVector> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads) { if (vec1.isEmpty() || vec2.isEmpty()) return; // Only the reference vector needs to be sorted, using the first column (DEC) std::sort(vec2.begin(), vec2.end(), [](const QVector& left, const QVector& right)->bool { if (left.empty() && right.empty()) return false; if (left.empty()) return true; if (right.empty()) return false; return left.first() < right.first(); } ); // sort2DVector(vec2); long dim1 = vec1.length(); // Objects long dim2 = vec2.length(); // Reference sources matched.reserve(dim1); QVector numMatched1; QVector numMatched2; numMatched1.fill(0, dim1); // How many times an object got matched with different reference sources numMatched2.fill(0, dim2); // How many times a reference source got matched with different objects omp_lock_t lock; omp_init_lock(&lock); // First pass: identify ambiguous sources and references // #pragma omp parallel for num_threads(nthreads) for (long i=0; i1) ++multiple1; } for (auto &mult : numMatched2) { if (mult>1) ++multiple2; } // Second pass, match unambiguous sources, only #pragma omp parallel for num_threads(nthreads) for (long i=0; i 1) continue; bool inside_previous = false; bool inside_current = false; QVector dummy; for (long j=0; j 1) continue; // calc DEC offset and see if we are "within reach" double ddec = fabs(vec2.at(j)[0] - vec1.at(i)[0]); if (ddec < tolerance) inside_current = true; else inside_current = false; // Leave if we passed the plausible matching zone if (inside_previous && !inside_current) break; if (inside_current) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); if (distance < tolerance) { dummy << vec2.at(j)[0]; // DEC OBJ dummy << vec2.at(j)[1]; // RA OBJ for (int k=2; k #include #include #include "instrumentdata.h" #include "../myimage/myimage.h" void binData(const QVector &data, QVector &dataBinned, const int n, const int nb, const int mb, const int binX, const int binY); void binDataMean(const QVector &data, QVector &dataBinned, const int n, const int nb, const int mb, const int binX, const int binY); QVector CDmatrixToTransformationMatrix(QVector CD, QString instName); void debayer(int chip, MyImage *image, MyImage *imageB, MyImage *imageG, MyImage *imageR); int direction(float N, float E, float W, float S); void equalizeBayerFlat(MyImage *image); void getBinnedSize(const instrumentDataType *instData, const QVector > Tmatrices, int &n_bin, int &m_bin, int binFactor, int &xminOffset, int &yminOffset); float hue_transit(float l1, float l2, float l3, float v1, float v3); void mapBinnedData(QVector &dataBinnedGlobal, const QVector &dataBinnedIndividual, QVector T, const int nGlobal, const int mGlobal, const int nInd, const int mInd, const long crpix1, const long crpix2, const int xminOffset, const int yminOffset, const QString instName); float posangle(const QVector CDmatrix); void rotateCDmatrix(QVector &CDin, float pa_new); void updateDebayerMemoryStatus(MyImage *image); QVector collapse_x(QVector &data, const QVector &globalMask, QVector &objectMask, const float kappa, const long n, const long m, const QString returnMode); QVector collapse_y(QVector &data, const QVector &globalMask, QVector &objectMask, const float kappa, const long n, const long m, const QString returnMode); QVector collapse_quad(QVector &data, const QVector &globalMask, QVector &objectMask, const float kappa, const long n, const long m, const QString direction, const QString returnMode); void match2D(const QVector > vec1, QVector > vec2, QVector> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads); void match2D_refcoords(const QVector > vec1, QVector > vec2, QVector> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads); double haversine(double ra1, double ra2, double dec1, double dec2); #endif // TOOLS_H THELI-3.1.3/src/tools/xcorr.cc000066400000000000000000000012461417631501300157620ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ THELI-3.1.3/src/validators.cc000066400000000000000000000046531417631501300156420ustar00rootroot00000000000000/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI 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 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 in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainwindow.h" #include "ui_mainwindow.h" #include #include void MainWindow::validate() { QRegExp rx1( "^\\S+$" ); QRegExp rx2( "^[A-Z0-9a-z-+._, ]+$" ); QValidator *validator_string = new QRegExpValidator( rx1, this ); QValidator *validator_stringdir = new QRegExpValidator( rx2, this ); ui->setupBiasLineEdit->setValidator( validator_stringdir ); ui->setupDarkLineEdit->setValidator( validator_stringdir ); ui->setupFlatLineEdit->setValidator( validator_stringdir ); ui->setupFlatoffLineEdit->setValidator( validator_stringdir ); ui->setupMainLineEdit->setValidator( validator_string ); ui->setupProjectLineEdit->setValidator( validator_string ); ui->setupScienceLineEdit->setValidator( validator_stringdir ); ui->setupSkyLineEdit->setValidator( validator_stringdir ); ui->setupStandardLineEdit->setValidator( validator_stringdir); } void MainWindow::connect_validators() { connect(ui->setupBiasLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupDarkLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupFlatLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupFlatoffLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupMainLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupProjectLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupScienceLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupSkyLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); connect(ui->setupStandardLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate); }