pax_global_header00006660000000000000000000000064146532352460014524gustar00rootroot0000000000000052 comment=5b8223215281b7bd99dbd31e8c1e208f5fe24750 pymoc-0.5.2/000077500000000000000000000000001465323524600126575ustar00rootroot00000000000000pymoc-0.5.2/.gitignore000066400000000000000000000000401465323524600146410ustar00rootroot00000000000000*~ *.pyc /MANIFEST /build /dist pymoc-0.5.2/.readthedocs.yaml000066400000000000000000000003301465323524600161020ustar00rootroot00000000000000# Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details version: 2 build: os: ubuntu-22.04 tools: python: "3.11" sphinx: configuration: doc/conf.py pymoc-0.5.2/CHANGES.txt000066400000000000000000000040171465323524600144720ustar00rootroot000000000000000.5.2 2024-08-02 - Prevented an error reading an ASCII MOC file with an order with an empty cell list. As of MOC 1.1 this should encode the MOCORDER if higher than the greatest stored order. This module does not (yet) process this information but it should now be able to read such files without error. 0.5.1 2024-07-09 - Prevented an error when reading an empty ASCII MOC file. - Updated a docstring which refered to the now deprecated Astropy FITS HDUList.writeto method clobber argument. - Skipped calling the Healpy "query_disc" function for catalogs if the given radius is zero (or less). - "pymoctool" now accepts "-" in place of a filename to read from stdin or write to stdout in ASCII format. 0.5.0 2017-05-30 - Improved speed of MOC generation from catalogs by making use of the Healpy "query_disc" function. Additional optional arguments can be given to the "catalog_to_moc" function to control this process. - "pymoctool" now checks that a running MOC is present for some commands. 0.4.2 2017-04-19 - Corrected bug reading MOCs in FITS format on 32-bit systems with 64-bit NUNIQ columns. 0.4.1 2016-08-08 - Corrected bug in intersection routine. - Added option to skip validation of cell numbers in the "add" method. 0.4.0 2015-11-20 - Added utility to create MOCs from catalog files. - "pymoctool" can now invoke the plotting and catalog utilities. - Preserve metadata read from FITS file when constructing new MOC object. 0.3.0 2014-11-14 - A command line utility "pymoctool" has been included in the package. - Additional keywords are now passed to FITS open and writeto functions. 0.2.0 2014-10-10 - Updated FITS table column name based on the IVOA version 1.0 MOC recommendation. - Defined addition, equality and subtraction operations. - Added clear, contains, flattened and intersection methods. - Added plotting utility based on Healpy. 0.1.0 2014-05-27 - Initial release. pymoc-0.5.2/COPYING000066400000000000000000001045131465323524600137160ustar00rootroot00000000000000 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 . pymoc-0.5.2/MANIFEST.in000066400000000000000000000001411465323524600144110ustar00rootroot00000000000000include COPYING include README.rst include MANIFEST.in include test/*.py include test-extra/*.py pymoc-0.5.2/README.rst000066400000000000000000000044051465323524600143510ustar00rootroot00000000000000Multi-Order Coverage map module for Python ========================================== Introduction ------------ .. startpymocintro PyMOC is a module for manipulating Multi-Order Coverage (MOC) maps. It includes support for reading and writing the three encodings mentioned in the IVOA recommendation: FITS, JSON and ASCII. PyMOC also includes a utility program ``pymoctool`` to allow MOC files to be manipulated from the command line. .. endpymocintro .. startpymocinstall Installation ------------ The module can be installed using the ``setup.py`` script:: python setup.py install Unit Tests ~~~~~~~~~~ Prior to installation, the unit tests can be run using:: PYTHONPATH=lib python3 -m unittest or:: PYTHONPATH=lib python2 -m unittest discover The `test-extra` directory contains additional tests which may take longer to perform. You can exclude these by specifying just the plain `test` directory, for example with:: PYTHONPATH=lib python -m unittest discover -s test The routines included in the doctests should also be covered by the unit tests. However to ensure the documentation is correct, they can be checked with:: sphinx-build -b doctest doc doc/_build/doctest Requirements ~~~~~~~~~~~~ For reading and writing data in FITS format, the ``astropy`` library is required. ``Healpy`` is needed for some of the utility functions such as ``plot_moc`` and ``catalog_to_moc``. .. endpymocinstall License ------- 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 . Additional Links ---------------- * `Documentation at Read the Docs `_ * `Repository at GitHub `_ * `Entry on PyPI `_ pymoc-0.5.2/doc/000077500000000000000000000000001465323524600134245ustar00rootroot00000000000000pymoc-0.5.2/doc/.gitignore000066400000000000000000000000101465323524600154030ustar00rootroot00000000000000/_build pymoc-0.5.2/doc/conf.py000066400000000000000000000213651465323524600147320ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # PyMOC documentation build configuration file, created by # sphinx-quickstart on Wed May 21 17:01:13 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../lib')) # Allow autodoc documentation to be built without optional requirements # being installed. # See: https://docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules # and: http://blog.rtwilson.com/how-to-make-your-sphinx-documentation-compile-with-readthedocs-when-youre-using-numpy-and-scipy/ try: from unittest.mock import Mock except ImportError: from mock import Mock for mod_name in ( 'astropy', 'astropy.coordinates', 'astropy.io', 'astropy.units', 'astropy.units.quantity', 'healpy', 'healpy.pixelfunc', 'matplotlib', 'matplotlib.colors', 'matplotlib.pyplot', 'numpy'): sys.modules[mod_name] = Mock() # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'PyMOC' copyright = '2014, Science and Technology Facilities Council' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. # version = 'X.X.X' from pymoc.version import version # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PyMOCdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'PyMOC.tex', 'PyMOC Documentation', 'Graham Bell', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pymoc', 'PyMOC Documentation', ['Graham Bell'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'PyMOC', 'PyMOC Documentation', 'Graham Bell', 'PyMOC', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False pymoc-0.5.2/doc/index.rst000066400000000000000000000004361465323524600152700ustar00rootroot00000000000000PyMOC ===== .. include:: ../README.rst :start-after: .. startpymocintro :end-before: .. endpymocintro Contents -------- .. toctree:: :maxdepth: 2 install moc io util Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` pymoc-0.5.2/doc/install.rst000066400000000000000000000001461465323524600156250ustar00rootroot00000000000000.. include:: ../README.rst :start-after: .. startpymocinstall :end-before: .. endpymocinstall pymoc-0.5.2/doc/io.rst000066400000000000000000000020021465323524600145570ustar00rootroot00000000000000I/O Functions ============= Input and output (I/O) functions for the three encodings used by MOC are located in a separate part of the package. This is to allow you to use the :class:`~pymoc.moc.MOC` class itself without needing the requirements of the I/O routines. For general file handling, the giving the ``filename`` argument to the :class:`~pymoc.moc.MOC` constructor, or using the :meth:`~pymoc.moc.MOC.read` and :meth:`~pymoc.moc.MOC.write` methods may be sufficient. The dedicated I/O functions described here can be used in more specialized situations, such as interacting with FITS HDU objects or reading and writing already-open file objects. pymoc.io.ascii -------------- .. automodule:: pymoc.io.ascii :members: :member-order: bysource :undoc-members: pymoc.io.fits ------------- .. automodule:: pymoc.io.fits :members: :member-order: bysource :undoc-members: pymoc.io.json ------------- .. automodule:: pymoc.io.json :members: :member-order: bysource :undoc-members: pymoc-0.5.2/doc/moc.rst000066400000000000000000000007341465323524600147400ustar00rootroot00000000000000The MOC Class ============= pymoc ----- .. module:: pymoc The ``pymoc`` module imports the :class:`~pymoc.moc.MOC` class from the :mod:`pymoc.moc` module, allowing it to be imported as follows:: from pymoc import MOC pymoc.moc --------- .. automodule:: pymoc.moc :members: :member-order: bysource :undoc-members: :special-members: __init__, __iter__, __len__, __getitem__, __iadd__, __add__, __isub__, __sub__, __eq__, __repr__ pymoc-0.5.2/doc/util.rst000066400000000000000000000005651465323524600151410ustar00rootroot00000000000000Utilities ========= pymoc.util.catalog ------------------ .. automodule:: pymoc.util.catalog :members: :member-order: bysource pymoc.util.plot --------------- .. automodule:: pymoc.util.plot :members: :member-order: bysource :undoc-members: pymoc.util.tool --------------- .. automodule:: pymoc.util.tool :members: :member-order: bysource pymoc-0.5.2/lib/000077500000000000000000000000001465323524600134255ustar00rootroot00000000000000pymoc-0.5.2/lib/pymoc/000077500000000000000000000000001465323524600145545ustar00rootroot00000000000000pymoc-0.5.2/lib/pymoc/__init__.py000066400000000000000000000013721465323524600166700ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from __future__ import absolute_import from .moc import MOC pymoc-0.5.2/lib/pymoc/io/000077500000000000000000000000001465323524600151635ustar00rootroot00000000000000pymoc-0.5.2/lib/pymoc/io/__init__.py000066400000000000000000000000001465323524600172620ustar00rootroot00000000000000pymoc-0.5.2/lib/pymoc/io/ascii.py000066400000000000000000000052011465323524600166230ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # Copyright (C) 2017 East Asian Observatory. # # 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 . from __future__ import unicode_literals def write_moc_ascii(moc, filename=None, file=None): """Write a MOC to an ASCII file. Either a filename, or an open file object can be specified. """ orders = [] for (order, cells) in moc: ranges = [] rmin = rmax = None for cell in sorted(cells): if rmin is None: rmin = rmax = cell elif rmax == cell - 1: rmax = cell else: ranges.append(_format_range(rmin, rmax)) rmin = rmax = cell ranges.append(_format_range(rmin, rmax)) orders.append('{0}'.format(order) + '/' + ','.join(ranges)) if file is not None: _write_ascii(orders, file) else: with open(filename, 'w') as f: _write_ascii(orders, f) def read_moc_ascii(moc, filename=None, file=None): """Read from an ASCII file into a MOC. Either a filename, or an open file object can be specified. """ if file is not None: orders = _read_ascii(file) else: with open(filename, 'r') as f: orders = _read_ascii(f) for text in orders: if not text: continue cells = [] (order, ranges) = text.split('/') if not ranges: continue for r in ranges.split(','): try: cells.append(int(r)) except ValueError as e: (rmin, rmax) = r.split('-') cells.extend(range(int(rmin), int(rmax) + 1)) moc.add(order, cells) def _write_ascii(orders, f): f.write(' '.join(orders)) def _read_ascii(f): text = f.read() return text.strip().split(' ') def _format_range(rmin, rmax): if rmin == rmax: return '{0}'.format(rmin) elif rmax == rmin + 1: return '{0},{1}'.format(rmin, rmax) else: return '{0}-{1}'.format(rmin, rmax) pymoc-0.5.2/lib/pymoc/io/fits.py000066400000000000000000000122411465323524600165020ustar00rootroot00000000000000# Copyright (C) 2013-2014 Science and Technology Facilities Council. # Copyright (C) 2017 East Asian Observatory. # # 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 . from __future__ import absolute_import # If running under Python 2, import the itertools.izip function. In # Python 3 this is not necessary -- the import will fail and we use the # normal zip function instead. try: from itertools import izip except ImportError as e: izip = zip from astropy.io import fits from datetime import datetime from math import log import numpy as np from ..version import version def write_moc_fits_hdu(moc): """Create a FITS table HDU representation of a MOC. """ # Ensure data are normalized. moc.normalize() # Determine whether a 32 or 64 bit column is required. if moc.order < 14: moc_type = np.int32 col_type = 'J' else: moc_type = np.int64 col_type = 'K' # Convert to the NUNIQ value which guarantees that one of the # top two bits is set so that the order of the value can be # determined. nuniq = [] for (order, cells) in moc: uniq_prefix = 4 * (4 ** order) for npix in cells: nuniq.append(npix + uniq_prefix) # Prepare the data, and sort into numerical order. nuniq = np.array(nuniq, dtype=moc_type) nuniq.sort() # Create the FITS file. col = fits.Column(name='UNIQ', format=col_type, array=nuniq) cols = fits.ColDefs([col]) rec = fits.FITS_rec.from_columns(cols) tbhdu = fits.BinTableHDU(rec) # Mandatory Keywords. tbhdu.header['PIXTYPE'] = 'HEALPIX' tbhdu.header['ORDERING'] = 'NUNIQ' tbhdu.header['COORDSYS'] = 'C' tbhdu.header['MOCORDER'] = moc.order tbhdu.header.comments['PIXTYPE'] = 'HEALPix magic code' tbhdu.header.comments['ORDERING'] = 'NUNIQ coding method' tbhdu.header.comments['COORDSYS'] = 'ICRS reference frame' tbhdu.header.comments['MOCORDER'] = 'MOC resolution (best order)' # Optional Keywords. tbhdu.header['MOCTOOL'] = 'PyMOC ' + version tbhdu.header.comments['MOCTOOL'] = 'Name of MOC generator' if moc.type is not None: tbhdu.header['MOCTYPE'] = moc.type tbhdu.header.comments['MOCTYPE'] = 'Source type (IMAGE or CATALOG)' if moc.id is not None: tbhdu.header['MOCID'] = moc.id tbhdu.header.comments['MOCID'] = 'Identifier of the collection' if moc.origin is not None: tbhdu.header['ORIGIN'] = moc.origin tbhdu.header.comments['ORIGIN'] = 'MOC origin' tbhdu.header['DATE'] = datetime.utcnow().replace( microsecond=0).isoformat() tbhdu.header.comments['DATE'] = 'MOC creation date' if moc.name is not None: tbhdu.header['EXTNAME'] = moc.name tbhdu.header.comments['EXTNAME'] = 'MOC name' return tbhdu def write_moc_fits(moc, filename, **kwargs): """Write a MOC as a FITS file. Any additional keyword arguments are passed to the astropy.io.fits.HDUList.writeto method. """ tbhdu = write_moc_fits_hdu(moc) prihdr = fits.Header() prihdu = fits.PrimaryHDU(header=prihdr) hdulist = fits.HDUList([prihdu, tbhdu]) hdulist.writeto(filename, **kwargs) def read_moc_fits(moc, filename, include_meta=False, **kwargs): """Read data from a FITS file into a MOC. Any additional keyword arguments are passed to the astropy.io.fits.open method. """ hl = fits.open(filename, mode='readonly', **kwargs) read_moc_fits_hdu(moc, hl[1], include_meta) def read_moc_fits_hdu(moc, hdu, include_meta=False): """Read data from a FITS table HDU into a MOC. """ if include_meta: header = hdu.header if 'MOCTYPE' in header: moc.type = header['MOCTYPE'] if 'MOCID' in header: moc.id = header['MOCID'] if 'ORIGIN' in header: moc.origin = header['ORIGIN'] if 'EXTNAME' in header: moc.name = header['EXTNAME'] current_order = None current_cells = [] # Determine type to use for orders: 32 bit if column type is J, # otherwise assume we need 64 bit. moc_type = np.int32 if (hdu.data.formats[0] == 'J') else np.int64 nuniqs = hdu.data.field(0) orders = (np.log2(nuniqs / 4) / 2).astype(moc_type) cells = nuniqs - 4 * (4 ** orders) for (order, cell) in izip(orders, cells): if order != current_order: if current_cells: moc.add(current_order, current_cells) current_order = order current_cells = [cell] else: current_cells.append(cell) if current_cells: moc.add(current_order, current_cells) pymoc-0.5.2/lib/pymoc/io/json.py000066400000000000000000000034121465323524600165060ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from __future__ import absolute_import, unicode_literals from codecs import utf_8_decode, utf_8_encode import json def write_moc_json(moc, filename=None, file=None): """Write a MOC in JSON encoding. Either a filename, or an open file object can be specified. """ moc.normalize() obj = {} for (order, cells) in moc: obj['{0}'.format(order)] = sorted(cells) if file is not None: _write_json(obj, file) else: with open(filename, 'wb') as f: _write_json(obj, f) def read_moc_json(moc, filename=None, file=None): """Read JSON encoded data into a MOC. Either a filename, or an open file object can be specified. """ if file is not None: obj = _read_json(file) else: with open(filename, 'rb') as f: obj = _read_json(f) for (order, cells) in obj.items(): moc.add(order, cells) def _write_json(obj, f): f.write(utf_8_encode( json.dumps(obj, sort_keys=True, separators=(',', ':')))[0]) def _read_json(f): return json.loads(utf_8_decode(f.read())[0]) pymoc-0.5.2/lib/pymoc/moc.py000066400000000000000000000602721465323524600157130ustar00rootroot00000000000000# Copyright (C) 2013-2014 Science and Technology Facilities Council. # Copyright (C) 2015-2016 East Asian Observatory. # # 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 . from __future__ import absolute_import from math import pi from os.path import isfile MAX_ORDER = 29 MOC_TYPES = ('IMAGE', 'CATALOG') class MOC(object): """Class representing Multi-Order Coverage maps. Apart from the properties listed below, the MOC also includes the following attributes: * id * name * origin """ def __init__(self, order=None, cells=None, filename=None, filetype=None, name=None, mocid=None, origin=None, moctype=None): """Construct new MOC object. By default the new MOC will be empty, but if an order and a collection of cells are specified, then these will be added to the new MOC. If a filename is specified then data from the given file will be read into the new object, and if it is a FITS file, the metadata will also be read, although this can be overridden by values given explicitly as constructor arguments. Additional metadata can be added to the MOC using the ``name``, ``mocid``, ``origin`` and ``moctype`` arguments, or added at a later time using the corresponding attributes and properties. The metadata values can be read from and written to FITS files, but are not included when a MOC is written to the other formats (JSON or ASCII). >>> from pymoc import MOC >>> m = MOC() >>> m.cells 0 >>> m = MOC(10, (1234, 4321)) >>> m.cells 2 >>> m = MOC(name='example', moctype='IMAGE') >>> m.name 'example' >>> m.type 'IMAGE' """ self._orders = tuple(set() for i in range(0, MAX_ORDER + 1)) self._normalized = True # Initialize metadata properties but wait until after reading # metadata from a file before overriding with specified values. self.id = None self.name = None self.origin = None self.type = None if filename is not None: # Read the file, including metadata if present. self.read(filename, filetype, include_meta=True) # Set any metadata explicity specified, overriding that # read from the file. if mocid is not None: self.id = mocid if name is not None: self.name = name if origin is not None: self.origin = origin if moctype is not None: self.type = moctype # Add any cells specified in the arguments. if order is not None and cells is not None: self.add(order, cells) elif order is not None or cells is not None: raise ValueError('Only one of order and cells specified') def __iter__(self): """Iterator for MOC objects. This yields an (order, cell collection) pair for each order at which there are cells. The results will be returned in ascending order of the order number. >>> m = MOC(0, (1, 2)) >>> m.add(1, (0,)) >>> for (order, cells) in m: ... print(str(order) + ' ' + str(sorted(cells))) 0 [1, 2] 1 [0] """ for order in range(0, MAX_ORDER + 1): if self._orders[order]: yield (order, frozenset(self._orders[order])) def __len__(self): """Length operator for MOC objects. Returns the number of orders at which the MOC has cells. >>> m = MOC(0, (1, 2)) >>> len(m) 1 """ n = 0 for order in range(0, MAX_ORDER + 1): if self._orders[order]: n += 1 return n def __getitem__(self, order): """Subscripting operator for MOC objects. This retrieves a collection of cells at the given order of the MOC. >>> m = MOC(5, (6, 7)) >>> sorted(m[5]) [6, 7] """ order = self._validate_order(order) return frozenset(self._orders[order]) def __eq__(self, other): """Equality test operator. >>> MOC(1, (4, 5, 6, 7)) == MOC(0, (1,)) True >>> MOC(2, (0, 1)) == MOC(0, (0,)) False >>> MOC(1, (5, 6)) != MOC(1, (1, 2)) True >>> MOC(2, (8, 9, 10, 11)) != MOC(1, (2,)) False """ if not isinstance(other, MOC): return NotImplemented self.normalize() other.normalize() for order in range(0, MAX_ORDER + 1): if self._orders[order] != other._orders[order]: return False return True def __ne__(self, other): """Inequality test operator. Implemented via __eq__. """ return not self.__eq__(other) def __iadd__(self, other): """In-place addition operator. Updates the MOC to represent the union of itself and the other MOC. >>> p = MOC(4, (5, 6)) >>> p += MOC(4, (7, 8)) >>> repr(p) '' """ if not isinstance(other, MOC): return NotImplemented for (order, cells) in other: self.add(order, cells) return self def __add__(self, other): """Addition operator. Returns a MOC which is the union of two MOCs. >>> MOC(4, (5, 6)) + MOC(4, (7, 8)) """ if not isinstance(other, MOC): return NotImplemented sum = self.copy() sum += other return sum def __sub__(self, other): """Subtraction operator. Returns a MOC which is the copy of the first MOC with the intersection with the second MOC removed. >>> MOC(0, (0,)) - MOC(2, (15,)) """ if not isinstance(other, MOC): return NotImplemented diff = self.copy() diff -= other return diff def __isub__(self, other): """In-place subtraction operator. Removes areas which overlap with the given MOC. """ if not isinstance(other, MOC): return NotImplemented for (order, cells) in other: self.remove(order, cells) return self def __repr__(self): """Generate printable representation. Since the constructor only accepts cells at one order and we may be generating a representation for a MOC with cells at multiple orders we can't try to give an expression which would construct the object. Instead show a description in angle brackets. """ return ''.format( [(o, sorted(cs)) for (o, cs) in enumerate(self._orders) if cs]) @property def order(self): """The highest order at which the MOC has cells. >>> m = MOC(4, (3, 2, 1)) >>> m.order 4 """ for order in range(MAX_ORDER, 0, -1): if self._orders[order]: return order return 0 @property def type(self): """The type of MOC (IMAGE or CATALOG). >>> m = MOC(moctype='IMAGE') >>> m.type 'IMAGE' >>> m.type = 'CATALOG' >>> m.type 'CATALOG' """ return self._type @type.setter def type(self, value): """Set the type of the MOC. The value should be either "IMAGE" or "CATALOG". """ self._type = None if value is None: return value = value.upper() if value in MOC_TYPES: self._type = value else: raise ValueError('MOC type must be one of ' + ', '.join(MOC_TYPES)) @property def normalized(self): """Whether the MOC has been normalized or not. >>> m = MOC() >>> m.add(1, (0,)) >>> m.add(2, (1,)) >>> m.normalized False >>> m.normalize() >>> m.normalized True """ return self._normalized @property def area(self): """The area enclosed by the MOC, in steradians. >>> m = MOC(0, (0, 1, 2)) >>> round(m.area, 2) 3.14 """ self.normalize() area = 0.0 for (order, cells) in self: area += (len(cells) * pi) / (3 * 4 ** order) return area @property def area_sq_deg(self): """The area enclosed by the MOC, in square degrees. >>> from math import sqrt >>> m = MOC(0, (0,)) >>> round(sqrt(m.area_sq_deg), 2) 58.63 """ return self.area * ((180 / pi) ** 2) @property def cells(self): """The number of cells in the MOC. This gives the total number of cells at all orders, with cells from every order counted equally. >>> m = MOC(0, (1, 2)) >>> m.cells 2 """ n = 0 for (order, cells) in self: n += len(cells) return n def add(self, order, cells, no_validation=False): """Add cells at a given order to the MOC. The cells are inserted into the MOC at the specified order. This leaves the MOC in an un-normalized state. The cells are given as a collection of integers (or types which can be converted to integers). >>> m = MOC() >>> m.add(4, (20, 21)) >>> m.cells 2 >>> m.add(5, (88, 89)) >>> m.cells 4 The `no_validation` option can be given to skip validation of the cell numbers. They must already be integers in the correct range. """ self._normalized = False order = self._validate_order(order) if no_validation: # Simply add the given cells to the set with no validation. self._orders[order].update(cells) else: # Collect validated cell numbers in a set for addition. cell_set = set() for cell in cells: cell = self._validate_cell(order, cell) cell_set.add(cell) self._orders[order].update(cell_set) def remove(self, order, cells): """Remove cells at a given order from the MOC. """ self._normalized = False order = self._validate_order(order) for cell in cells: cell = self._validate_cell(order, cell) self._compare_operation(order, cell, True, 'remove') def clear(self): """Clears all cells from a MOC. >>> m = MOC(4, (5, 6)) >>> m.clear() >>> m.cells 0 """ for order in range(0, MAX_ORDER + 1): self._orders[order].clear() self._normalized = True def copy(self): """Return a copy of a MOC. >>> p = MOC(4, (5, 6)) >>> q = p.copy() >>> repr(q) '' """ copy = MOC(name=self.name, mocid=self.id, origin=self.origin, moctype=self.type) copy += self return copy def contains(self, order, cell, include_smaller=False): """Test whether the MOC contains the given cell. If the include_smaller argument is true then the MOC is considered to include a cell if it includes part of that cell (at a higher order). >>> m = MOC(1, (5,)) >>> m.contains(0, 0) False >>> m.contains(0, 1, True) True >>> m.contains(0, 1, False) False >>> m.contains(1, 4) False >>> m.contains(1, 5) True >>> m.contains(2, 19) False >>> m.contains(2, 21) True """ order = self._validate_order(order) cell = self._validate_cell(order, cell) return self._compare_operation(order, cell, include_smaller, 'check') def _compare_operation(self, order, cell, include_smaller, operation): """General internal method for comparison-based operations. This is a private method, and does not update the normalized flag. """ # Check for a larger cell (lower order) which contains the # given cell. for order_i in range(0, order): shift = 2 * (order - order_i) cell_i = cell >> shift if cell_i in self._orders[order_i]: if operation == 'check': return True elif operation == 'remove': # Remove the cell and break it into its 4 constituent # cells. Those which actually match the area we are # trying to remove will be removed at the next stage. self._orders[order_i].remove(cell_i) self.add(order_i + 1, range(cell_i << 2, (cell_i + 1) << 2)) elif operation == 'inter': return [(order, (cell,))] # Check for the specific cell itself, but only after looking at larger # cells because for the "remove" operation we may have broken up # one of the large cells so that it subsequently matches. if cell in self._orders[order]: if operation == 'check': return True elif operation == 'remove': self._orders[order].remove(cell) elif operation == 'inter': return [(order, (cell,))] result = [] if include_smaller: # Check for a smaller cell (higher order) which is part # of the given cell. for order_i in range(order + 1, MAX_ORDER + 1): shift = 2 * (order_i - order) cells = [] for cell_i in self._orders[order_i]: if (cell_i >> shift) == cell: if operation == 'check': return True elif operation == 'remove' or operation == 'inter': cells.append(cell_i) if operation == 'remove': for cell_i in cells: self._orders[order_i].remove(cell_i) elif operation == 'inter': if cells: result.append((order_i, cells)) if operation == 'check': return False elif operation == 'inter': return result def intersection(self, other): """Returns a MOC representing the intersection with another MOC. >>> p = MOC(2, (3, 4, 5)) >>> q = MOC(2, (4, 5, 6)) >>> p.intersection(q) """ inter = MOC() for (order, cells) in other: for cell in cells: for i in self._compare_operation(order, cell, True, 'inter'): inter.add(*i) return inter def normalize(self, max_order=MAX_ORDER): """Ensure that the MOC is "well-formed". This structures the MOC as is required for the FITS and JSON representation. This method is invoked automatically when writing to these formats. The number of cells in the MOC will be minimized, so that no area of the sky is covered multiple times by cells at different orders, and if all four neighboring cells are present at an order (other than order 0), they are merged into their parent cell at the next lower order. >>> m = MOC(1, (0, 1, 2, 3)) >>> m.cells 4 >>> m.normalize() >>> m.cells 1 """ max_order = self._validate_order(max_order) # If the MOC is already normalized and we are not being asked # to reduce the order, then do nothing. if self.normalized and max_order >= self.order: return # Group the pixels by iterating down from the order. At each # order, where all 4 adjacent pixels are present (or we are above # the maximum order) they are replaced with a single pixel in the # next lower order. Otherwise the pixel should appear in the MOC # unless it is already represented at a lower order. for order in range(self.order, 0, -1): pixels = self._orders[order] next_pixels = self._orders[order - 1] new_pixels = set() while pixels: pixel = pixels.pop() # Look to lower orders to ensure this pixel isn't # already covered. check_pixel = pixel already_contained = True for check_order in range(order - 1, -1, -1): check_pixel >>= 2 if check_pixel in self._orders[check_order]: break else: already_contained = False # Check whether this order is above the maximum, or # if we have all 4 adjacent pixels. Also do this if # the pixel was already contained at a lower level # so that we can avoid checking the adjacent pixels. if (already_contained or (order > max_order) or (((pixel ^ 1) in pixels) and ((pixel ^ 2) in pixels) and ((pixel ^ 3) in pixels))): pixels.discard(pixel ^ 1) pixels.discard(pixel ^ 2) pixels.discard(pixel ^ 3) if not already_contained: # Group these pixels by placing the equivalent pixel # for the next order down in the set. next_pixels.add(pixel >> 2) else: new_pixels.add(pixel) if new_pixels: self._orders[order].update(new_pixels) self._normalized = True def flattened(self, order=None, include_smaller=True): """Return a flattened pixel collection at a single order.""" if order is None: order = self.order else: order = self._validate_order(order) # Start with the cells which are already at this order. flat = set(self[order]) # Look at lower orders and expand them into this set. # Based on the "map" algorithm from Appendix A of the # MOC recommendation. for order_i in range(0, order): shift = 2 * (order - order_i) for cell in self[order_i]: flat.update(range(cell << shift, (cell + 1) << shift)) # Look at higher orders unless we have been told to exclude # them. if include_smaller: for order_i in range(order + 1, MAX_ORDER + 1): shift = 2 * (order_i - order) for cell in self[order_i]: flat.add(cell >> shift) return flat def read(self, filename, filetype=None, include_meta=False, **kwargs): """Read data from the given file into the MOC object. The cell lists read from the file are added to the current object. Therefore if the object already contains some cells, it will be updated to represent the union of the current coverge and that from the file. The file type can be specified as "fits", "json" or "ascii", with "text" allowed as an alias for "ascii". If the type is not specified, then an attempt will be made to guess from the file name, or the contents of the file. Note that writing to FITS and JSON will cause the MOC to be normalized automatically. Any additional keyword arguments (kwargs) are passed on to the corresponding pymoc.io read functions (read_moc_fits, read_moc_json or read_moc_ascii). """ if filetype is not None: filetype = filetype.lower() else: filetype = self._guess_file_type(filename) if filetype == 'fits': from .io.fits import read_moc_fits read_moc_fits(self, filename, include_meta, **kwargs) elif filetype == 'json': from .io.json import read_moc_json read_moc_json(self, filename, **kwargs) elif filetype == 'ascii' or filetype == 'text': from .io.ascii import read_moc_ascii read_moc_ascii(self, filename, **kwargs) else: raise ValueError('Unknown MOC file type {0}'.format(filetype)) def write(self, filename, filetype=None, **kwargs): """Write the coverage data in the MOC object to a file. The filetype can be given or left to be inferred as for the read method. Any additional keyword arguments (kwargs) are passed on to the corresponding pymoc.io write functions (write_moc_fits, write_moc_json or write_moc_ascii). This can be used, for example, to set overwrite=True (or clobber=True prior to Astropy version 2.0) when writing FITS files. """ if filetype is not None: filetype = filetype.lower() else: filetype = self._guess_file_type(filename) if filetype == 'fits': from .io.fits import write_moc_fits write_moc_fits(self, filename, **kwargs) elif filetype == 'json': from .io.json import write_moc_json write_moc_json(self, filename, **kwargs) elif filetype == 'ascii' or filetype == 'text': from .io.ascii import write_moc_ascii write_moc_ascii(self, filename, **kwargs) else: raise ValueError('Unknown MOC file type {0}'.format(filetype)) def _guess_file_type(self, filename): """Attempt to guess the type of a MOC file. Returns "fits", "json" or "ascii" if successful and raised a ValueError otherwise. """ # First attempt to guess from the file name. namelc = filename.lower() if namelc.endswith('.fits') or namelc.endswith('.fit'): return 'fits' elif namelc.endswith('.json'): return 'json' elif namelc.endswith('.txt') or namelc.endswith('.ascii'): return 'ascii' # Otherwise, if the file exists, look at the first character. if isfile(filename): with open(filename, 'r') as f: c = f.read(1) if c == 'S': return 'fits' elif c == '{': return 'json' elif c.isdigit(): return 'ascii' raise ValueError('Unable to determine format of {0}'.format(filename)) def _order_num_cells(self, order): """Determine the number of possible cells for an order.""" return 12 * 4 ** order def _validate_order(self, order): """Check that the given order is valid.""" try: order = int(order) except ValueError as e: raise TypeError('MOC order must be convertable to int') if not 0 <= order <= MAX_ORDER: raise ValueError( 'MOC order must be in range 0-{0}'.format(MAX_ORDER)) return order def _validate_cell(self, order, cell): """Check that the given cell is valid. The order is assumed already to have been validated. """ max_cells = self._order_num_cells(order) try: cell = int(cell) except ValueError as e: raise TypeError('MOC cell must be convertable to int') if not 0 <= cell < max_cells: raise ValueError( 'MOC cell order {0} must be in range 0-{1}'.format( order, max_cells - 1)) return cell pymoc-0.5.2/lib/pymoc/util/000077500000000000000000000000001465323524600155315ustar00rootroot00000000000000pymoc-0.5.2/lib/pymoc/util/__init__.py000066400000000000000000000000001465323524600176300ustar00rootroot00000000000000pymoc-0.5.2/lib/pymoc/util/catalog.py000066400000000000000000000155271465323524600175270ustar00rootroot00000000000000# Copyright (C) 2015-2017 East Asian Observatory. # # 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 . from __future__ import absolute_import from math import pi from astropy.coordinates import SkyCoord from astropy.io import ascii from astropy.units import arcsecond, hour, degree, radian from astropy.units.quantity import Quantity from healpy import query_disc from healpy.pixelfunc import \ ang2pix, ang2vec, get_all_neighbours, pix2ang, vec2pix import numpy as np from ..moc import MOC def catalog_to_moc(catalog, radius, order, **kwargs): """ Convert a catalog to a MOC. The catalog is given as an Astropy SkyCoord object containing multiple coordinates. The radius of catalog entries can be given as an Astropy Quantity (with units), otherwise it is assumed to be in arcseconds. Any additional keyword arguments are passed on to `catalog_to_cells`. """ # Generate list of MOC cells. cells = catalog_to_cells(catalog, radius, order, **kwargs) # Create new MOC object using our collection of cells. moc = MOC(moctype='CATALOG') moc.add(order, cells, no_validation=True) return moc def _catalog_to_cells_neighbor(catalog, radius, order): """ Convert a catalog to a list of cells. This is the original implementation of the `catalog_to_cells` function which does not make use of the Healpy `query_disc` routine. Note: this function uses a simple flood-filling approach and is very slow, especially when used with a large radius for catalog objects or a high resolution order. """ if not isinstance(radius, Quantity): radius = radius * arcsecond nside = 2 ** order # Ensure catalog is in ICRS coordinates. catalog = catalog.icrs # Determine central cell for each catalog entry. phi = catalog.ra.radian theta = (pi / 2) - catalog.dec.radian cells = np.unique(ang2pix(nside, theta, phi, nest=True)) # Iteratively consider the neighbors of cells within our # catalog regions. new_cells = cells rejected = np.array((), dtype=np.int64) while True: # Find new valid neighboring cells which we didn't already # consider. neighbors = np.unique(np.ravel( get_all_neighbours(nside, new_cells, nest=True))) neighbors = np.extract( [(x != -1) and (x not in cells) and (x not in rejected) for x in neighbors], neighbors) # Get the coordinates of each of these neighbors and compare them # to the catalog entries. (theta, phi) = pix2ang(nside, neighbors, nest=True) coords = SkyCoord(phi, (pi / 2) - theta, frame='icrs', unit='rad') (idx, sep2d, dist3d) = coords.match_to_catalog_sky(catalog) within_range = (sep2d < radius) # If we didn't find any new cells within range, # end the iterative process. if not np.any(within_range): break new_cells = neighbors[within_range] cells = np.concatenate((cells, new_cells)) rejected = np.concatenate(( rejected, neighbors[np.logical_not(within_range)])) return cells def catalog_to_cells(catalog, radius, order, include_fallback=True, **kwargs): """ Convert a catalog to a set of cells. This function is intended to be used via `catalog_to_moc` but is available for separate usage. It takes the same arguments as that function. This function uses the Healpy `query_disc` function to get a list of cells for each item in the catalog in turn. Additional keyword arguments, if specified, are passed to `query_disc`. This can include, for example, `inclusive` (set to `True` to include cells overlapping the radius as well as those with centers within it) and `fact` (to control sampling when `inclusive` is specified). If cells at the given order are bigger than the given radius, then `query_disc` may find none inside the radius. In this case, if `include_fallback` is `True` (the default), the cell at each position is included. If the given radius is zero (or smaller) then Healpy `query_disc` is not used -- instead the fallback position is used automatically. """ nside = 2 ** order # Ensure catalog is in ICRS coordinates. catalog = catalog.icrs # Ensure radius is in radians. if isinstance(radius, Quantity): radius = radius.to(radian).value else: radius = radius * pi / (180.0 * 3600.0) # Convert coordinates to position vectors. phi = catalog.ra.radian theta = (pi / 2) - catalog.dec.radian vectors = ang2vec(theta, phi) # Ensure we can iterate over vectors (it might be a single position). if catalog.isscalar: vectors = [vectors] # Query for a list of cells for each catalog position. cells = set() for vector in vectors: if radius > 0.0: # Try "disc" query. vector_cells = query_disc(nside, vector, radius, nest=True, **kwargs) if vector_cells.size > 0: cells.update(vector_cells.tolist()) continue elif not include_fallback: continue # The query didn't find anything -- include the cell at the # given position at least. cell = vec2pix(nside, vector[0], vector[1], vector[2], nest=True) cells.add(cell.item()) return cells def read_ascii_catalog(filename, format_, unit=None): """ Read an ASCII catalog file using Astropy. This routine is used by pymoctool to load coordinates from a catalog file in order to generate a MOC representation. """ catalog = ascii.read(filename, format=format_) columns = catalog.columns if 'RA' in columns and 'Dec' in columns: if unit is None: unit = (hour, degree) coords = SkyCoord(catalog['RA'], catalog['Dec'], unit=unit, frame='icrs') elif 'Lat' in columns and 'Lon' in columns: if unit is None: unit = (degree, degree) coords = SkyCoord(catalog['Lon'], catalog['Lat'], unit=unit, frame='galactic') else: raise Exception('columns RA,Dec or Lon,Lat not found') return coords pymoc-0.5.2/lib/pymoc/util/plot.py000066400000000000000000000104221465323524600170600ustar00rootroot00000000000000# Copyright (C) 2013-2014 Science and Technology Facilities Council. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import healpy from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt import numpy as np def plot_moc(moc, order=None, antialias=0, filename=None, projection='cart', color='blue', title='', coord_sys='C', graticule=True, **kwargs): """Plot a MOC using Healpy. This generates a plot of the MOC at the specified order, or the MOC's current order if this is not specified. The MOC is flattened at an order of `order + antialias` to generate intermediate color levels. :param order: HEALPix order at which to generate the plot. :param antialias: number of additional HEALPix orders to use for intermediate color levels. (There can be `4 ** antialias` levels.) :param filename: file in which to save plot. If not specified then the plot is shown with `plt.show()`. :param projection: map projection to be used --- can be shortened to 4 characters. One of: * `'cart[esian]'` (uses `healpy.visufunc.cartview`) * `'moll[weide]'` (uses `healpy.visufunc.mollview`) * `'gnom[onic]'` (uses `healpy.visufunc.gnomview`) :param color: color scheme. One of: * `'blue'` * `'green'` * `'red'` * `'black'` :param title: title of the plot. :param coord_sys: Healpy coordinate system code for the desired plot coordinates. One of: * `'C'` --- Celestial (equatorial) * `'G'` --- Galactic * `'E'` --- Ecliptic :param graticule: whether or not to draw a graticule. :param \*\*kwargs: passed to the selected Healpy plotting function. """ # Process arguments. plotargs = {'xsize': 3200, 'cbar': False, 'notext': True} if order is None: order = moc.order if projection.startswith('cart'): plotter = healpy.visufunc.cartview elif projection.startswith('moll'): plotter = healpy.visufunc.mollview elif projection.startswith('gnom'): plotter = healpy.visufunc.gnomview else: raise ValueError('Unknown projection: {0}'.format(projection)) if color == 'blue': plotargs['cmap'] = LinearSegmentedColormap.from_list( 'white-blue', ['#FFFFFF', '#0000AA']) elif color == 'green': plotargs['cmap'] = LinearSegmentedColormap.from_list( 'white-green', ['#FFFFFF', '#008800']) elif color == 'red': plotargs['cmap'] = LinearSegmentedColormap.from_list( 'white-red', ['#FFFFFF', '#FF0000']) elif color == 'black': plotargs['cmap'] = LinearSegmentedColormap.from_list( 'white-black', ['#FFFFFF', '#000000']) else: raise ValueError('Unknown color: {0}'.format(color)) if coord_sys == 'C': pass elif coord_sys == 'G': plotargs['coord'] = ('C', 'G') elif coord_sys == 'E': plotargs['coord'] = ('C', 'E') else: raise ValueError('Unknown coordinate system: {0}'.format(coord_sys)) # Any other arguments are passed the Healpy plotter directly. plotargs.update(kwargs) # Create a Numpy array which is zero for points outside the MOC and one # for points inside the MOC. map = np.zeros(12 * 4 ** order) antialias_shift = 2 * antialias for cell in moc.flattened(order + antialias): map[cell >> antialias_shift] += 1.0 # Plot the Numpy array using Healpy. plotter(map, nest=True, title=title, **plotargs) if graticule: healpy.visufunc.graticule() if filename is not None: plt.savefig(filename) else: plt.show() pymoc-0.5.2/lib/pymoc/util/tool.py000066400000000000000000000316631465323524600170710ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # Copyright (C) 2015-2017 East Asian Observatory. # # 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 . """pymoctool - PyMOC utility program Usage:: pymoctool [INPUT]... [COMMAND [FILE]]... [--output OUTPUT] This program can be used to manipulate MOC files. All formats handled by PyMOC (FITS, JSON and ASCII) are supported. The program maintains a "running" MOC into which all input files are merged. Each command operates on the "running" MOC. Input files and commands are processed in the order given to the command. For example, this command:: pymoctool a.fits --output a.json b.fits --output merged.txt would load a MOC "a.fits", re-write it as "a.json", merge (forming the union with) "b.fits" and write the combined MOC to "merged.txt". """ from __future__ import absolute_import, print_function import os.path import sys import textwrap from .. import MOC from ..io.ascii import read_moc_ascii, write_moc_ascii from ..version import version class CommandDict(dict): """Decorator to record commands in a dictionary.""" def __init__(self): """Constructor.""" dict.__init__(self) self.documentation = {} def __call__(self, *aliases): """Callable method. Adds the function which it is decorating to the dictionary, indexed by each of the given command aliases. """ def command(f): for alias in aliases: self[alias] = f self.documentation[aliases[0].lstrip('-')] = (aliases, f.__doc__) return f return command class CommandError(Exception): """Class representing expected errors from PyMOC tool commands.""" pass class MOCTool(object): """Class implementing a basic tool to manipulate MOC files.""" command = CommandDict() def __init__(self): """Constructor. Initializes the running MOC object to None. """ self.moc = None def run(self, params): """Main run method for PyMOC tool. Takes a list of command line arguments to process. Each operation is performed on a current "running" MOC object. """ self.params = list(reversed(params)) if not self.params: self.help() return while self.params: p = self.params.pop() if p in self.command: # If we got a known command, execute it. self.command[p](self) elif p == '-': self.read_moc_stdin() elif os.path.exists(p): # If we were given the name of an existing file, read it. self.read_moc(p) else: # Otherwise raise an error. raise CommandError('file or command {0} not found'.format(p)) def read_moc(self, filename): """Read a file into the current running MOC object. If the running MOC object has not yet been created, then it is created by reading the file, which will import the MOC metadata. Otherwise the metadata are not imported. """ if self.moc is None: self.moc = MOC(filename=filename) else: self.moc.read(filename) def read_moc_stdin(self): """Read from stdin into the current running MOC object. Create the running MOC object if it does not already exist, then attempt to read ASCII format data from standard input. """ if self.moc is None: self.moc = MOC() read_moc_ascii(self.moc, file=sys.stdin) @command('--catalog') def catalog(self): """Create MOC from catalog of coordinates. This command requires that the Healpy and Astropy libraries be available. It attempts to load the given catalog, and merges it with the running MOC. The name of an ASCII catalog file should be given. The file should contain either "RA" and "Dec" columns (for ICRS coordinates) or "Lon" and "Lat" columns (for galactic coordinates). The MOC order and radius (in arcseconds) can be given with additional options. :: pymoctool --catalog coords.txt [order 12] [radius 3600] [unit (hour | deg | rad) (deg | rad)] [format commented_header] [inclusive] Units (if not specified) are assumed to be hours and degrees for ICRS coordinates and degrees for galactic coordinates. The format, if not specified (as an Astropy ASCII table format name) is assumed to be commented header, e.g.: :: # RA Dec 01:30:00 +45:00:00 22:30:00 +45:00:00 """ from .catalog import catalog_to_moc, read_ascii_catalog filename = self.params.pop() order = 12 radius = 3600 unit = None format_ = 'commented_header' kwargs = {} while self.params: if self.params[-1] == 'order': self.params.pop() order = int(self.params.pop()) elif self.params[-1] == 'radius': self.params.pop() radius = float(self.params.pop()) elif self.params[-1] == 'unit': self.params.pop() unit_x = self.params.pop() unit_y = self.params.pop() unit = (unit_x, unit_y) elif self.params[-1] == 'format': self.params.pop() format_ = self.params.pop() elif self.params[-1] == 'inclusive': self.params.pop() kwargs['inclusive'] = True else: break coords = read_ascii_catalog(filename, format_=format_, unit=unit) catalog_moc = catalog_to_moc(coords, radius, order, **kwargs) if self.moc is None: self.moc = catalog_moc else: self.moc += catalog_moc @command('--help', '-h') def help(self): """Display command usage information.""" if self.params: command = self.params.pop().lstrip('-') if command in self.command.documentation: (aliases, doc) = self.command.documentation[command] (synopsis, body) = self._split_docstring(doc) print(synopsis) if body: print() print(body) else: raise CommandError('command {0} not known'.format(command)) else: (synopsis, body) = self._split_docstring(__doc__) print(synopsis) print() print(body) print() print('Commands:') for command in sorted(self.command.documentation.keys()): print(' ', ', '.join(self.command.documentation[command][0])) print() print('Use "pymoctool --help COMMAND" for additional ' 'information about a command.') @command('--id') def identifier(self): """Set the identifier of the current MOC. The new identifier should be given after this option. :: pymoctool ... --id 'New MOC identifier' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.id = self.params.pop() @command('--info', '-i') def display_info(self): """Display basic information about the running MOC.""" if self.moc is None: print('No MOC information present') return if self.moc.name is not None: print('Name:', self.moc.name) if self.moc.id is not None: print('Identifier:', self.moc.id) print('Order:', self.moc.order) print('Cells:', self.moc.cells) print('Area:', self.moc.area_sq_deg, 'square degrees') @command('--intersection') def intersection(self): """Compute the intersection with the given MOC. This command takes the name of a MOC file and forms the intersection of the running MOC with that file. :: pymoctool a.fits --intersection b.fits --output intersection.fits """ if self.moc is None: raise CommandError('No MOC information present for intersection') filename = self.params.pop() self.moc = self.moc.intersection(MOC(filename=filename)) @command('--name') def name(self): """Set the name of the current MOC. The new name should be given after this option. :: pymoctool ... --name 'New MOC name' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.name = self.params.pop() @command('--normalize') def normalize(self): """Normalize the MOC to a given order. This command takes a MOC order (0-29) and normalizes the MOC so that its maximum order is the given order. :: pymoctool a.fits --normalize 10 --output a_10.fits """ if self.moc is None: raise CommandError('No MOC information present for normalization') order = int(self.params.pop()) self.moc.normalize(order) @command('--output', '-o') def write_moc(self): """Write the MOC to a given file.""" if self.moc is None: raise CommandError('No MOC information present for output') filename = self.params.pop() if filename == '-': write_moc_ascii(self.moc, file=sys.stdout) print() else: self.moc.write(filename) @command('--subtract') def subtract(self): """Subtract the given MOC from the running MOC. This command takes the name of a MOC file to be subtracted from the running MOC. :: pymoctool a.fits --subtract b.fits --output difference.fits """ if self.moc is None: raise CommandError('No MOC information present for subtraction') filename = self.params.pop() self.moc -= MOC(filename=filename) @command('--plot') def plot(self): """Show the running MOC on an all-sky map. This command requires that the Healpy and matplotlib libraries be available. It plots the running MOC, which should be normalized to a lower order first if it would generate an excessively large pixel array. :: pymoctool a.moc --normalize 8 --plot It also accepts additional arguments which can be used to control the plot. The 'order' option can be used instead of normalizing the MOC before plotting. The 'antialias' option specifies an additional number of MOC orders which should be used to smooth the edges as plotted -- 1 or 2 is normally sufficient. The 'file' option can be given to specify a file to which the plot should be saved. :: pymoctool ... --plot [order ] [antialias ] [file ] ... """ if self.moc is None: raise CommandError('No MOC information present for plotting') from .plot import plot_moc order = self.moc.order antialias = 0 filename = None while self.params: if self.params[-1] == 'order': self.params.pop() order = int(self.params.pop()) elif self.params[-1] == 'antialias': self.params.pop() antialias = int(self.params.pop()) elif self.params[-1] == 'file': self.params.pop() filename = self.params.pop() else: break plot_moc(self.moc, order=order, antialias=antialias, filename=filename, projection='moll') @command('--version') def version(self): """Show PyMOC version number.""" print('PyMOC', version) def _split_docstring(self, docstring): """Separate a docstring into the synopsis (first line) and body.""" lines = docstring.strip().splitlines() synopsis = lines[0].strip() body = textwrap.dedent('\n'.join(lines[2:])) # Remove RST preformatted text markers. body = body.replace('\n::\n', '') body = body.replace('::\n', ':') return (synopsis, body) pymoc-0.5.2/lib/pymoc/version.py000066400000000000000000000013171465323524600166150ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . version = '0.5.2' pymoc-0.5.2/requirements.txt000066400000000000000000000000101465323524600161320ustar00rootroot00000000000000astropy pymoc-0.5.2/scripts/000077500000000000000000000000001465323524600143465ustar00rootroot00000000000000pymoc-0.5.2/scripts/pymoctool000077500000000000000000000022021465323524600163150ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from __future__ import print_function from os.path import basename import sys from pymoc.util.tool import MOCTool, CommandError def main(): """Main routine to run the pymoc tool.""" name = basename(sys.argv[0]) tool = MOCTool() try: tool.run(sys.argv[1:]) except CommandError as e: print(name + ':', e.args[0], file=sys.stderr) sys.exit(1) if __name__ == '__main__': main() pymoc-0.5.2/setup.py000066400000000000000000000027611465323524600143770ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from distutils.core import setup import sys sys.path.insert(0, 'lib') from pymoc.version import version with open('README.rst') as f: long_description = f.read() setup( name='pymoc', version=version, description='Multi-Order Coverage map module for Python', long_description=long_description, author='Graham Bell', author_email='g.bell@eaobservatory.org', url='http://github.com/grahambell/pymoc', package_dir={'': 'lib'}, packages=['pymoc', 'pymoc.io', 'pymoc.util'], scripts=['scripts/pymoctool'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Topic :: Scientific/Engineering :: Astronomy', ], ) pymoc-0.5.2/test-extra/000077500000000000000000000000001465323524600147575ustar00rootroot00000000000000pymoc-0.5.2/test-extra/__init__.py000066400000000000000000000000001465323524600170560ustar00rootroot00000000000000pymoc-0.5.2/test-extra/test_operators_random.py000066400000000000000000000065521465323524600217560ustar00rootroot00000000000000# Copyright (C) 2016 East Asian Observatory. # # 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 . from random import sample from unittest import TestCase from pymoc import MOC class OperatorsRandomizedTestCase(TestCase): def test_operators(self): repeats = 10 order = 6 for i in range(0, repeats): # Make random MOCs, take difference and intersection. p = self._make_random_moc(order) q = self._make_random_moc(order) s_pq = p - q s_qp = q - p i_pq = p.intersection(q) i_qp = q.intersection(p) # p.write('test_moc_p_{}.fits'.format(i + 1), overwrite=True) # q.write('test_moc_q_{}.fits'.format(i + 1), overwrite=True) # s_pq.write('test_moc_pq_{}.fits'.format(i + 1), overwrite=True) # s_qp.write('test_moc_qp_{}.fits'.format(i + 1), overwrite=True) # i_pq.write('test_moc_i_{}.fits'.format(i + 1), overwrite=True) # Intersection should be the same both ways round. self.assertEqual(i_pq, i_qp) # Areas should add up to differences + 2 x intersection. self.assertAlmostEqual(p.area + q.area, s_pq.area + s_qp.area + 2 * i_pq.area, places=10) # Make differences and intersection via flattened set. p_flat = p.flattened(order=order) q_flat = q.flattened(order=order) s_pq_flat = p_flat - q_flat s_qp_flat = q_flat - p_flat i_flat = p_flat & q_flat # Compare with flattened-method version via MOC equality. self.assertEqual(s_pq, MOC(order, s_pq_flat)) self.assertEqual(s_qp, MOC(order, s_qp_flat)) self.assertEqual(i_pq, MOC(order, i_flat)) # Compare with flattened-method version via flat set. s_pq_flattened = s_pq.flattened(order=order) s_qp_flattened = s_qp.flattened(order=order) i_pq_flattened = i_pq.flattened(order=order) i_qp_flattened = i_qp.flattened(order=order) self.assertEqual(s_pq_flattened, s_pq_flat) self.assertEqual(s_qp_flattened, s_qp_flat) self.assertEqual(i_pq_flattened, i_flat) self.assertEqual(i_qp_flattened, i_flat) # Differences and intersection should be disjoint. self.assertTrue(s_pq_flattened.isdisjoint(s_qp_flattened)) self.assertTrue(s_pq_flattened.isdisjoint(i_pq_flattened)) self.assertTrue(s_qp_flattened.isdisjoint(i_pq_flattened)) def _make_random_moc(self, order): m = MOC() for order_i in range(0, order + 1): m.add(order_i, sample(range(0, 12 * 4 ** order_i), 4 ** order_i)) return m pymoc-0.5.2/test/000077500000000000000000000000001465323524600136365ustar00rootroot00000000000000pymoc-0.5.2/test/__init__.py000066400000000000000000000000001465323524600157350ustar00rootroot00000000000000pymoc-0.5.2/test/test_area.py000066400000000000000000000075421465323524600161670ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from math import sqrt from unittest import TestCase from pymoc import MOC class AreaTestCase(TestCase): def test_orders(self): # Test the size of one cell of each order against the values # given in the MOC recommendation. m = MOC(0, [0]) self.assertAlmostEqual(sqrt(m.area_sq_deg), 58.63, places=2) m = MOC(1, [0]) self.assertAlmostEqual(sqrt(m.area_sq_deg), 29.32, places=2) m = MOC(2, [0]) self.assertAlmostEqual(sqrt(m.area_sq_deg), 14.66, places=2) m = MOC(3, [0]) self.assertAlmostEqual(sqrt(m.area_sq_deg), 7.329, places=3) m = MOC(4, [0]) self.assertAlmostEqual(sqrt(m.area_sq_deg), 3.665, places=3) m = MOC(5, [0]) self.assertAlmostEqual(sqrt(m.area_sq_deg), 1.832, places=3) m = MOC(6, [0]) self.assertAlmostEqual(60 * sqrt(m.area_sq_deg), 54.97, places=2) m = MOC(7, [0]) self.assertAlmostEqual(60 * sqrt(m.area_sq_deg), 27.48, places=2) m = MOC(8, [0]) self.assertAlmostEqual(60 * sqrt(m.area_sq_deg), 13.74, places=2) m = MOC(9, [0]) self.assertAlmostEqual(60 * sqrt(m.area_sq_deg), 6.871, places=3) m = MOC(10, [0]) self.assertAlmostEqual(60 * sqrt(m.area_sq_deg), 3.435, places=3) m = MOC(11, [0]) self.assertAlmostEqual(60 * sqrt(m.area_sq_deg), 1.718, places=3) m = MOC(12, [0]) self.assertAlmostEqual(3600 * sqrt(m.area_sq_deg), 51.53, places=2) m = MOC(13, [0]) self.assertAlmostEqual(3600 * sqrt(m.area_sq_deg), 25.77, places=2) m = MOC(14, [0]) self.assertAlmostEqual(3600 * sqrt(m.area_sq_deg), 12.88, places=2) m = MOC(15, [0]) self.assertAlmostEqual(3600 * sqrt(m.area_sq_deg), 6.442, places=3) m = MOC(16, [0]) self.assertAlmostEqual(3600 * sqrt(m.area_sq_deg), 3.221, places=3) m = MOC(17, [0]) self.assertAlmostEqual(3600 * sqrt(m.area_sq_deg), 1.610, places=3) m = MOC(18, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 805.2, places=1) m = MOC(19, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 402.6, places=1) m = MOC(20, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 201.3, places=1) m = MOC(21, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 100.6, places=1) m = MOC(22, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 50.32, places=2) m = MOC(23, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 25.16, places=2) m = MOC(24, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 12.58, places=2) m = MOC(25, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 6.291, places=3) m = MOC(26, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 3.145, places=3) m = MOC(27, [0]) self.assertAlmostEqual(3600E3 * sqrt(m.area_sq_deg), 1.573, places=3) m = MOC(28, [0]) self.assertAlmostEqual(3600E6 * sqrt(m.area_sq_deg), 786.3, places=1) m = MOC(29, [0]) self.assertAlmostEqual(3600E6 * sqrt(m.area_sq_deg), 393.2, places=1) pymoc-0.5.2/test/test_ascii.py000066400000000000000000000053541465323524600163460ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # Copyright (C) 2017-2024 East Asian Observatory. # # 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 . from __future__ import unicode_literals from io import StringIO from unittest import TestCase from pymoc import MOC from pymoc.io.ascii import read_moc_ascii, write_moc_ascii class ASCIITestCase(TestCase): def test_ascii(self): test_ascii = '1/1,3,4 2/4,25,12-14,21' test_ascii_sorted = '1/1,3,4 2/4,12-14,21,25' in_ = StringIO(test_ascii) moc = MOC() read_moc_ascii(moc, file=in_) self.assertEqual(moc.order, 2) self.assertEqual(moc[0], frozenset()) self.assertEqual(moc[1], frozenset([1, 3, 4])) self.assertEqual(moc[2], frozenset([4, 12, 13, 14, 21, 25])) out = StringIO() write_moc_ascii(moc, file=out) self.assertEqual(out.getvalue(), test_ascii_sorted) def test_ascii_empty(self): in_ = StringIO('') moc = MOC() read_moc_ascii(moc, file=in_) self.assertEqual(moc.order, 0) self.assertEqual(moc[0], frozenset()) def test_ascii_trailing(self): # Check MOC 1.1 addition of trailing section to # signify the MOCORDER. in_ = StringIO('13/5,6,7 14/') moc = MOC() read_moc_ascii(moc, file=in_) self.assertEqual(moc[13], frozenset([5, 6, 7])) self.assertEqual(moc[14], frozenset()) def test_ascii_large(self): orig = MOC() orig.add(29, [ 3458700000000000000, 3458700000000000007, 3458700000000000008, 3458700000000000009, ]) out = StringIO() write_moc_ascii(orig, file=out) text = out.getvalue() self.assertEqual( text, '29/3458700000000000000,' '3458700000000000007-3458700000000000009') copy = MOC() in_ = StringIO(text) read_moc_ascii(copy, file=in_) self.assertEqual(copy.order, 29) self.assertEqual(copy.cells, 4) self.assertEqual(copy[29], frozenset([ 3458700000000000000, 3458700000000000007, 3458700000000000008, 3458700000000000009])) pymoc-0.5.2/test/test_catalog.py000066400000000000000000000065501465323524600166670ustar00rootroot00000000000000# Copyright (C) 2017 East Asian Observatory. # # 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 . from unittest import TestCase from astropy.coordinates import SkyCoord from pymoc import MOC from pymoc.util.catalog import catalog_to_moc, catalog_to_cells class CatalogTestCase(TestCase): def test_cells(self): # Catalog with an entry at cell 30000 (order 6: ~1 deg. res.) catalog = SkyCoord(303.75, -4.18152827, frame='icrs', unit='deg') cells = catalog_to_cells(catalog, 60, 6, include_fallback=False) self.assertEqual(cells, set((30000,))) # Nudge position so it no longer matches: no result without fallback. catalog = SkyCoord(303.50, -4.18152827, frame='icrs', unit='deg') cells = catalog_to_cells(catalog, 60, 6, include_fallback=False) self.assertEqual(cells, set(())) cells = catalog_to_cells(catalog, 60, 6, include_fallback=True) self.assertEqual(cells, set((30000,))) # Catalog with two entries: compare to results from flood-fill method. catalog = SkyCoord([100.0, 200.0], [40.0, 60.0], frame='icrs', unit='deg') cells = catalog_to_cells(catalog, 3600, 7) self.assertEqual(cells, set(( 26860, 26861, 26862, 26863, 26866, 26867, 26872, 26873, 26874, 26875, 27204, 27205, 27206, 27207, 27216, 44535, 44540, 44541, 44543, 47264, 47265, 47266, 47267, 47268, 47270, 47271, 47272, 47273, 47274, 47276, ))) # Test inclusive option: should add extra cells. inclusive = catalog_to_cells(catalog, 3600, 7, inclusive=True) self.assertGreater(len(inclusive), len(cells)) self.assertTrue(inclusive.issuperset(cells)) # Test a cell close to a boundary. catalog = SkyCoord(44.978, 1.304, frame='icrs', unit='deg') cells = catalog_to_cells(catalog, 10, 12, inclusive=True) self.assertEqual(cells, set((12344, 12345, 12346, 12347,))) cells = catalog_to_cells(catalog, 0, 12, inclusive=True) self.assertEqual(cells, set((12344,))) def test_catalog(self): catalog = SkyCoord([150.0, 300.0], [-45.0, 45.0], frame='icrs', unit='deg') moc = catalog_to_moc(catalog, 0.5, 20) self.assertIsInstance(moc, MOC) self.assertEqual(moc.type, 'CATALOG') expected = MOC() expected.add(19, [ 994284930659, 994284930660, 994284930662, 2579127859609, 2579127859611, 2579127859612]) expected.add(20, [ 3977139722630, 3977139722631, 3977139722644, 3977139722646, 3977139722652, 3977139722661, 10316511438426, 10316511438435, 10316511438441, 10316511438443, 10316511438456, 10316511438457]) self.assertEqual(moc, expected) pymoc-0.5.2/test/test_fits.py000066400000000000000000000066271465323524600162270ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from unittest import TestCase from pymoc import MOC from pymoc.io.fits import read_moc_fits_hdu, write_moc_fits_hdu class FITSTestCase(TestCase): def test_fits(self): orig = MOC() orig.add(10, [5, 6, 7, 8]) orig.add(11, [1000, 1001, 2000]) hdu = write_moc_fits_hdu(orig) copy = MOC() read_moc_fits_hdu(copy, hdu) self.assertEqual(copy.order, 11) self.assertEqual(copy[10], frozenset([5, 6, 7, 8])) self.assertEqual(copy[11], frozenset([1000, 1001, 2000])) def test_fits_large_32(self): orig = MOC() orig.add(13, [805306367]) hdu = write_moc_fits_hdu(orig) self.assertIn('J', hdu.header['TFORM1']) copy = MOC() read_moc_fits_hdu(copy, hdu) self.assertEqual(copy.order, 13) self.assertEqual(copy[13], frozenset([805306367])) def test_fits_64(self): orig = MOC() orig.add(14, [0]) hdu = write_moc_fits_hdu(orig) self.assertIn('K', hdu.header['TFORM1']) copy = MOC() read_moc_fits_hdu(copy, hdu) self.assertEqual(copy.order, 14) self.assertEqual(copy[14], frozenset([0])) def test_fits_large_64(self): orig = MOC() orig.add(29, [3458700000000000000]) hdu = write_moc_fits_hdu(orig) self.assertIn('K', hdu.header['TFORM1']) copy = MOC() read_moc_fits_hdu(copy, hdu) self.assertEqual(copy.order, 29) self.assertEqual(copy[29], frozenset([3458700000000000000])) def test_fits_meta(self): # Write a FITS HDU including metadata and read it back. orig = MOC(order=10, cells=(4, 5, 6, 7), name='test-moc', mocid='ivo://TEST/...', origin='ivo://TEST', moctype='image') hdu = write_moc_fits_hdu(orig) copy = MOC() read_moc_fits_hdu(copy, hdu, include_meta=True) self.assertEqual(copy.name, 'test-moc') self.assertEqual(copy.id, 'ivo://TEST/...') self.assertEqual(copy.origin, 'ivo://TEST') self.assertEqual(copy.type, 'IMAGE') # Check that the MOC was normalized. self.assertEqual(copy.cells, 1) # Now check we do not overwrite metadata unless requested. other = MOC(order=10, cells=(4, 5, 6, 7), name='test-moc-modified', mocid='ivo://TEST2/...', origin='ivo://TEST2', moctype='catalog') read_moc_fits_hdu(other, hdu, include_meta=False) self.assertEqual(other.name, 'test-moc-modified') self.assertEqual(other.id, 'ivo://TEST2/...') self.assertEqual(other.origin, 'ivo://TEST2') self.assertEqual(other.type, 'CATALOG') pymoc-0.5.2/test/test_flatten.py000066400000000000000000000024461465323524600167120ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from unittest import TestCase from pymoc import MOC class FlattenTestCase(TestCase): def test_flattened(self): p = MOC(4, (11, 12)) self.assertEqual(p.flattened(), set((11, 12))) q = p + MOC(3, (0,)) self.assertEqual(q.flattened(), set((0, 1, 2, 3, 11, 12))) q = p + MOC(5, (55,)) self.assertEqual(q.flattened(4), set((11, 12, 13))) self.assertEqual(q.flattened(4, False), set((11, 12))) self.assertEqual(q.flattened(5), set((44, 45, 46, 47, 48, 49, 50, 51, 55))) pymoc-0.5.2/test/test_json.py000066400000000000000000000050041465323524600162170ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # Copyright (C) 2017-2024 East Asian Observatory. # # 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 . from __future__ import unicode_literals from io import BytesIO from unittest import TestCase from pymoc import MOC from pymoc.io.json import read_moc_json, write_moc_json class JSONTestCase(TestCase): def test_json(self): test_json = b'{"1":[1,2,4],"2":[12,13,14,21,23,25]}' in_ = BytesIO(test_json) moc = MOC() read_moc_json(moc, file=in_) self.assertEqual(moc.order, 2) self.assertEqual(moc[0], frozenset()) self.assertEqual(moc[1], frozenset([1, 2, 4])) self.assertEqual(moc[2], frozenset([12, 13, 14, 21, 23, 25])) out = BytesIO() write_moc_json(moc, file=out) self.assertEqual(out.getvalue(), test_json) def test_json_trailing(self): # Check MOC 1.1 addition of trailing section to # signify the MOCORDER. in_ = BytesIO(b'{"13":[5,6,7],"14":[]}') moc = MOC() read_moc_json(moc, file=in_) self.assertEqual(moc[13], frozenset([5, 6, 7])) self.assertEqual(moc[14], frozenset()) def test_json_large(self): orig = MOC() orig.add(29, [ 3458700000000000000, 3458700000000000007, 3458700000000000008, 3458700000000000009, ]) out = BytesIO() write_moc_json(orig, file=out) json = out.getvalue() self.assertEqual( json, b'{"29":[3458700000000000000,3458700000000000007,' b'3458700000000000008,3458700000000000009]}') copy = MOC() in_ = BytesIO(json) read_moc_json(copy, file=in_) self.assertEqual(copy.order, 29) self.assertEqual(copy.cells, 4) self.assertEqual(copy[29], frozenset([ 3458700000000000000, 3458700000000000007, 3458700000000000008, 3458700000000000009])) pymoc-0.5.2/test/test_meta.py000066400000000000000000000030401465323524600161720ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from unittest import TestCase from pymoc import MOC class MetadataTestCase(TestCase): def test_metadata(self): m = MOC(name='test-moc', mocid='ivo://TEST/...', origin='ivo://TEST', moctype='image') self.assertEqual(m.name, 'test-moc') self.assertEqual(m.id, 'ivo://TEST/...') self.assertEqual(m.origin, 'ivo://TEST') self.assertEqual(m.type, 'IMAGE') m.type = 'catalog' m.name = 'test-moc-modified' m.id = 'ivo://TEST2/...' m.origin = 'ivo://TEST2' self.assertEqual(m.name, 'test-moc-modified') self.assertEqual(m.id, 'ivo://TEST2/...') self.assertEqual(m.origin, 'ivo://TEST2') self.assertEqual(m.type, 'CATALOG') with self.assertRaises(ValueError): m.type = 'something other than image or catalog' pymoc-0.5.2/test/test_normalize.py000066400000000000000000000031621465323524600172510ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from unittest import TestCase from pymoc import MOC class NormalizeTestCase(TestCase): def test_aggregate(self): m = MOC(10, set([0, 1, 2, 3, 4])) self.assertEqual(m.order, 10) self.assertEqual(m[10], frozenset([0, 1, 2, 3, 4])) self.assertEqual(m[9], frozenset()) m.normalize() self.assertEqual(m.order, 10) self.assertEqual(m[10], frozenset([4])) self.assertEqual(m[9], frozenset([0])) def test_included(self): m = MOC(10, set([0, 1, 2, 3, 4])) m.add(8, set([0])) self.assertEqual(m.order, 10) self.assertEqual(m[8], frozenset([0])) self.assertEqual(m[9], frozenset()) self.assertEqual(m[10], frozenset([0, 1, 2, 3, 4])) m.normalize() self.assertEqual(m.order, 8) self.assertEqual(m[8], frozenset([0])) self.assertEqual(m[9], frozenset()) self.assertEqual(m[10], frozenset()) pymoc-0.5.2/test/test_operators.py000066400000000000000000000124211465323524600172650ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from unittest import TestCase from pymoc import MOC class OperatorsTestCase(TestCase): def test_eq(self): self.assertEqual( MOC(1, (4,)), MOC(2, (16, 17, 18, 19))) self.assertEqual( MOC(4, (5, 6)), MOC(4, (6, 5))) self.assertNotEqual( MOC(4, (5, 6)), MOC(4, (5, 6, 7))) self.assertNotEqual( MOC(5, (10,)), MOC(6, (10,))) self.assertNotEqual( MOC(3, (4, 5, 6)), MOC(3, (4, 5, 6)) + MOC(10, (0,))) def test_iadd(self): p = MOC(4, (11, 12)) p.add(5, (100,)) q = MOC(4, (13,)) q.add(5, (101,)) p += q self.assertEqual(p.cells, 5) self.assertEqual(sorted(p[4]), [11, 12, 13]) self.assertEqual(sorted(p[5]), [100, 101]) def test_contains(self): m = MOC() m.add(0, (10, 11)) m.add(1, (36, 37)) m.add(2, (128, 129)) m.add(3, (448, 499)) self.assertEqual(m.contains(0, 10), True) self.assertEqual(m.contains(0, 11), True) self.assertEqual(m.contains(0, 0, True), False) self.assertEqual(m.contains(0, 0, False), False) self.assertEqual(m.contains(1, 40), True) self.assertEqual(m.contains(2, 160), True) self.assertEqual(m.contains(0, 7, True), True) self.assertEqual(m.contains(0, 7, False), False) def test_copy(self): # TODO: check metadata copying p = MOC(1, (2, 3)) p.add(4, (5, 6)) q = p.copy() self.assertEqual(q.cells, 4) self.assertEqual(sorted(q[1]), [2, 3]) self.assertEqual(sorted(q[4]), [5, 6]) def test_clear(self): p = MOC() p.add(4, (5, 6)) p.add(0, (11,)) p.add(1, (42, 43, 44)) self.assertEqual(p.cells, 6) self.assertEqual(p.normalized, False) p.clear() self.assertEqual(p.cells, 0) self.assertEqual(p.normalized, True) def test_add(self): p = MOC(4, (11, 12)) p.add(5, (100,)) q = MOC(4, (13,)) q.add(5, (101,)) s = p + q # Check the original MOCs were not altered. self.assertEqual(p.cells, 3) self.assertEqual(q.cells, 2) # Check the sum is the union of p and q. self.assertEqual(s.cells, 5) self.assertEqual(sorted(s[4]), [11, 12, 13]) self.assertEqual(sorted(s[5]), [100, 101]) def test_remove(self): m = MOC(4, (10, 11, 12, 13)) m.remove(4, (10, 13)) self.assertEqual(m, MOC(4, (11, 12))) def test_isub(self): p = MOC(1, (3, 4, 5)) p -= MOC(1, (4,)) self.assertEqual(p, MOC(1, (3, 5))) def test_sub(self): p = MOC() p.add(1, (3, 4, 5)) q = MOC() q.add(0, (0,)) q.add(1, (5,)) q.add(2, (19,)) d = p - q self.assertEqual(d, MOC(2, (16, 17, 18))) def test_intersection(self): p = MOC(4, (10, 11, 12)) q = MOC(4, (9, 11, 13)) i = p.intersection(q) self.assertFalse(i.normalized) self.assertEqual(i, MOC(4, (11,))) p = MOC(0, (0,)) p.add(1, (4, 5, 6)) q = MOC(0, (1,)) q.add(1, (1, 2, 3)) i = p.intersection(q) self.assertFalse(i.normalized) self.assertEqual(i, MOC(1, (1, 2, 3, 4, 5, 6))) p = MOC(0, (1,)) q = MOC(2, (15, 19)) i = p.intersection(q) self.assertFalse(i.normalized) self.assertEqual(i, MOC(2, (19,))) p.add(0, (2,)) q.add(0, (2,)) i = p.intersection(q) self.assertFalse(i.normalized) self.assertEqual(i, MOC(0, (2,)) + MOC(2, (19,))) # Test of intersection with 2 levels difference. # (This test is based on GitHub issue #2.) p = MOC(4, (1024,)) q = MOC(6, (16385,)) i = p.intersection(q) self.assertFalse(i.normalized) self.assertEqual(i, MOC(6, (16385,))) i = q.intersection(p) self.assertFalse(i.normalized) self.assertEqual(i, MOC(6, (16385,))) # Test of intersection with values at multiple levels. p = MOC(1, (1,)) q = MOC() q.add(2, (4, 8)) q.add(3, (20, 192)) q.add(4, (96, 256)) expect = MOC() expect.add(2, (4,)) expect.add(3, (20,)) expect.add(4, (96,)) i = p.intersection(q) self.assertFalse(i.normalized) self.assertEqual(i, expect) i = q.intersection(p) self.assertFalse(i.normalized) self.assertEqual(i, expect) pymoc-0.5.2/test/test_properties.py000066400000000000000000000024721465323524600174500ustar00rootroot00000000000000# Copyright (C) 2014 Science and Technology Facilities Council. # # 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 . from unittest import TestCase from pymoc import MOC class PropertiesTestCase(TestCase): def test_properties(self): m = MOC(4, (11, 12)) self.assertEqual(m.normalized, False) self.assertEqual(m.order, 4) self.assertEqual(m.cells, 2) self.assertEqual(len(m), 1) m.add(5, (198, 199)) self.assertEqual(m.normalized, False) self.assertEqual(m.order, 5) self.assertEqual(m.cells, 4) self.assertEqual(len(m), 2) m.normalize() self.assertEqual(m.normalized, True) m.add(6, (1, 2)) self.assertEqual(m.normalized, False)