├── .gitignore ├── README.txt ├── gplv3.txt ├── planck ├── .gitignore ├── TODO ├── __init__.py ├── base.py ├── correction.py ├── create_siam.py ├── cut_planet.pro ├── fixperm.sh ├── focalplane.py ├── hfi.py ├── hitmap.py ├── lfi.py ├── maptools.py ├── metadata.py ├── pix2od.py ├── pointing.py ├── pointingtools.py ├── private_template.py ├── ps.py ├── test_correction.py ├── test_planck_LFI_HFI.py ├── test_pointing.py ├── test_pointingtools.py ├── toast.py └── utils.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | private.py 2 | .svn 3 | *.pyc 4 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | Python package for dealing with Planck satellite data 2 | part of the US Planck Test Environment 3 | 4 | license: GPL v3 5 | author: Andrea Zonca 6 | website: http://andreazonca.com 7 | 8 | this software needs data that are not publicly available in 9 | order to work [RIMO, SIAM, AHF], and are not included in the 10 | package, therefore you need to be part of the Planck Collaboration 11 | to use it. 12 | 13 | this software does not include any performance number or any other 14 | information covered by the Planck Data Agreement. 15 | 16 | If you are member of the Planck collaboration and interested in using 17 | and contributing to the software please contact me. 18 | 19 | Includes: 20 | 21 | * planck, LFI, HFI: metadata classes for LFI and HFI channels 22 | created dynamically from the Reduced Instrument Model (RIMO), 23 | not publicly available, not even channel names are available in 24 | this package. 25 | 26 | * pointing: pointing library which builds detector pointing from 27 | satellite quaternions, it is based on quaternionarray 28 | [http://github.com/zonca/quaternionarray] 29 | 30 | * utils, ps, hitmap: utilities for date conversion, angular power spectra 31 | and hitmaps 32 | -------------------------------------------------------------------------------- /gplv3.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /planck/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *swp 3 | ipython* 4 | *png 5 | *npy 6 | *txt 7 | *xml 8 | *swo 9 | -------------------------------------------------------------------------------- /planck/TODO: -------------------------------------------------------------------------------- 1 | toast: 2 | 3 | decouple Observations and EFF. 4 | 5 | create DataStream(TimeStream) and SimNoiseStream(TimeStream) 6 | that get the observations list and creates the streams. 7 | 8 | at write time: 9 | stack->push:noise_stream, push:real_stream,FLG [gets only the flags] 10 | 11 | -------------------------------------------------------------------------------- /planck/__init__.py: -------------------------------------------------------------------------------- 1 | from .lfi import LFI 2 | from .hfi import HFI 3 | from .base import Channel 4 | 5 | def parse_channels(chfreq): 6 | if chfreq is None: 7 | return None 8 | if isinstance(chfreq, list) and isinstance(chfreq[0], Channel): 9 | return chfreq 10 | else: 11 | pl = Planck() 12 | if isinstance(chfreq, int): 13 | return pl.f[chfreq].ch 14 | elif isinstance(chfreq, str): 15 | return [pl[chfreq]] 16 | elif isinstance(chfreq, list) and isinstance(chfreq[0], str): 17 | return [pl[tag] for tag in chfreq] 18 | 19 | def parse_channel(chfreq): 20 | if isinstance(chfreq, Channel): 21 | return chfreq 22 | else: 23 | pl = Planck() 24 | if isinstance(chfreq, str): 25 | return pl[chfreq] 26 | 27 | 28 | class Planck(object): 29 | '''Planck class, gives an iterator .ch for all LFI and HFI channels''' 30 | 31 | def __init__(self): 32 | self.inst = {'LFI':LFI(), 'HFI':HFI()} 33 | self.ch = [ch for inst in self.inst.values() for ch in inst.ch] 34 | self.f = dict((freq,f) for inst in self.inst.values() for freq,f in inst.f.items()) 35 | 36 | def __getitem__(self, key): 37 | try: 38 | return self.inst['LFI'][key] 39 | except KeyError: 40 | return self.inst['HFI'][key] 41 | -------------------------------------------------------------------------------- /planck/base.py: -------------------------------------------------------------------------------- 1 | from astropy.io import fits as pyfits 2 | import logging as l 3 | import numpy as np 4 | try: 5 | from exceptions import KeyError, ValueError 6 | except: 7 | pass 8 | import itertools 9 | import operator 10 | import collections 11 | from . import private 12 | 13 | def group_by_horn(chlist): 14 | return itertools.groupby(chlist, operator.attrgetter('horn')) 15 | 16 | class ChannelBase(object): 17 | '''Base for Channel, frequencyset and detector''' 18 | 19 | def __repr__(self): 20 | return self.tag 21 | 22 | def get_gaussian_beam(self, lmax=1024, pol=False, beam_eff=False): 23 | """Equivalent gaussian beam from RIMO FWHM 24 | 25 | Returns the transfer function of a gaussian beam until lmax, 26 | either polarized or not""" 27 | import healpy as hp 28 | beam = hp.gauss_beam( self.fwhm, lmax, pol) 29 | 30 | if beam_eff: 31 | beam *= self.beam_efficiency 32 | return beam 33 | 34 | class Channel(ChannelBase): 35 | '''Abstract channel class for LFI and HFI channels''' 36 | 37 | def __init__(self, data, inst=None): 38 | try: 39 | self.tag = data[0][0].strip().decode('unicode_escape') 40 | except: 41 | self.tag = data[0].strip() 42 | self.rimo = np.array(data) 43 | self.inst = inst 44 | 45 | @property 46 | def num(self): 47 | return self.f.ch.index(self) 48 | 49 | @property 50 | def arm(self): 51 | return self.tag[-1] 52 | 53 | @property 54 | def sampling_freq(self): 55 | return float(self.rimo['F_SAMP']) 56 | 57 | @property 58 | def white_noise(self): 59 | return float(self.rimo[self.inst.white_noise_field]) 60 | 61 | @property 62 | def pair(self): 63 | return self.inst[self.tag.replace(self.MS[self.n], self.MS[not self.n])] 64 | 65 | @property 66 | def n(self): 67 | return self.fromMS[self.arm] 68 | 69 | def get_beam_real(self, m_b, component='main'): 70 | """Return real""" 71 | if m_b == -1: 72 | return 2 * -1 * private.BEAM[component][self.tag][-m_b] 73 | else: 74 | return 2 * private.BEAM[component][self.tag][m_b] 75 | 76 | def get_beam_imag(self, m_b, component='main'): 77 | """Return imaginary""" 78 | if m_b == -1: 79 | return private.BEAM[component][self.tag][2] 80 | elif m_b == 0: 81 | return 0 82 | elif m_b == 1: 83 | return private.BEAM[component][self.tag][2] 84 | 85 | @property 86 | def fwhm(self): 87 | fwhm = self.get_instrument_db_field("FWHM") 88 | l.info("Channel %s: FWHM %.2f arcmin" % (self.tag, fwhm)) 89 | return np.radians(fwhm/60.), 90 | 91 | @property 92 | def beam_efficiency(self): 93 | import private 94 | try: 95 | return private.beam_efficiency[self.tag] / 100. 96 | except KeyError: 97 | l.warning("Missing beam efficiency for channel %s" % self.tag) 98 | return 1. 99 | 100 | def get_instrument_db_field(self, field): 101 | try: 102 | return self.inst.instrument_db(self)[field][0] 103 | except ValueError: 104 | return self.inst.instrument_db(self)[field.upper()][0] 105 | 106 | class FrequencySet(ChannelBase): 107 | def __init__(self, freq, ch, inst=None): 108 | self.freq = freq 109 | self.ch = ch 110 | self.inst = inst 111 | for ch in self.ch: 112 | ch.f = self 113 | self.tag = '%d' % self.freq 114 | self.f = self 115 | 116 | @property 117 | def horns(self): 118 | return group_by_horn(self.ch) 119 | 120 | def __repr__(self): 121 | return '%d GHz' % self.freq 122 | 123 | @property 124 | def sampling_freq(self): 125 | return self.ch[0].sampling_freq 126 | 127 | def get_aggregated_property(self, name): 128 | name_attrgetter = operator.attrgetter(name) 129 | return np.mean([name_attrgetter(ch) for ch in self.ch]) 130 | 131 | def __getattr__(self, name): 132 | return self.get_aggregated_property(name) 133 | 134 | def freq2inst(freq): 135 | return ['LFI','HFI'][freq>=100] 136 | 137 | EXCLUDED_CH = ['143-8', '545-3', '857-4'] 138 | 139 | class Instrument(object): 140 | '''Common base class for LFI and HFI''' 141 | 142 | Channel = Channel 143 | FrequencySet = FrequencySet 144 | 145 | def __init__(self, name, rimo): 146 | '''Rimo is full path to Reduced Instrument Model FITS file''' 147 | self.name = name 148 | self.rimo = rimo 149 | rimo_file = np.array(pyfits.open(rimo)[1].data) 150 | rimo_file.sort() 151 | self.rimo_fields = rimo_file.dtype.names 152 | self.ch = map(self.Channel, rimo_file, [self]*len(rimo_file)) 153 | self.ch = [ch for ch in self.ch if ch.tag not in EXCLUDED_CH] 154 | self.chdict = dict( (ch.tag, ch) for ch in self.ch) 155 | self.f = self.create_frequency_sets() 156 | 157 | def create_frequency_sets(self): 158 | freqs = [self.freq_from_tag(ch.tag) for ch in self.ch] 159 | f = collections.OrderedDict() 160 | for freq in sorted(set(freqs)): 161 | chlist = [self.ch[i] for i,chfreq in enumerate(freqs) if chfreq == freq] 162 | f[freq] = self.FrequencySet(freq, chlist, self) 163 | return f 164 | 165 | def instrument_db(self,ch): 166 | if not hasattr(self,'_instrument_db') or self._instrument_db is None: 167 | if isinstance(self.instrument_db_file, list): 168 | self.instrument_db_file = self.instrument_db_file[0] 169 | if isinstance(self.instrument_db_file, dict): 170 | self.instrument_db_file = self.instrument_db_file[self.name] 171 | self._instrument_db = np.array(pyfits.open(self.instrument_db_file,ignore_missing_end=True)[1].data) 172 | l.warning('Loading instrumentdb %s' % self.instrument_db_file) 173 | try: 174 | det_index, = np.where([rad[0].strip().endswith(ch.tag.encode()) for rad in self._instrument_db['Radiometer']]) 175 | except ValueError: 176 | det_index, = np.where([rad[0].strip().endswith(ch.tag.encode()) for rad in self._instrument_db['DETECTOR']]) 177 | return self._instrument_db[det_index] 178 | 179 | def __getitem__(self, key): 180 | return self.chdict[key] 181 | -------------------------------------------------------------------------------- /planck/correction.py: -------------------------------------------------------------------------------- 1 | import logging as l 2 | import pycfitsio 3 | import numpy as np 4 | from . import private 5 | 6 | class DummyClass: 7 | pass 8 | physcon = DummyClass() 9 | physcon.c = 2.997924580000e+08 10 | 11 | from dipole import SatelliteVelocity 12 | 13 | import quaternionarray as qarray 14 | import glob 15 | 16 | #from tabulate_corrections_calc import TabulatedAttitudeCorrections 17 | #from IPython.Debugger import Tracer; debug_here = Tracer() 18 | 19 | def arcmin2rad(ang): 20 | return np.radians(ang/60.) 21 | 22 | def deaberration(vec, obt, coord): 23 | satvel = SatelliteVelocity(coord).orbital_v(obt) 24 | return np.cross(vec, np.cross(vec, satvel/physcon.c)) 25 | 26 | def simple_deaberration(vec, obt, coord): 27 | l.critical('Applying SIMPLE deaberration correction') 28 | satvel = SatelliteVelocity(coord, interp='linear').orbital_v(obt) 29 | return -1 * satvel/physcon.c 30 | 31 | def get_wobble_psi2_maris(obt): 32 | TAC=TabulatedAttitudeCorrections(private.WOBBLE['sun_file'],private.WOBBLE['planck_file']) 33 | return np.radians( 34 | TAC.TabulatePsi2(obt*2**16) /60. 35 | ) 36 | 37 | def get_wobble_psi2(obt, filename=None): 38 | """Reads psi2 wobble angle from file generated by Michele's standalone code""" 39 | if filename is None: 40 | filename = private.WOBBLE['psi2_file'] 41 | 42 | w = np.loadtxt(filename, delimiter=',', skiprows=1) 43 | 44 | return np.radians( 45 | np.interp(obt, w[:,1]/2**16, w[:,2])/60. 46 | ) 47 | 48 | def wobble(obt, wobble_psi2_model=get_wobble_psi2_maris, offset=0): 49 | """Gets array of OBT and returns an array of quaternions""" 50 | 51 | R_psi1 = qarray.inv(qarray.rotation([0,0,1], private.WOBBLE_DX7['psi1_ref'])) 52 | R_psi2 = qarray.inv(qarray.rotation([0,1,0], private.WOBBLE_DX7['psi2_ref'])) 53 | 54 | psi2 = wobble_psi2_model(obt) - offset 55 | R_psi2T = qarray.rotation([0,1,0], psi2) 56 | 57 | wobble_rotation = qarray.mult(qarray.inv(R_psi1), 58 | qarray.mult(R_psi2T , 59 | qarray.mult(R_psi2 , R_psi1) 60 | ) 61 | ) 62 | 63 | #debug_here() 64 | return wobble_rotation 65 | 66 | def ahf_wobble(obt): 67 | """Pointing period by pointing period correction for psi1 and psi2 from 68 | the AHF observation files""" 69 | 70 | R_psi1 = qarray.inv(qarray.rotation([0,0,1], private.WOBBLE['psi1_ref'])) 71 | R_psi2 = qarray.inv(qarray.rotation([0,1,0], private.WOBBLE['psi2_ref'])) 72 | 73 | psi1, psi2 = get_ahf_wobble(obt) 74 | 75 | R_psi2T = qarray.rotation([0,1,0], psi2) 76 | R_psi1T = qarray.rotation([0,0,1], psi1) 77 | 78 | wobble_rotation = qarray.mult(R_psi1T, 79 | qarray.mult(R_psi2T , 80 | qarray.mult(R_psi2 , R_psi1) 81 | ) 82 | ) 83 | 84 | return wobble_rotation 85 | 86 | 87 | def get_ahf_wobble(obtx): 88 | """Read psi1 and psi2 file previously extracted from observation AHF files""" 89 | filename = sorted(glob.glob(private.cal_folder + '/WDX9/*.fits'))[-1] 90 | l.info(filename) 91 | with pycfitsio.open(filename) as fitsfile: 92 | obt = fitsfile['OBT'].read_column(0)/2.**16 + 20 #shift forward of 20 seconds, so that the abrupt change in wobble angle is within the manouvre and does not impact the pointing between the last AHF quaternion and the manouvre 93 | psi1 = arcmin2rad(fitsfile['PSI_1'].read_column(0)) 94 | psi2 = arcmin2rad(fitsfile['PSI_2'].read_column(0)) 95 | # reproduce dpc dx9 96 | #psi1[1:] = psi1[0:-1] 97 | #psi2[1:] = psi2[0:-1] 98 | i_interp = np.interp(obtx, obt, np.arange(len(obt))) 99 | i_rounded = np.floor(i_interp).astype(np.int) 100 | return psi1[i_rounded], psi2[i_rounded] 101 | #return np.interp(obtx, obt, psi1), np.interp(obtx, obt, psi2) 102 | 103 | def read_ptcor(obt, ptcorfile): 104 | data = np.loadtxt(ptcorfile, delimiter=',') 105 | l.debug('Reading ' + ptcorfile) 106 | #i = data[:, 0].searchsorted(np.median(obt)) 107 | #return data[i-1, 1], data[i-1, 2] 108 | return np.interp(obt, data[:,0], data[:,1]), np.interp(obt, data[:,0], data[:,2]) 109 | 110 | def ptcor(obt, ptcorfile): 111 | # Boresight rotation of 85 degrees in order to get in inscan-xscan reference frame 112 | q_str_LOS = qarray.rotation(np.array([0,1,0]), np.radians(90-85)) 113 | 114 | # read variable correction for current OD from file 115 | delta_inscan, delta_xscan = read_ptcor(obt, ptcorfile) 116 | 117 | # rotation in inscan-xscan reference frame 118 | qcor = qarray.mult( 119 | qarray.rotation(np.array([0,1,0]), delta_xscan), 120 | qarray.rotation(np.array([1,0,0]), delta_inscan) 121 | ) 122 | 123 | qcor_tot = qarray.mult(q_str_LOS, qarray.mult(qcor, qarray.inv(q_str_LOS))) 124 | return qcor_tot 125 | -------------------------------------------------------------------------------- /planck/create_siam.py: -------------------------------------------------------------------------------- 1 | import pointingtools 2 | from planck import Planck 3 | pl=Planck.Planck() 4 | s=pointingtools.SiamAngles(False) 5 | lfi=pl.inst['LFI'] 6 | lines=[] 7 | lines.append('2011-05-23 TestEnv JupE 1.0\n') 8 | for ch in lfi.ch: 9 | lines.append(ch.tag + '\n') 10 | ss=s.get(ch).T 11 | for row in ss: 12 | lines.append('%.16e %.16e %.16e\n' % tuple(row)) 13 | a = open('siam_instrument_jupE1.0.txt', 'w') 14 | a.writelines(lines) 15 | a.close() 16 | -------------------------------------------------------------------------------- /planck/cut_planet.pro: -------------------------------------------------------------------------------- 1 | result = command_line_args(count=count) 2 | lat = float(result[0]) 3 | lon = float(result[1]) 4 | radius = float(result[2]) 5 | nside = float(result[3]) 6 | 7 | ;glon_glat = [lon 33.75, lat -40.33] ; Jupiter 8 | ;radius = 1.5d ; deg 9 | ;nside = 512 10 | 11 | ang2vec, lat , lon ,vector,/astro 12 | 13 | query_disc,nside,vector,radius,listpix,/nested,/deg,/inclusive 14 | 15 | print, listpix 16 | 17 | exit, status = 0 18 | -------------------------------------------------------------------------------- /planck/fixperm.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python -m compileall . 3 | chgrp -R cmb * 4 | chmod -R g+wrX,o+rX * 5 | -------------------------------------------------------------------------------- /planck/focalplane.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from pointingtools import * 4 | import re 5 | s=Siam(False) 6 | plt.figure() 7 | pair = {'a':'b','M':'S'} 8 | from planck import Planck 9 | lfi = Planck.Planck() 10 | for ch in lfi.ch: 11 | tag = ch.tag 12 | m = s.get(ch) 13 | 14 | print(tag) 15 | label = tag 16 | 17 | vec=np.dot(m,[1,0,0]) 18 | y=np.dot(m,[0,1,0])*.002 19 | 20 | if y[0] < 0: 21 | y *= -1 22 | 23 | if re.match('.*[abMS].*',tag) is None: 24 | plt.plot(vec[0],vec[1],'bs') 25 | else: 26 | col = 'k' 27 | if re.match('.*[bS].*',tag): 28 | col = 'r' 29 | label = None 30 | else: 31 | label += '+' + pair[tag[-1]] 32 | plt.plot(np.array([0,y[0]])+vec[0],np.array([0,y[1]]+vec[1]),col) 33 | 34 | if label: 35 | plt.text(vec[0]-.002, vec[1]-.005, label, fontsize=6) 36 | plt.grid() 37 | plt.ylim([-.09,.09]) 38 | plt.show() 39 | -------------------------------------------------------------------------------- /planck/hfi.py: -------------------------------------------------------------------------------- 1 | # Generic python class for dealing with Planck HFI 2 | # by zonca@deepspace.ucsb.edu 3 | 4 | import numpy as np 5 | from .base import Channel, Instrument 6 | from . import private 7 | 8 | class HFIChannel(Channel): 9 | 10 | MS = { 0 : 'a', 1 : 'b' } 11 | fromMS = { 'a' : 0, 'b' : 1} 12 | 13 | @property 14 | def centralfreq(self): 15 | return self.f.freq 16 | 17 | @property 18 | def calibdiff(self): 19 | return self.diff / self.inst.cal['cal'][self.inst.cal['ch']==self.tag] 20 | 21 | @property 22 | def horn(self): 23 | return int(self.tag.replace('a','').replace('b','').replace('-','')) 24 | 25 | def Planck_to_RJ(self, data): 26 | return data / private.mKRJ_2_mKcmb[self.f.freq] 27 | 28 | @property 29 | def eff_tag(self): 30 | return self.tag.replace('-','_') 31 | 32 | class HFI(Instrument): 33 | 34 | uncal = 'R' 35 | white_noise_field = "NET_WHT" 36 | 37 | Channel = HFIChannel 38 | 39 | def __init__(self, name = 'HFI', rimo = private.rimo['HFI'], instrument_db = private.instrument_db): 40 | super(HFI, self).__init__(name,rimo) 41 | self.instrument_db_file = rimo 42 | 43 | def load_cal(self): 44 | if not private.HFI_calibfile is None: 45 | self.cal = np.loadtxt(private.HFI_calibfile,dtype=[('ch','S8'),('cal',np.double)]) 46 | 47 | @staticmethod 48 | def freq_from_tag(tag): 49 | return int(tag[:3]) 50 | -------------------------------------------------------------------------------- /planck/hitmap.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import healpy 3 | import cPickle 4 | import logging as l 5 | import numpy as np 6 | from LFI import LFI 7 | from pointing import Pointing, DiskPointing 8 | from testenv.remix import read_exchange 9 | import glob 10 | 11 | def testBit(int_type, offset): 12 | """returns a nonzero result, 2**offset, if the bit at 'offset' is one.""" 13 | mask = 1 << offset 14 | return(int_type & mask) 15 | 16 | def concat_hitmaps(folder = 'pkl/'): 17 | files = glob.iglob(folder + '*pkl') 18 | for f in files: 19 | print(f) 20 | odhitmap = cPickle.load(open(f,'rb')) 21 | try: 22 | hitmap += odhitmap 23 | except: 24 | hitmap = odhitmap 25 | return hitmap 26 | 27 | 28 | class HitMap(object): 29 | 30 | def __init__(self, freq, od, nside=1024, use_flag=True,folder=None): 31 | LOG_FILENAME = '/project/projectdirs/planck/user/zonca/issues/hitmap/full.log' 32 | l.basicConfig(filename=LOG_FILENAME,level=l.DEBUG) 33 | self.freq = freq 34 | self.od = od 35 | self.use_flag = use_flag 36 | self.lfi = LFI() 37 | self.f = self.lfi.f[self.freq] 38 | self.nside = nside 39 | #self.ecl2gal = healpy.Rotator(coord=['E','G']) 40 | self.folder = folder 41 | l.info('%s ready' % self) 42 | 43 | def __repr__(self): 44 | return 'HitMap %d GHz, od %d' % (self.freq, self.od) 45 | 46 | def run(self): 47 | print('Reading data') 48 | read_exchange(self.f.ch, ods = [self.od], discard_flag = False,type='C') 49 | obt_good = testBit(self.f.commonflag,0)==0 50 | print('Preparing pointing') 51 | self.pnt = DiskPointing(self.od, self.freq, folder=self.folder) 52 | self.hitmap = np.zeros(healpy.nside2npix(self.nside)) 53 | for ch in self.f.ch: 54 | print('Processing rad %s' % ch) 55 | #theta, phi = self.ecl2gal(*self.pnt.get_ang(ch)) 56 | theta, phi = self.pnt.get_ang(ch) 57 | ch_good = obt_good & (ch.flagx == 0) & (ch.pair.flagx == 0) 58 | print('Flagged %.2f perc' % (100*(len(ch_good)-ch_good.sum())/len(ch_good))) 59 | if len(theta[ch_good]) > 0: 60 | ids = np.bincount(healpy.ang2pix(self.nside, theta[ch_good], phi[ch_good], nest=True)) 61 | self.hitmap[:len(ids)] += ids 62 | else: 63 | print('Skip channel') 64 | print('Writing to file') 65 | cPickle.dump(self.hitmap, open('/project/projectdirs/planck/user/zonca/issues/hitmap/pkl/%d_%d.pkl' % (self.freq,self.od),'wb'),protocol=-1) 66 | 67 | def pix2map(pix, nside, tod=None): 68 | """Pixel array to hitmap, if TOD with same lenght of PIX is provided, 69 | it is binned to a map""" 70 | #TODO test case 71 | pix = pix.astype(np.int) 72 | ids = np.bincount(pix, weights=None) 73 | npix = healpy.nside2npix(nside) 74 | hitmap = np.ones(npix) * healpy.UNSEEN 75 | hitmap[:len(ids[:npix])] = ids[:npix] 76 | hitmap = healpy.ma(hitmap) 77 | if tod is None: 78 | return hitmap 79 | else: 80 | ids_binned = np.bincount(pix, weights=tod) 81 | binned = np.ones(npix) * healpy.UNSEEN 82 | binned[:len(ids_binned[:npix])] = ids_binned[:npix] 83 | binned = healpy.ma(binned)/hitmap 84 | return hitmap, binned 85 | 86 | 87 | -------------------------------------------------------------------------------- /planck/lfi.py: -------------------------------------------------------------------------------- 1 | # Generic python class for dealing with Planck LFI 2 | 3 | from .base import Channel, ChannelBase, FrequencySet, Instrument 4 | from . import private 5 | 6 | class LFI_response: 7 | """ Class to store response curve in similar format to 8 | LFI_response data object 9 | """ 10 | def __init__(self,keys,sky_Vi,sky_Vo,ref_Vi,ref_Vo): 11 | self.keys = keys # Dictionary of keys and values 12 | self.sky_volt_in = sky_Vi 13 | self.sky_volt_out = sky_Vo 14 | self.load_volt_in = ref_Vi 15 | self.load_volt_out = ref_Vo 16 | 17 | def flatten_d(chlist): 18 | return [d for ch in chlist for d in ch.d] 19 | 20 | class LFIChannel(Channel): 21 | 22 | MS = { 0 : 'M', 1 : 'S' } 23 | fromMS = { 'M' : 0, 'S' : 1} 24 | 25 | def __init__(self, data, inst=None): 26 | super(LFIChannel, self).__init__(data, inst) 27 | self.d = [Detector(self, 0), Detector(self, 1)] 28 | 29 | @property 30 | def RCA(self): 31 | return LFI.RCA_from_tag(self.tag) 32 | 33 | @property 34 | def horn(self): 35 | return self.RCA 36 | 37 | @property 38 | def centralfreq(self): 39 | return self.get_instrument_db_field('nu_cen') 40 | 41 | @property 42 | def wn(self): 43 | return self.get_instrument_db_field('net_KCMB') 44 | 45 | def __getitem__(self, n): 46 | return self.d[n] 47 | 48 | def Planck_to_RJ(self, data): 49 | import dipole 50 | return dipole.Planck_to_RJ(data, self.centralfreq) 51 | 52 | @property 53 | def eff_tag(self): 54 | return self.tag 55 | 56 | @property 57 | def white_noise_sigma(self): 58 | return self.get_instrument_db_field("NET")**2 * self.get_instrument_db_field("F_SAMP") 59 | 60 | class LFIFrequencySet(FrequencySet): 61 | 62 | @property 63 | def d(self): 64 | return flatten_d(self.ch) 65 | class LFI(Instrument): 66 | 67 | uncal = 'C' 68 | white_noise_field = "NET" 69 | 70 | Channel = LFIChannel 71 | FrequencySet = LFIFrequencySet 72 | 73 | def __init__(self, name = 'LFI', rimo = private.rimo['LFI'], instrument_db = private.instrument_db): 74 | super(LFI, self).__init__(name,rimo) 75 | self.instrument_db_file = instrument_db 76 | 77 | @classmethod 78 | def freq_from_tag(cls, tag): 79 | RCA = cls.RCA_from_tag(tag) 80 | if RCA <= 23: 81 | return 70 82 | elif RCA <= 26: 83 | return 44 84 | elif RCA <= 28: 85 | return 30 86 | else: 87 | return None 88 | 89 | @staticmethod 90 | def RCA_from_tag(tag): 91 | return int(tag[3:5]) 92 | 93 | @property 94 | def d(self): 95 | return flatten_d(self.ch) 96 | 97 | class Detector(ChannelBase): 98 | def __init__(self, ch, n): 99 | self.n = n 100 | self.ch = ch 101 | self.tag = '%s-%s%s' % (ch.tag, self.ch.n, self.n) 102 | 103 | def savfilename(self, od): 104 | return private.savfilename % (od, self.ch.RCA, self.ch.n, self.n) 105 | 106 | @property 107 | def cdstag(self): 108 | return 'RCA%s%s%s' % (self.ch.RCA,self.ch.n, self.n) 109 | 110 | #def get_adc_response(self): 111 | # """Returns sky and ref splines of response""" 112 | # import scipy.interpolate.fitpack as fit 113 | # sys.modules['__main__'].LFI_response = LFI_response 114 | # try: 115 | # resp = cPickle.load(open(os.path.join(private.ADC['folder'], "%s_LFI_response.pic" % self.cdstag.lower()))) 116 | # except exceptions.IOError: 117 | # l.warning('NO ADC response for %s' % self.tag) 118 | # return fit.splrep(resp.sky_volt_out,resp.sky_volt_in,s=0.0), fit.splrep(resp.load_volt_out,resp.load_volt_in,s=0.0) 119 | -------------------------------------------------------------------------------- /planck/maptools.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import healpy as hp 3 | 4 | def degrade_mask(m, nside): 5 | return np.ceil(hp.ud_grade(m.astype(np.float), nside)).astype(np.bool) 6 | -------------------------------------------------------------------------------- /planck/metadata.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from glob import glob 3 | import os 4 | import sqlite3 5 | import logging as l 6 | from astropy.io import fits as pyfits 7 | from collections import namedtuple 8 | import sys 9 | 10 | from . import parse_channels 11 | from .base import freq2inst 12 | 13 | try: 14 | from . import private 15 | except ImportError: 16 | print('private.py is needed to use the planck module, this is available only to members of the Planck collaboration') 17 | raise 18 | 19 | Period = namedtuple('Period', ['number','start','stop','splitnumber']) 20 | Observation = namedtuple('Observation', ['od','tag','start','stop','PP','EFF', 'break_startrow', 'break_stoprow']) 21 | 22 | def get_g0(ch, reference_cal="DX10"): 23 | if ch.inst.name == "HFI": 24 | hfi_gains = { 25 | "100-1a" : 10010720032650.1, 26 | "100-1b" : 8164078549011.37 27 | } 28 | g0 = hfi_gains[ch.tag] 29 | else: 30 | filename = sorted(glob(private.cal_folder + "/%s/C%03d-*.fits" % (reference_cal, ch.f.freq)))[-1] 31 | finalsurv = 5 if reference_cal.startswith("DDX9") else 8 32 | with pyfits.open(filename) as calfile: 33 | 34 | g0 = np.mean(calfile[str(ch.tag)].data.field(0)[ 35 | (calfile["PID"].data["PID"] > private.survey[1].PID_LFI[0]) & 36 | (calfile["PID"].data["PID"] < private.survey[finalsurv].PID_LFI[1]) 37 | ]) 38 | return g0 39 | 40 | def obt2od(obt, freq=30): 41 | """Get precise OD from obt stamp2""" 42 | conn = sqlite3.connect(private.database) 43 | c = conn.cursor() 44 | query = c.execute('select startOBT, endOBT, od from efdd_od_ranges where startOBT<%d and endOBT>%d' % (obt,obt)) 45 | q = query.fetchone() 46 | od = int(q[2]) + float((obt-q[0]))/(q[1]-q[0]) 47 | c.close() 48 | return od 49 | 50 | def pid2od(pid, db): 51 | """Find the operational day a given LFI pointing ID is""" 52 | conn = sqlite3.connect(db) 53 | c = conn.cursor() 54 | query = c.execute( 55 | 'select od from list_ahf_infos where pointID_unique glob "{}-*" or pointID_unique like "{}"'.format(pid, pid) ) 56 | first_od = query.fetchone() 57 | if first_od == None: 58 | raise Exception('ERROR: could not find any OD in {} with the LFI PID {}'. format(db, pid)) 59 | od = first_od[0] 60 | return od 61 | 62 | def obt2utc(obt): 63 | import scipy.interpolate 64 | utcvec, obtvec = np.genfromtxt( '/project/projectdirs/planck/data/mission/SIAM/utc2obt_dx11.txt' ).T 65 | # utc2obt = scipy.interpolate.interp1d(utcvec, obtvec) 66 | obt2utc = scipy.interpolate.interp1d(obtvec, utcvec) 67 | return obt2utc(obt) 68 | 69 | class DataSelector(object): 70 | """Planck data selector 71 | channels can be integer frequency, list of channel names (same frequency) or a single channel name string 72 | efftype is R for reduced, C for converted [uncal with dip] 73 | ods are the AHF ODs 74 | eff_ods are the EFF ODs 75 | 76 | some configuration options can be modified after creating the object by accessing the .config dictionary""" 77 | 78 | def __init__(self, channels=None, efftype='R', include_preFLS=False): 79 | self.include_preFLS = include_preFLS 80 | self.channels = parse_channels(channels) 81 | 82 | if self.channels is None: 83 | self.f = None 84 | else: 85 | self.f = self.channels[0].f 86 | self.config = {} 87 | self.config['database'] = private.database 88 | self.config['breaks'] = private.TOAST['breaks'] 89 | if self.channels is None: 90 | self.config['exchangefolder'] = None 91 | else: 92 | self.config['exchangefolder'] = private.exchangefolder[self.f.inst.name] 93 | 94 | self.config['ahf_folder'] = private.AHF 95 | self.config['exclude_454_455'] = True 96 | self.efftype = efftype 97 | self.ring_range = None 98 | 99 | @property 100 | def ods(self): 101 | try: 102 | return self._ods 103 | except AttributeError: 104 | self._ods = set() 105 | for obt_range in self.obt_ranges: 106 | self._ods.update(self.get_ODs(obt_range)) 107 | self._ods = sorted(list(self._ods)) 108 | return self.ods 109 | 110 | @property 111 | def obt_ranges(self): 112 | try: 113 | return self._obt_ranges 114 | except AttributeError: 115 | self._obt_ranges = [get_obt_range_from_od(od, self.config['database']) for od in self.ods] 116 | return self._obt_ranges 117 | 118 | def by_od_range(self, od_range): 119 | """ods is a list of start and stop OD (INCLUSIVE)""" 120 | self.od_range = od_range 121 | self._ods = range(od_range[0], od_range[1]+1) 122 | if self.config['exclude_454_455'] and self.f.inst.name == 'LFI': 123 | for OD in [454, 455]: 124 | try: 125 | self._ods.remove(OD) 126 | except: 127 | pass 128 | 129 | def by_obt(self, obt_ranges): 130 | """obt_ranges is a list of 2 element lists (or tuple) with start-stop obt""" 131 | raise NotImplementedError() 132 | self._obt_ranges = obt_ranges 133 | 134 | def by_lfi_rings(self, rings): 135 | """rings is an inclusive list of lfi ring numbers""" 136 | odstart = pid2od(rings[0], self.config['database']) 137 | odstop = pid2od(rings[1], self.config['database']) 138 | self.by_od_range([odstart, odstop]) 139 | self.ring_range = rings 140 | 141 | def by_hfi_rings(self, rings): 142 | """rings is an inclusive list of hfi ring numbers""" 143 | lfirings = [rings[0]-237, rings[1]-237] 144 | self.by_lfi_rings(lfirings) 145 | 146 | def get_AHF_ods(self, obt_range): 147 | conn = sqlite3.connect(self.config['database']) 148 | c = conn.cursor() 149 | values = ((obt_range[0]-1)*2**16, (obt_range[-1]+1)*2**16) 150 | query = c.execute('select od from ahf_files where endOBT>=? and startOBT<=?', values) 151 | ods = [int(q[0]) for q in query] 152 | c.close() 153 | assert len(ods) > 0, "Cannot find ODs for obt range " + str(obt_range) 154 | return ods 155 | 156 | def get_one_AHF(self, obt_range): 157 | ods = self.get_AHF_ods(obt_range) 158 | files = [glob( 159 | os.path.join(self.config['ahf_folder'], '%04d' % od, 'vel*') 160 | )[0] for od in ods] 161 | assert len(files) > 0, "Cannot find AHF for obt range " + str(obt_range) 162 | return files 163 | 164 | def get_AHF(self): 165 | return [self.get_one_AHF(obt_range) for obt_range in self.obt_ranges] 166 | 167 | def get_EFF(self): 168 | return self.latest_exchange(self.eff_ods) 169 | 170 | def get_OD_OBS(self): 171 | """Gets one observation for each Operational Day""" 172 | OBS = [] 173 | for od, obt_range in zip(self.ods, self.obt_ranges): 174 | eff_ods = eff_ods_from_obt_range(self.f.freq, obt_range) 175 | if self.config['exclude_454_455'] and self.f.inst.name == 'LFI': 176 | for OD in [454, 455]: 177 | try: 178 | eff_ods.remove(OD) 179 | except: 180 | pass 181 | OBS.append(Observation(od=od, tag='', start=obt_range[0], stop=obt_range[1], PP=self.get_PP(od), EFF=self.latest_exchange(eff_ods), break_startrow=None, break_stoprow=None)) 182 | return OBS 183 | 184 | def get_OBS(self): 185 | """Checks the breaks table and splits the observations accordingly""" 186 | OBS = self.get_OD_OBS() 187 | 188 | conn = sqlite3.connect(self.config['breaks']) 189 | c = conn.cursor() 190 | #obt are in clocks in the database 191 | query = c.execute('select od, startobt, stopobt, startrow, stoprow from eff_breaks where freq=? and startobt > ? and stopobt < ?', (self.f.freq,OBS[0].start*2**16, OBS[-1].stop*2**16)) 192 | for od, startobt, stopobt, startrow, stoprow in query: 193 | #convert in seconds 194 | startobt /= 2.**16 195 | stopobt /= 2.**16 196 | l.warning('Break found in OD %d' % od) 197 | try: 198 | OB = [o for o in OBS if o.start < stopobt and o.stop > startobt][0] 199 | except IndexError: 200 | l.error('Cannot identify the observation related to the break in OD %d' % od) 201 | sys.exit(1) 202 | i = OBS.index(OB) 203 | splitted_OBS = split_observation(OB, startobt, stopobt, startrow, stoprow) 204 | OBS[i] = splitted_OBS[1] 205 | OBS.insert(i, splitted_OBS[0]) 206 | c.close() 207 | return OBS 208 | 209 | def get_PP(self, od): 210 | """Gets all the pointing periods in one Operational Day, returns a list of Period named tuples""" 211 | conn = sqlite3.connect(self.config['database']) 212 | c = conn.cursor() 213 | if self.include_preFLS: 214 | query = c.execute('select pointID_unique, start_time, end_time from list_ahf_infos where od==? AND start_time < end_time order by start_time ASC', (str(od),)) 215 | else: 216 | query = c.execute('select pointID_unique, start_time, end_time from list_ahf_infos where od==? and start_time > 106743579730069 AND start_time < end_time order by start_time ASC', (str(od),)) 217 | 218 | PP = [] 219 | for q in query: 220 | pid_numbers= list(map(int, q[0].split('-'))) 221 | if self.ring_range != None: 222 | # Check if the Pointing ID is within a specified ring range 223 | if pid_numbers[0] < self.ring_range[0]: continue 224 | if pid_numbers[0] > self.ring_range[1]: continue 225 | if len(pid_numbers) == 1: 226 | pid_numbers.append(0) 227 | PP.append( Period(pid_numbers[0],q[1]/2.**16,q[2]/2.**16, pid_numbers[1]) ) 228 | c.close() 229 | return PP 230 | 231 | #def get_obt_range_from_ods(self, freq=None, ods=None): 232 | # if ods is None: 233 | # ods = self.ods 234 | # if freq is None: 235 | # freq = self.f.freq 236 | # conn = sqlite3.connect(self.config['database']) 237 | # c = conn.cursor() 238 | # query = c.execute('select startOBT, endOBT from efdd_od_ranges where freq=? and od in ? order by od ASC', (freq, ods)) 239 | # c.close() 240 | # obt_ranges = [[q[0]/2.**16, q[1]/2.**16] for q in query] 241 | # return obt_ranges 242 | 243 | #def get_obt_range_from_od_range(self, freq=None, od_range=None): 244 | # if od_range is None: 245 | # od_range = self.od_range 246 | # if freq is None: 247 | # freq = self.f.freq 248 | # conn = sqlite3.connect(self.config['database']) 249 | # c = conn.cursor() 250 | # obt_range = [] 251 | # #start of first pp 252 | # query = c.execute('select start_time from list_ahf_infos where od==? order by pointID_unique ASC limit 1', od_range[0]) 253 | # obt_range.append(query.fetchone()[0]/2.**16) 254 | # #end of last pp 255 | # query = c.execute('select end_time from list_ahf_infos where od==? order by pointID_unique DESC limit 1', od_range[1]) 256 | # obt_range.append(query.fetchone()[0]/2.**16) 257 | # c.close() 258 | # return obt_range 259 | 260 | 261 | @property 262 | def eff_ods(self): 263 | """List of ODs within the obt range provided""" 264 | eff_ods = eff_ods_from_obt_range(self.f.freq, [self.obt_ranges[0][0], self.obt_ranges[-1][-1]]) 265 | if self.config['exclude_454_455'] and self.f.inst.name == 'LFI': 266 | for OD in [454, 455]: 267 | try: 268 | eff_ods.remove(OD) 269 | except: 270 | pass 271 | return eff_ods 272 | 273 | def latest_exchange(self, od): 274 | return latest_exchange(self.f.freq, od, self.config['exchangefolder'], self.efftype) 275 | 276 | def eff_ods_from_obt_range(freq, obt_range, database=None): 277 | conn = sqlite3.connect(database or private.database) 278 | c = conn.cursor() 279 | query = c.execute('select od from efdd_od_ranges where freq=? and endOBT>=? and startOBT<=?',(freq, obt_range[0]*2**16, obt_range[1]*2**16) ) 280 | eff_ods = [q[0] for q in query] 281 | c.close() 282 | return eff_ods 283 | 284 | def get_obt_range_from_od(od, database=None): 285 | conn = sqlite3.connect(database or private.database) 286 | c = conn.cursor() 287 | query = c.execute('select start_time,end_time from list_ahf_infos where od==? order by start_time ASC', (str(od),)) 288 | all = query.fetchall() 289 | obt_range = (all[0][0]/2.**16, all[-1][-1]/2.**16) 290 | c.close() 291 | return obt_range 292 | 293 | def latest_exchange(freq, ods, exchangefolder = None, type = 'R'): 294 | """Returns the latest version of an exchange format file""" 295 | single = False 296 | if exchangefolder is None: 297 | exchangefolder = private.exchangefolder[freq2inst(freq)] 298 | 299 | if isinstance(ods, int): 300 | ods = [ods] 301 | single = True 302 | #if glob(exchangefolder + '/*.fits'): 303 | # ods = [0] 304 | if type == 'K': 305 | type = '' 306 | EFF = [] 307 | for od in ods: 308 | pattern = '*%03d?%04d?%s*.fits' % (freq, od, type) 309 | if od: 310 | pattern = os.path.join('%04d' % od, pattern) 311 | l.debug('Exchange format: %s' % (os.path.join(exchangefolder, pattern))) 312 | allversions = glob(os.path.join(exchangefolder, pattern)) 313 | if len(allversions) == 1: 314 | EFF.append(allversions[0]) 315 | else: 316 | if not allversions: 317 | error_message = 'Cannot find file from pattern: %s' % os.path.join(exchangefolder, pattern) 318 | l.error(error_message) 319 | raise IOError(error_message) 320 | EFF.append(max(allversions, key = lambda x: int(x[-13:-5]))) 321 | if single: 322 | EFF = EFF[0] 323 | return EFF 324 | 325 | def split_observation(OB, startobt, stopobt, startrow, stoprow): 326 | """Splits one observation in 2 observations""" 327 | PP1 = [p for p in OB.PP if p.start < startobt] 328 | PP1[-1] = Period(PP1[-1].number, PP1[-1].start, startobt, PP1[-1].splitnumber) 329 | OB1 = Observation(od=OB.od, tag=OB.tag + 'a', start=OB.start, stop=startobt, PP=PP1, EFF=OB.EFF, break_startrow=startrow, break_stoprow=None) 330 | 331 | PP2 = [p for p in OB.PP if p.stop > stopobt] 332 | PP2[0] = Period(PP2[0].number, stopobt, PP2[0].stop, PP2[0].splitnumber) 333 | OB2 = Observation(od=OB.od, tag=OB.tag + 'b', start=stopobt, stop=OB.stop, PP=PP2, EFF=OB.EFF, break_startrow=None, break_stoprow=stoprow) 334 | 335 | return OB1, OB2 336 | 337 | 338 | if __name__ == '__main__': 339 | ds = DataSelector(channels=30) 340 | ds.config['exchangefolder'] = '/global/scratch/sd/planck/user/zonca/data/LFI_DX7S_conv/' 341 | ds.by_od_range([452, 457]) 342 | print(ds.get_EFF()) 343 | print(ds.get_AHF()) 344 | print(ds.get_OBS()) 345 | obs=ds.get_OBS() 346 | -------------------------------------------------------------------------------- /planck/pix2od.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import datetime 3 | import sys 4 | import numpy as np 5 | from optparse import OptionParser 6 | import sys 7 | import os.path 8 | import exceptions 9 | 10 | try: 11 | from bitstring import ConstBitArray 12 | except exceptions.ImportError: 13 | print('pix2od requires bitstring: easy_install bitstring') 14 | sys.exit(1) 15 | 16 | PIX2ODPATH = 'data' 17 | OBTSTARTDATE = datetime.datetime(1958,1,1,0,0,0) 18 | LAUNCH = datetime.datetime(2009, 5, 13, 13, 11, 57, 565826) 19 | SECONDSPERDAY = 3600 * 24 20 | 21 | def pix2od(ch, pixels): 22 | """ nside 512 NEST pixel number to OD [91-563 excluding 454-455] for Planck channels 23 | it returns a list of sets. 24 | Each set contains the ODs hit by each pixel 25 | """ 26 | filename = os.path.join(PIX2ODPATH, 'od_by_pixel_%s.bin' % ch.replace('M','S')) 27 | pixels_by_od = ConstBitArray(filename = filename) 28 | odrange = [91, 563+1] 29 | num_ods = odrange[1] - odrange[0] 30 | NSIDE = 512 31 | NPIX = 12 * NSIDE**2 32 | tot_ods = list() 33 | if np.any(np.array(pixels) >= NPIX): 34 | raise exceptions.ValueError('ERROR: input pixels must be NSIDE 512, RTFM!') 35 | for pix in pixels: 36 | ods = set(np.array(list(pixels_by_od[num_ods*pix:num_ods*pix+num_ods].findall([True]))) + odrange[0]) 37 | tot_ods.append(ods) 38 | return tot_ods 39 | 40 | 41 | if __name__ == '__main__': 42 | usage = '''nside 512 NEST pixel number to OD [91-563 excluding 454-455] for Planck channels 43 | pix2od -c LFI27M 1000 [1001 1002...] 44 | returns list of operational days 45 | pointing generated with TestEnv using HORN pointing (M has same pointing as S) 46 | Using Galactic coordinates: 47 | pix2od -c LFI28S -a -- Lat[+-90 deg] Long[+-180 deg] 48 | ''' 49 | parser = OptionParser (usage = usage) 50 | parser.add_option('-c','--channel', dest = 'ch', 51 | help = 'channel tag (def %default)', action = 'store', type = 'string', 52 | default = 'LFI28M') 53 | parser.add_option('-a','--angles', dest = 'angles', 54 | help = 'Use galactic latitude [+-90] and longitude [+-180] in degrees instead of pixel numbers (def %default)', action = 'store_true', 55 | default = False) 56 | 57 | (options, args) = parser.parse_args() 58 | 59 | if len(args) < 1: 60 | parser.print_help() 61 | sys.exit(1) 62 | NSIDE=512 63 | if options.angles: 64 | tot_ods = [] 65 | from healpy import ang2pix 66 | args = map(float, args) 67 | pixels = [] 68 | for latitude, longitude in zip(args[::2], args[1::2]): 69 | pixels.append(ang2pix(NSIDE, np.radians(90-latitude), np.radians(longitude),nest=True)) 70 | tot_ods = set.intersection(*utils.pix2od(options.ch, pixels)) 71 | else: 72 | pixels = map(int, args) 73 | tot_ods = set.union(*utils.pix2od(options.ch, pixels)) 74 | 75 | all_ods = np.unique(tot_ods) 76 | print(' '.join(map(str,list(all_ods)))) 77 | sys.exit(0) 78 | -------------------------------------------------------------------------------- /planck/pointing.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import logging as l 4 | import numpy as np 5 | #from IPython.Debugger import Tracer; debug_here = Tracer() 6 | import quaternionarray as qarray 7 | from . import Planck 8 | from . import parse_channel 9 | from . import private 10 | from astropy.io import fits as pyfits 11 | from .pointingtools import angles2siam, quaternion_ecl2gal, AHF_btw_OBT 12 | import pycfitsio 13 | from . import correction 14 | import glob 15 | import os 16 | try: 17 | from exceptions import IndexError 18 | except: 19 | pass 20 | 21 | def compute_pol_weigths(psi): 22 | spsi = np.sin(psi) 23 | cpsi = np.cos(psi) 24 | cf = 1./(cpsi**2 + spsi**2) 25 | return (cpsi**2 - spsi**2)*cf, 2*cpsi*spsi*cf 26 | 27 | class IDBSiam: 28 | def __init__(self, instrument_db, obt, Pxx=False): 29 | if instrument_db is None: 30 | instrument_db = private.instrument_db 31 | #if isinstance(instrument_db, list): 32 | # instrument_db = instrument_db[obt.mean() > 1667477889.4692688] # first stamp of OD 539 33 | l.warning("Using IDB: " + str(map(os.path.basename, instrument_db.values()))) 34 | self.uv_angles = {} 35 | for instrument_db_one in instrument_db.values(): 36 | idb_file = pyfits.open(instrument_db_one) 37 | for row in np.array(idb_file[1].data): 38 | try: 39 | radtag = row["Radiometer"].strip() 40 | except IndexError: 41 | radtag = row["DETECTOR"].strip() 42 | radtag = radtag.decode("ascii") 43 | self.uv_angles[radtag] = {} 44 | for fi in ["theta_uv","phi_uv","psi_uv","psi_pol"]: 45 | try: 46 | self.uv_angles[radtag][fi]=np.radians(row[fi]) 47 | except IndexError: 48 | self.uv_angles[radtag][fi]=np.radians(row[fi.upper()]) 49 | if Pxx: 50 | self.uv_angles[radtag]["psi_uv"]=0 51 | self.uv_angles[radtag]["psi_pol"]=0 52 | idb_file.close() 53 | 54 | def get(self, ch): 55 | return angles2siam(self.uv_angles[ch.tag]["theta_uv"], 56 | self.uv_angles[ch.tag]["phi_uv"], 57 | self.uv_angles[ch.tag]["psi_uv"] + 58 | self.uv_angles[ch.tag]["psi_pol"]) 59 | 60 | class Pointing(object): 61 | '''Pointing interpolation and rotation class 62 | 63 | usage: 64 | >>> ch= Planck()['100-1a'] 65 | >>> pnt = Pointing(obt, coord='G') #interpolates AHF to obt 66 | >>> vec = pnt.get(ch) #rotates to detector frame and gives x,y,z vector 67 | >>> pix = pnt.get_pix(ch, 2048, nest=True) #healpix pixel number nside 2048 68 | ''' 69 | comp = ['X','Y','Z','S'] 70 | 71 | def __init__(self,obt,coord='G', horn_pointing=False, deaberration=True, wobble=True, interp='slerp', siamfile=None, wobble_offset=0, ptcorfile=None, Pxx=False, instrument_db=None): 72 | ''' 73 | nointerp to use the AHF OBT stamps''' 74 | l.warning('Pointing setup, coord:%s, deab:%s, wobble:%s' % (coord, deaberration, wobble)) 75 | #get ahf limits 76 | self.Pxx = Pxx 77 | self.deaberration = deaberration 78 | self.wobble = wobble 79 | 80 | filenames = AHF_btw_OBT(obt) 81 | files = [pycfitsio.open(f) for f in filenames] 82 | l.debug('reading files %s' % str(files)) 83 | AHF_data_iter = [f[0] for f in files] 84 | 85 | l.debug('reading files') 86 | 87 | ahf_obt = np.concatenate([h.read_column('OBT_SPL') for h in AHF_data_iter]) 88 | ahf_obt /= 2.**16 89 | i_start = max(ahf_obt.searchsorted(obt[0])-1,0) 90 | i_end = min(ahf_obt.searchsorted(obt[-1])+1,len(ahf_obt)-1) 91 | ahf_obt = ahf_obt[i_start:i_end] 92 | 93 | ahf_quat = np.empty((len(ahf_obt),4)) 94 | for i,c in enumerate(self.comp): 95 | ahf_quat[:,i] = np.concatenate([h.read_column('QUATERNION_'+c) for h in AHF_data_iter])[i_start:i_end] 96 | 97 | #debug_here() 98 | if self.wobble: 99 | #ahf_quat = qarray.mult(ahf_quat, correction.wobble(ahf_obt,offset=wobble_offset)) 100 | # DX8 wobble angle correction 101 | wob = correction.ahf_wobble(ahf_obt) 102 | ahf_quat = qarray.mult(ahf_quat, wob) 103 | #print(wob[17320:17335]) 104 | #print(ahf_obt[17329]) 105 | #34690:34705 106 | qarray.norm_inplace(ahf_quat) 107 | 108 | if ptcorfile == True: 109 | ptcorfile = private.ptcorfile 110 | if ptcorfile: 111 | ahf_quat = qarray.mult(ahf_quat, correction.ptcor(ahf_obt, ptcorfile)) 112 | 113 | if coord == 'G': 114 | ahf_quat = quaternion_ecl2gal(ahf_quat) 115 | 116 | if interp is None: 117 | self.qsatgal_interp = ahf_quat 118 | # save AHF obt for later interpolation 119 | self.ahf_obt = ahf_obt 120 | else: 121 | l.info('Interpolating quaternions with %s' % interp) 122 | interpfunc = getattr(qarray, interp) 123 | self.qsatgal_interp = interpfunc(obt, ahf_obt, ahf_quat) 124 | 125 | #if self.wobble: 126 | # self.qsatgal_interp = qarray.mult(self.qsatgal_interp, correction.wobble(obt)) 127 | # qarray.norm_inplace(self.qsatgal_interp) 128 | 129 | l.info('Quaternions interpolated') 130 | self.siam = IDBSiam(instrument_db, obt, self.Pxx) 131 | 132 | self.obt = obt 133 | self.coord = coord 134 | 135 | l.debug('Closing AHF files') 136 | for f in files: 137 | f.close() 138 | 139 | def interp_get(self, rad): 140 | '''Interpolation after rotation to gal frame''' 141 | from Quaternion import Quat 142 | l.info('Rotating to detector %s' % rad) 143 | siam_quat = Quat(self.siam.get(rad)).q 144 | totquat = qarray.mult(self.qsatgal_interp, siam_quat) 145 | totquat_interp = qarray.nlerp(self.obt, self.ahfobt, totquat) 146 | x = np.array([1, 0, 0]) 147 | vec = qarray.rotate(totquat_interp, x) 148 | l.info('Rotated to detector %s' % rad) 149 | return vec 150 | 151 | def get(self, rad): 152 | rad = parse_channel(rad) 153 | l.info('Rotating to detector %s' % rad) 154 | x = np.dot(self.siam.get(rad),[1, 0, 0]) 155 | vec = qarray.rotate(self.qsatgal_interp, x) 156 | qarray.norm_inplace(vec) 157 | if self.deaberration: 158 | l.warning('Applying deaberration correction') 159 | vec += correction.simple_deaberration(vec, self.obt, self.coord) 160 | qarray.norm_inplace(vec) 161 | l.info('Rotated to detector %s' % rad) 162 | return vec 163 | 164 | def inv(self, rad, vec): 165 | rad = parse_channel(rad) 166 | l.info('Rotating to detector %s' % rad) 167 | if self.deaberration: 168 | l.warning('Applying deaberration correction') 169 | vec -= correction.simple_deaberration(vec, self.obt, self.coord) 170 | qarray.norm_inplace(vec) 171 | vec_rad = qarray.rotate(qarray.inv(self.qsatgal_interp), vec) 172 | invsiam = np.linalg.inv(self.siam.get(rad)) 173 | #invsiamquat = qarray.inv(qarray.norm(qarray.from_rotmat(self.siam.get(rad)))) 174 | #qarray.rotate(invsiamquat, vec_rad) 175 | return np.array([np.dot(invsiam , row) for row in vec_rad]) 176 | 177 | def compute_psi(self, theta, phi, rad): 178 | psi = self.compute_psi_dx8(theta, phi, rad) 179 | psi += np.pi 180 | psi[psi > np.pi] -= 2*np.pi 181 | if self.Pxx: 182 | psi -= np.pi/2 183 | psi[psi < - np.pi] += 2*np.pi 184 | return psi 185 | 186 | def compute_psi_dx8(self, theta, phi, rad): 187 | z = np.dot(self.siam.get(rad),[0, 0, 1]) 188 | vecz = qarray.norm(qarray.rotate(self.qsatgal_interp, z)) 189 | e_phi = np.hstack([-np.sin(phi)[:,np.newaxis], np.cos(phi)[:,np.newaxis], np.zeros([len(phi),1])]) 190 | e_theta = np.hstack([(np.cos(theta)*np.cos(phi))[:,np.newaxis], (np.cos(theta)*np.sin(phi))[:,np.newaxis], -np.sin(theta)[:,np.newaxis]]) 191 | psi = np.arctan2(-qarray.arraylist_dot(vecz, e_phi), -qarray.arraylist_dot(vecz, e_theta)) 192 | return psi.flatten() 193 | 194 | def get_vecpsi(self, rad): 195 | from healpy import vec2ang 196 | vec = self.get(rad) 197 | theta, phi = vec2ang(vec) 198 | psi = self.compute_psi(theta, phi, rad) 199 | return vec, psi 200 | 201 | def get_3ang(self, rad): 202 | l.info('Rotating to detector %s' % rad) 203 | theta, phi = self.get_ang(rad) 204 | psi = self.compute_psi(theta, phi, rad) 205 | l.info('Rotated to detector %s' % rad) 206 | return theta, phi, psi 207 | 208 | def get_pix_iqu(self, rad, nside=1024, nest=True): 209 | from healpy import vec2pix, vec2ang 210 | vec = self.get(rad) 211 | theta, phi = vec2ang(vec) 212 | psi = self.compute_psi(theta, phi, rad) 213 | #return vec2pix(nside, vec[:,0], vec[:,1], vec[:,2], nest), np.cos(2*psi), np.sin(2*psi) 214 | cos2psi, sin2psi = compute_pol_weigths(psi) 215 | return vec2pix(nside, vec[:,0], vec[:,1], vec[:,2], nest), cos2psi, sin2psi 216 | 217 | def get_pix(self, rad, nside=1024, nest=True): 218 | from healpy import vec2pix 219 | vec = self.get(rad) 220 | return vec2pix(nside, vec[:,0], vec[:,1], vec[:,2], nest) 221 | 222 | def get_ang(self, rad, degrees=False): 223 | from healpy import vec2ang 224 | vec = self.get(rad) 225 | ang = vec2ang(vec) 226 | if degrees: 227 | return map(np.rad2deg, ang) 228 | else: 229 | return ang 230 | 231 | class DiskPointing(Pointing): 232 | '''Read pointing from disk''' 233 | def __init__(self, od, freq, folder=None): 234 | self.folder = folder or private.pointingfolder 235 | self.filename = glob.glob(self.folder + '/%04d/?%03d-*.fits' % (od,freq))[0] 236 | 237 | def get_3ang(self, ch): 238 | l.debug('Reading %s' % self.filename) 239 | #with pycfitsio.open(self.filename) as f: 240 | # h = f[ch.tag] 241 | # return h.read_column('THETA'), h.read_column('PHI'), h.read_column('PSI') 242 | with pyfits.open(self.filename) as f: 243 | h = f[ch.tag] 244 | return h.data['THETA'], h.data['PHI'], h.data['PSI'] 245 | 246 | def get_ang(self, ch): 247 | l.debug('Reading %s' % self.filename) 248 | with pycfitsio.open(self.filename) as f: 249 | h = f[ch.tag] 250 | return h.read_column('THETA'), h.read_column('PHI') 251 | 252 | def get_pix(self, rad, nside=1024, nest=True): 253 | from healpy import ang2pix 254 | theta, phi = self.get_ang(rad) 255 | return ang2pix(nside, theta, phi, nest) 256 | 257 | def get_pix_psi(self, rad, nside=1024, nest=True): 258 | from healpy import ang2pix 259 | theta, phi, psi = self.get_3ang(rad) 260 | return ang2pix(nside, theta, phi, nest), psi 261 | 262 | def get(self, ch): 263 | import healpy 264 | theta, phi, psi = self.get_3ang(ch) 265 | return healpy.ang2vec(theta, phi) 266 | -------------------------------------------------------------------------------- /planck/pointingtools.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import math 4 | from astropy.io import fits as pyfits 5 | import logging as l 6 | import numpy as np 7 | #from IPython.Debugger import Tracer; debug_here = Tracer() 8 | import quaternionarray as qarray 9 | from .utils import grouper 10 | from . import private 11 | 12 | SPIN2BORESIGHT = np.radians(85.0) 13 | 14 | def angles2siam(theta, phi, psi): 15 | mat_spin2boresight=qarray.rotation([0,1,0], np.pi/2-SPIN2BORESIGHT) 16 | 17 | mat_theta_phi = qarray.rotation([-math.sin(phi),math.cos(phi),0], theta) 18 | mat_psi = qarray.rotation([0,0,1], psi) 19 | # detector points to X axis 20 | total = qarray.mult(mat_spin2boresight, qarray.mult(mat_theta_phi, mat_psi)) 21 | # siam is defined as pointing to Z axis 22 | return np.dot(qarray.to_rotmat(total[0]), np.array([[0,0,1],[0,1,0],[1,0,0]])) 23 | 24 | try: 25 | import pysqlite2.dbapi2 as sqlite3 26 | except: 27 | import sqlite3 28 | 29 | QECL2GAL_HYDRA = np.array((-0.37382079227204573, 0.33419217216073838, 0.64478939348298625, 0.57690575088960561)) 30 | QECL2GAL_HEALPIX = np.array([-0.37381693504678937, 0.33419069514234978, 0.64479285220138716, 0.57690524015582401]) 31 | QECL2GAL = QECL2GAL_HEALPIX 32 | 33 | class Siam(object): 34 | 35 | def __init__(self, horn_pointing=False, siamfile=None): 36 | self.horn_pointing = horn_pointing 37 | if siamfile is None: 38 | siamfile = private.siam 39 | f = open(siamfile) 40 | lines = f.readlines() 41 | self.siam = {} 42 | for line in grouper(4,lines[1:]): 43 | chtag = line[0].split()[0] 44 | m = np.array(np.matrix(';'.join(line[1:]))) 45 | self.siam[chtag] = m 46 | self.siamfile = siamfile 47 | def get(self, ch): 48 | if ch.inst.name == 'HFI': 49 | l.debug('using SIAM %s' % self.siamfile) 50 | return self.siam[ch.tag].T 51 | else: 52 | l.warning('For LFI using instrument DB angles') 53 | return SiamAngles(self.horn_pointing).get(ch) 54 | 55 | class SiamAngles(object): 56 | 57 | 58 | def __init__(self, horn_pointing): 59 | self.horn_pointing = horn_pointing 60 | 61 | def get_angles(self, ch): 62 | if self.horn_pointing and ch.arm == 'M': 63 | l.warning('USING HORN POINTING') 64 | S_ch = ch.inst[ch.tag.replace('M','S')] 65 | theta = np.radians(S_ch.get_instrument_db_field('theta_uv')) 66 | phi = np.radians(S_ch.get_instrument_db_field('phi_uv')) 67 | else: 68 | theta = np.radians(ch.get_instrument_db_field('theta_uv')) 69 | phi = np.radians(ch.get_instrument_db_field('phi_uv')) 70 | psi = np.radians(ch.get_instrument_db_field('psi_uv')+ch.get_instrument_db_field('psi_pol')) 71 | return theta, phi, psi 72 | 73 | def get(self, ch): 74 | return angles2siam(*self.get_angles(ch)) 75 | 76 | class SiamForcedAngles(SiamAngles): 77 | 78 | def __init__(self, theta, phi, psi): 79 | self.theta = theta 80 | self.phi = phi 81 | self.psi = psi 82 | 83 | def get_angles(self, ch): 84 | return self.theta, self.phi, self.psi 85 | 86 | def AHF_btw_OBT(obt): 87 | 88 | conn = sqlite3.connect(private.database) 89 | c = conn.cursor() 90 | values = ((obt[0]-60*5)*2**16, (obt[-1]+60*5)*2**16) 91 | query = c.execute('select file_path from ahf_files where endOBT>=? and startOBT<=?', values) 92 | files = [q[0] for q in query] 93 | c.close() 94 | return files 95 | 96 | def generate_repointing_flag(obt): 97 | flag = np.zeros_like(obt) 98 | files = [pyfits.open(file)[1].data for file in AHF_btw_OBT(obt)] 99 | 100 | files[-1] = files[-1][:(files[-1].field('OBT_SPL')/2.**16).searchsorted(obt[-1])+1] 101 | files[0] = files[0][(files[0].field('OBT_SPL')/2.**16).searchsorted(obt[0])-1:] 102 | AHF = np.concatenate(files) 103 | 104 | i_start_repointing, = np.nonzero(np.diff(AHF['OBT_BEG'])) 105 | start_repointing = AHF['OBT_SPL'][i_start_repointing+1]/2.**16 106 | end_repointing = AHF['OBT_BEG'][i_start_repointing+1]/2.**16 107 | for start, end in zip(start_repointing,end_repointing): 108 | flag[obt.searchsorted(start):obt.searchsorted(end)] = 1 109 | return flag 110 | 111 | def quaternion_ecl2gal(qsat): 112 | '''Convert array of quaternions from Ecliptic to Galactic''' 113 | l.info('Rotating to Galactic frame') 114 | qsatgal = qarray.mult(QECL2GAL ,qsat) 115 | # renormalizing to unity 116 | qarray.norm_inplace(qsatgal) 117 | return qsatgal 118 | 119 | def vector_ecl2gal(vecl): 120 | '''Convert arrays from Ecliptic to Galactic''' 121 | l.info('Rotating to Galactic frame') 122 | return qarray.rotate(QECL2GAL ,vecl) 123 | 124 | def vector_gal2ecl(vecl): 125 | '''Convert arrays from Ecliptic to Galactic''' 126 | l.info('Rotating to Galactic frame') 127 | return qarray.rotate(qarray.inv(QECL2GAL) ,vecl) 128 | -------------------------------------------------------------------------------- /planck/private_template.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | #add all the paths and rename to private.py 3 | database = '' 4 | exchangefolder = {'LFI':'', 5 | 'HFI':''} 6 | LFI_rimo = '' 7 | HFI_rimo = '' 8 | instrument_db = '' 9 | savfilename = '' 10 | AHF_limits = '' 11 | siam = '' 12 | PIX2ODPATH = '' 13 | HFI_calibfile = '' 14 | 15 | WOBBLE = { 'psi1_ref' : 0., 16 | 'psi2_ref' : 0., 17 | 'psi2_file' : '', 18 | 'sun_file' : '', 19 | 'planck_file' : '', 20 | } 21 | 22 | mKRJ_2_mKcmb = { 23 | } 24 | 25 | mkCMB_2_MJy_sr = { 26 | } 27 | -------------------------------------------------------------------------------- /planck/ps.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import pkgutil 3 | import numpy as np 4 | import os 5 | from astropy.io import fits as pyfits 6 | from configobj import ConfigObj 7 | import math 8 | 9 | import healpy 10 | 11 | def apply_mask(mask, m): 12 | m[mask == 0] = healpy.UNSEEN 13 | return m 14 | 15 | def sum_diff_maps(a, b): 16 | '''Returns half-sum and half-difference of input maps on common pixels 17 | ''' 18 | 19 | valid_pixels = np.logical_and(a != healpy.UNSEEN, b != healpy.UNSEEN) 20 | jackmaps = np.zeros_like([a,b]) 21 | jackmaps[:] = healpy.UNSEEN 22 | jackmaps[0][valid_pixels] = ( a[valid_pixels] + b[valid_pixels]) / 2 23 | jackmaps[1][valid_pixels] = ( a[valid_pixels] - b[valid_pixels]) / 2 24 | 25 | return jackmaps 26 | 27 | def smooth(m, arcmin, lmax = None): 28 | '''Utility to smooth a map with smooting by Healpix 29 | ''' 30 | unseen = m == healpy.UNSEEN 31 | healpy.write_map('tempmap.fits', m, nest = False) 32 | config_filename = 'config_smooth.txt' 33 | config = ConfigObj() 34 | config.filename = config_filename 35 | config['simul_type'] = 1 36 | if lmax: 37 | config['nlmax'] = lmax 38 | config['infile'] = 'tempmap.fits' 39 | config['outfile'] = 'tempmap_smoothed.fits' 40 | config['fwhm_arcmin'] = arcmin 41 | config['iter_order'] = 3 42 | config.write() 43 | if os.path.exists('tempmap_smoothed.fits'): 44 | os.remove('tempmap_smoothed.fits') 45 | callstring = ['smoothing','--double',config_filename] 46 | with open(os.devnull, 'w') as fnull: 47 | subprocess.call(callstring, shell=False,stdout=fnull,stderr=None) 48 | smoothed_m = healpy.read_map('tempmap_smoothed.fits') 49 | smoothed_m[unseen] = healpy.UNSEEN 50 | return smoothed_m 51 | 52 | def remove_dipole(m, gal_cut = 30): 53 | #module abs path 54 | abspath = os.path.dirname(__file__) 55 | if os.path.exists('tempmap.fits'): 56 | os.remove('tempmap.fits') 57 | healpy.write_map('tempmap.fits',m,nest = False) 58 | callstring = 'idl %s/fixmap.pro -IDL_QUIET 1 -quiet -args tempmap.fits %d' % (abspath,gal_cut) 59 | subprocess.call(callstring, shell=True) 60 | out = healpy.read_map('no_dipole_tempmap.fits', nest=True) 61 | os.remove('no_dipole_tempmap.fits') 62 | return out 63 | 64 | def anafast(m, m2=None, gal_cut = 30, lmax = None): 65 | '''Utility to run anafast by Healpix''' 66 | healpy.write_map('tempmap.fits', m, nest = False) 67 | config_filename = 'anafastconfig.txt' 68 | config = ConfigObj() 69 | config.filename = config_filename 70 | config['simul_type'] = 1 71 | if gal_cut: 72 | config['theta_cut_deg'] = gal_cut 73 | if lmax: 74 | config['nlmax'] = lmax 75 | config['infile'] = 'tempmap.fits' 76 | if not m2 is None: 77 | healpy.write_map('tempmap2.fits', m2, nest = False) 78 | config['infile2'] = 'tempmap2.fits' 79 | config['outfile'] = 'tempcl.fits' 80 | config['won'] = 0 81 | config.write() 82 | if os.path.exists('tempcl.fits'): 83 | os.remove('tempcl.fits') 84 | callstring = 'anafast --double %s' % config_filename 85 | subprocess.call(callstring, shell=True) 86 | cl = pyfits.open('tempcl.fits')[1].data.field('TEMPERATURE') 87 | os.remove('tempcl.fits') 88 | return cl 89 | 90 | def cut_planet(lat, lon, radius = 1.5, nside = 512): 91 | '''Cut planet 92 | 93 | Example: 94 | Jupiter [lat -40.33,lon 33.75] radius = 1.5 deg''' 95 | 96 | callstring = 'idl cut_planet.pro -IDL_QUIET 1 -quiet -args %f %f %f %f' % (lat, lon, radius, nside) 97 | popen = subprocess.Popen(callstring, shell=True, stdout=subprocess.PIPE, cwd = os.path.dirname(__file__)) 98 | output = popen.communicate()[0] 99 | return map(float, output.strip().split()) 100 | -------------------------------------------------------------------------------- /planck/test_correction.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import cPickle 3 | import numpy as np 4 | import healpy 5 | import logging as l 6 | import unittest 7 | import matplotlib.pyplot as plt 8 | 9 | from pointing import * 10 | from correction import * 11 | import private 12 | from LFI import LFI 13 | 14 | class TestCorrection(unittest.TestCase): 15 | 16 | def setUp(self): 17 | 18 | l.basicConfig(level=l.DEBUG, 19 | format='%(asctime)s %(levelname)s %(message)s') 20 | 21 | def test_deaberration(self): 22 | """Test with Michele's corrections""" 23 | ch = LFI(instrument_db='/u/zonca/planck/data/mission/SIAM/LFI_instrumentDB_9.3.fits')['LFI28M'] 24 | obt = np.array([1628860882.826]) # OD92 25 | pnt = Pointing(obt, coord='E', deaberration=False, wobble=False) 26 | vec = pnt.get(ch) # theta = 166 deg 27 | vecc = vec + deaberration(vec, obt, coord='E') 28 | qarray.norm_inplace(vecc) 29 | np.testing.assert_array_almost_equal(np.degrees(np.arccos(qarray.arraylist_dot(vec, vecc)))*60**2, np.array([[ 19.8740605]])) 30 | obt += 10. #30 sec after 14.6 deg 31 | pnt = Pointing(obt, coord='E', deaberration=False, wobble=False) 32 | vec = pnt.get(ch) # theta = 106 deg 33 | vecc = vec + deaberration(vec, obt, coord='E') 34 | qarray.norm_inplace(vecc) 35 | np.testing.assert_array_almost_equal(np.degrees(np.arccos(qarray.arraylist_dot(vec, vecc)))*60**2, np.array([[ 6.31009871]])) 36 | 37 | def test_get_wobble_psi2(self): 38 | self.assertAlmostEqual(get_wobble_psi2(1.067546522419189e+14/2**16), np.radians(-28.236426/60)) 39 | 40 | def test_null_correction(self): 41 | r = wobble([0,0], wobble_psi2_model=lambda x:np.array([private.WOBBLE_DX7['psi2_ref']]*len(x))) 42 | np.testing.assert_array_almost_equal(r, np.array([[-0., -0., -0., 1.], [-0., -0., -0., 1.]])) 43 | 44 | def test_wobble_correction(self): 45 | r = wobble(np.array([1635615346.1697083])) 46 | np.testing.assert_array_almost_equal(r, np.array([[ 2.08679712e-08, -1.56235725e-05, -0.00000000e+00, 1.00000000e+00]])) 47 | 48 | def test_ahf_wobble_correction_angles(self): 49 | obt = [106753612931221/2.**16 + 1] #PID 62, first of OD 93 50 | psi1, psi2 = get_ahf_wobble(obt) 51 | np.testing.assert_array_almost_equal(psi1, np.radians(np.array([4.4775999999999998])/60.)) 52 | np.testing.assert_array_almost_equal(psi2, np.radians(np.array([-28.2402000])/60.)) 53 | 54 | def test_ahf_wobble_correction_angles(self): 55 | obt = [106753612931221/2.**16 + 1] #PID 62, first of OD 93 56 | wobble_rot = ahf_wobble(obt) 57 | #TODO implement real test 58 | 59 | def test_read_ptcor1(self): 60 | delta_inscan, delta_xscan = read_ptcor1(100) 61 | self.assertAlmostEqual(delta_inscan, -0.16329599216) 62 | self.assertAlmostEqual(delta_xscan, -0.0351865320531) 63 | 64 | def test_ptcor1(self): 65 | 66 | rot = ptcor1(100) 67 | #TODO implement real test 68 | 69 | if __name__ == '__main__': 70 | unittest.main() 71 | -------------------------------------------------------------------------------- /planck/test_planck_LFI_HFI.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Planck import * 3 | 4 | class TestPlanckLFIHFI(unittest.TestCase): 5 | 6 | def setUp(self): 7 | self.Planck = Planck() 8 | self.lfi = self.Planck.inst['LFI'] 9 | self.hfi = self.Planck.inst['HFI'] 10 | 11 | def test_Planck(self): 12 | self.assertEqual(len(self.Planck.ch), 71) 13 | 14 | def test_LFI(self): 15 | self.assertEqual(self.lfi.name , 'LFI') 16 | self.assertEqual(len(self.lfi.ch), 22 ) 17 | self.assertEqual(len(self.lfi.d), 44 ) 18 | self.assertEqual(self.lfi['LFI25M'].tag, 'LFI25M') 19 | self.assertEqual(self.lfi['LFI25M'].arm, 'M') 20 | self.assertEqual(self.lfi['LFI25M'].RCA, 25) 21 | self.assertEqual(self.lfi['LFI27M'][0].tag, 'LFI27M-00') 22 | self.assertEqual(self.lfi['LFI27M'][0].ch.tag, 'LFI27M') 23 | self.assertEqual(self.lfi['LFI28S'].tag, 'LFI28S') 24 | self.assertEqual(self.lfi.ch[0].tag, 'LFI18M') 25 | self.assertEqual(self.lfi.ch[0].tag, 'LFI18M') 26 | 27 | def test_HFI(self): 28 | self.assertEqual(len(self.hfi.ch), 49) 29 | self.assertEqual(self.hfi['217-8a'].tag, '217-8a') 30 | self.assertEqual(self.hfi['545-4'].tag, '545-4') 31 | -------------------------------------------------------------------------------- /planck/test_pointing.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import cPickle 3 | import numpy as np 4 | import healpy 5 | import logging as l 6 | import unittest 7 | import matplotlib.pyplot as plt 8 | 9 | from pointing import * 10 | from LFI import LFI 11 | from testenv.remix import read_exchange 12 | 13 | class TestPointing(unittest.TestCase): 14 | 15 | def setUp(self): 16 | 17 | l.basicConfig(level=l.DEBUG, 18 | format='%(asctime)s %(levelname)s %(message)s') 19 | self.chlfi = LFI()['LFI28M'] 20 | self.TOLERANCE = 1e-7 21 | #from healpix 22 | self.ecl2gal_healpix = np.matrix([ 23 | [ -5.48824860e-02, -9.93821033e-01, -9.64762490e-02], 24 | [ 4.94116468e-01, -1.10993846e-01, 8.62281440e-01], 25 | [ -8.67661702e-01, -3.46354000e-04, 4.97154957e-01] 26 | ]) 27 | 28 | def test_prepare_for_dipole(self): 29 | '''Saves pointing array for testing dipole generation''' 30 | read_exchange([self.chlfi], ods = [100], discard_flag = False,type='R') 31 | pnt = Pointing(self.chlfi.f.obtx,coord='G') 32 | vec = pnt.get(self.chlfi) 33 | np.save('vec_LFI28M_OD100_G',vec) 34 | 35 | def test_prepare_for_M3(self): 36 | '''Saves pointing array for comparing with M3''' 37 | read_exchange([self.chlfi], ods = [100], discard_flag = False,type='R') 38 | span = 56300 39 | obt = self.chlfi.f.obtx[:span] 40 | pnt = Pointing(obt, coord='E') 41 | vec = pnt.get(self.chlfi) 42 | np.save('vec_LFI28M_OD100_E',vec) 43 | np.save('obt_LFI28M_OD100_E',obt) 44 | 45 | def test_pointing_vs_dpc(self): 46 | '''Check pointing against LFI DPC''' 47 | # pointing extracted from DPC trieste 48 | dpc=cPickle.load(open('/u/zonca/p/issues/pointing/pointing100_DPC.pkl')) 49 | i_dpc = dpc['sampleOBT'].searchsorted(106793429004442.0) 50 | thetadpc=dpc['theta'][i_dpc] 51 | phidpc=dpc['phi'][i_dpc] 52 | psidpc=dpc['psi'][i_dpc] 53 | dpc['psi'] = dpc['psi'][i_dpc:] 54 | dpc['theta'] = dpc['theta'][i_dpc:] 55 | dpc['phi'] = dpc['phi'][i_dpc:] 56 | dpc['sampleOBT'] = dpc['sampleOBT'][i_dpc:]/2**16 57 | dpc['name'] = 'dpc' 58 | 59 | read_exchange([self.chlfi], ods = [100], discard_flag = False,type='R') 60 | i_te = 697 61 | te = {'sampleOBT':self.chlfi.f.obtx[i_te:],'name':'te'} 62 | #pnt = Pointing(self.chlfi.f.obtx[697:698],coord='E') 63 | pnt = Pointing(te['sampleOBT'],coord='E', deaberration=False, wobble=False, horn_pointing=False) 64 | vec = pnt.get(self.chlfi) 65 | thetav, phiv, psiv = pnt.get_3ang(self.chlfi) 66 | te['theta'] = thetav 67 | te['phi'] = phiv 68 | theta, phi, psi = thetav[0], phiv[0], psiv[0] 69 | print('Theta DPC %f testenv %f' % (thetadpc, theta)) 70 | print('Phi DPC %f testenv %f' % (phidpc, phi)) 71 | span = 32.5 * 60 * 10 72 | for angle in ['theta','phi','diff_theta','diff_phi']: 73 | plt.figure() 74 | if angle.startswith('diff'): 75 | a = angle.split('_')[1] 76 | plt.plot(d['sampleOBT'][:span], dpc[a][:span]-te[a][:span],label=a.capitalize() + ' difference') 77 | else: 78 | for d in [dpc,te]: 79 | plt.plot(d['sampleOBT'][:span], d[angle][:span], label=d['name']) 80 | plt.legend();plt.grid() 81 | plt.title(angle.capitalize().replace('_',' ')) 82 | plt.xlabel('OBT') 83 | plt.ylabel('%s [rad]' % angle) 84 | plt.savefig('%s_dpc_te.png' % angle) 85 | assert abs(thetadpc - theta) < self.TOLERANCE 86 | assert abs(phidpc - phi) < self.TOLERANCE 87 | assert abs(psidpc - psi) < self.TOLERANCE 88 | 89 | def test_quaternion_ecl2gal(self): 90 | q = np.array([0, 0, 0, 1]) 91 | vecl = np.array([ 0.29192658, 0.45464871, 0.84147098]) 92 | qgal = quaternion_ecl2gal(q) 93 | vgal_ecl2gal = qarray.rotate(qgal,vecl).flatten() 94 | vgal_matrix = np.asarray(self.ecl2gal_healpix * vecl[:,np.newaxis]).flatten() 95 | np.testing.assert_array_almost_equal(vgal_ecl2gal , vgal_matrix) 96 | 97 | def test_vector_ecl2gal(self): 98 | vecl = np.array([ 0.29192658, 0.45464871, 0.84147098]) 99 | vgal_ecl2gal = vector_ecl2gal(vecl).flatten() 100 | vgal_matrix = np.asarray(self.ecl2gal_healpix * vecl[:,np.newaxis]).flatten() 101 | np.testing.assert_array_almost_equal(vgal_ecl2gal , vgal_matrix) 102 | 103 | def test_iqu_vs_m3(self): 104 | obt = np.array([1629538385.0881653, 1629538385.3650208]) 105 | pnt = Pointing(obt, deaberration=False, wobble=False, horn_pointing=False) 106 | pix, qw, uw = pnt.get_pix_iqu(self.chlfi) 107 | np.testing.assert_array_almost_equal(pix, [6100717, 6102734]) 108 | np.testing.assert_array_almost_equal(qw, [-8.252502679824829e-01, -8.330312371253967e-01]) 109 | np.testing.assert_array_almost_equal(uw, [5.647672414779663e-01, 5.532259941101074e-01]) 110 | 111 | if __name__ == '__main__': 112 | unittest.main() 113 | -------------------------------------------------------------------------------- /planck/test_pointingtools.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from pointingtools import * 4 | 5 | def AHF_path_to_od(path): 6 | return int(path.split('/')[-2]) 7 | 8 | class TestPointingTools(unittest.TestCase): 9 | 10 | 11 | def test_AHF_btw_od(self): 12 | obt = [1629623011.4397736, 1629883390.4398956] 13 | files = AHF_btw_OBT(obt) 14 | ods = map(AHF_path_to_od, files) 15 | self.assertEqual(ods, [100, 101, 102, 103]) 16 | 17 | if __name__ == '__main__': 18 | unittest.main() 19 | -------------------------------------------------------------------------------- /planck/toast.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | import copy 4 | import os 5 | import exceptions 6 | import glob 7 | import sqlite3 8 | 9 | import private 10 | from Planck import parse_channels, EXCLUDED_CH 11 | from metadata import DataSelector 12 | from collections import defaultdict 13 | 14 | import logging as l 15 | from pytoast.core import Run, ParMap 16 | 17 | from astropy.io import fits as pyfits 18 | 19 | l.basicConfig(level=l.INFO) 20 | 21 | 22 | class PPBoundaries: 23 | def __init__(self, freq, dbfile): 24 | """Load the start and stop OBT timestamps extracted from exchange format files""" 25 | self.dbfile = dbfile 26 | 27 | conn = sqlite3.connect( dbfile ) 28 | c = conn.cursor() 29 | 30 | self.ppf = [] 31 | 32 | tabname = 'ring_times_hfi' 33 | 34 | if ( freq == 30 ): 35 | tabname = 'ring_times_lfi30' 36 | if ( freq == 44 ): 37 | tabname = 'ring_times_lfi44' 38 | if ( freq == 70 ): 39 | tabname = 'ring_times_lfi70' 40 | 41 | execstr = "select id, pointID_unique, start, stop from %s" % ( tabname ) 42 | query = c.execute( execstr ) 43 | for id, pointID_unique, start, stop in query: 44 | self.ppf += [ ( start, stop ) ] 45 | 46 | c.close() 47 | 48 | def get(self, PID): 49 | # LFI PID 3 is row 1 50 | filerow = PID - 2 51 | return self.ppf[filerow] 52 | 53 | def get_eff_od(file_path): 54 | return int(os.path.basename(file_path).split('-')[1]) 55 | 56 | def strconv(f): 57 | """Formatting for the xml""" 58 | return "%.16g" % f 59 | 60 | def Params(dic=None): 61 | """Creates a Toast ParMap from a python dictionary""" 62 | params = ParMap() 63 | if not dic is None: 64 | for k,v in dic.iteritems(): 65 | if isinstance(v, float): 66 | v = strconv(v) 67 | else: 68 | v = str(v) 69 | params[k] = v 70 | return params 71 | 72 | DEFAULT_OBTMASK = {'LFI':1, 'HFI':1} 73 | DEFAULT_FLAGMASK = {'LFI':255, 'HFI':1} 74 | 75 | class ToastConfig(object): 76 | """Toast configuration class""" 77 | 78 | def __init__(self, odrange=None, channels=None, nside=1024, ordering='RING', coord='E', outmap='outmap.fits', exchange_folder=None, fpdb=None, output_xml='toastrun.xml', ahf_folder=None, components='IQU', obtmask=None, flagmask=None, log_level=l.INFO, remote_exchange_folder=None, remote_ahf_folder=None, calibration_file=None, dipole_removal=False, noise_tod=False, noise_tod_weight=None, efftype=None, flag_HFI_bad_rings=None, include_preFLS=False, ptcorfile=None, include_repointings=False, psd=None, deaberrate=True, extend_857=False, no_wobble=False, eff_is_for_flags=False, exchange_weights=None, beamsky=None, beamsky_weight=None, interp_order=5, horn_noise_tod=None, horn_noise_weight=None, horn_noise_psd=None, observation_is_interval=False, lfi_ring_range=None, hfi_ring_range=None, wobble_high=False): 79 | """TOAST configuration: 80 | 81 | odrange: list of start and end OD, AHF ODS, i.e. with whole pointing periods as the DPC is using 82 | lfi_ring_range: first and last LFI pointing ID to include 83 | hfi_ring_range: first and last HFI ring number to include 84 | channels: one of integer frequency, channel string, list of channel strings 85 | obtmask and flagmask: default LFI 1,255 HFI 1,1 86 | exchange_folder: either a string or a container or strings listing locations for Exchange Format data 87 | exchange_weights: list of scaling factors to apply to Exchange data prior to coadding 88 | eff_is_for_flags : only use Exchange data for flags 89 | remote_exchange_folder, remote_ahf_folder: they allow to run toast.py in one environment using ahf_folder and exchange_folder and then replace the path with the remote folders 90 | calibration_file: path to a fits calibration file, with first extension OBT, then one extension per channel with the calibration factors 91 | dipole_removal: dipole removal is performed ONLY if calibration is specified 92 | noise_tod: Add simulated noise TODs 93 | noise_tod_weight: scaling factor to apply to noise_tod 94 | flag_HFI_bad_rings: if None, flagged just for HFI. If a valid file, use that as input. 95 | include_preFLS : if None, True for LFI 96 | include_repointings : Construct intervals with the 4 minute repointing maneuvers: 10% dataset increase, continuous time stamps 97 | psd : templated name of an ASCII PSD files. Tag CHANNEL will be replaced with the appropriate channel identifier. 98 | horn_noise_tod : False 99 | horn_noise_weight : None 100 | horn_noise_psd : templated name of an ASCII PSD files. Tag HORN will be replaced with the appropriate identifier. 101 | deaberrate : Correct pointing for aberration 102 | extend_857 : Whether or not to include the RTS bolometer, 857-4 in processing 103 | no_wobble : Disable all flavors of wobble angle correction 104 | wobble_high : Use 8Hz wobble correction rather than per ring 105 | beamsky : templated name of the beamsky files for OTF sky convolution. Tag CHANNEL will be replaced with the appropriate channel identifier. 106 | beamsky_weight : scaling factor to apply to the beamsky 107 | interp_order : beamsky interpolation order defines number of cartesian pixels to interpolate over 108 | observation_is_interval : If True, do not split operational days into pointing period intervals 109 | 110 | additional configuration options are available modifying: 111 | .config 112 | and Data Selector configuration: 113 | .data_selector.config 114 | dictionaries before running .run() 115 | """ 116 | l.root.level = log_level 117 | self.extend_857 = extend_857 118 | if self.extend_857: 119 | if '857-4' in EXCLUDED_CH: EXCLUDED_CH.remove('857-4') 120 | if sum([odrange!=None, lfi_ring_range!=None, hfi_ring_range!=None]) != 1: 121 | raise Exception('Must specify exactly one type of data span: OD, LFI PID or HFI ring') 122 | self.odrange = odrange 123 | self.lfi_ring_range = lfi_ring_range 124 | self.hfi_ring_range = hfi_ring_range 125 | self.nside = nside 126 | self.coord = coord 127 | self.ordering = ordering 128 | self.outmap = outmap 129 | if channels == None: 130 | raise Exception('Must define which channels to include') 131 | self.channels = parse_channels(channels) 132 | self.f = self.channels[0].f 133 | self.output_xml = output_xml 134 | self.ptcorfile = ptcorfile 135 | if no_wobble and wobble_high: 136 | raise Exception('no_wobble and wobble_high are mutually exclusive') 137 | self.no_wobble = no_wobble 138 | self.wobble_high = wobble_high 139 | self.include_repointings = include_repointings 140 | self.deaberrate = deaberrate 141 | self.noise_tod = noise_tod 142 | self.noise_tod_weight = noise_tod_weight 143 | self.psd = psd 144 | self.horn_noise_tod = horn_noise_tod 145 | self.horn_noise_weight = horn_noise_weight 146 | self.horn_noise_psd = horn_noise_psd 147 | if self.horn_noise_tod and not self.horn_noise_psd: 148 | raise Exception('Must specify horn_noise_psd template name when enabling horn_noise') 149 | self.fpdb = fpdb or private.rimo[self.f.inst.name] 150 | self.beamsky = beamsky 151 | self.beamsky_weight = beamsky_weight 152 | self.interp_order = interp_order 153 | self.observation_is_interval = observation_is_interval 154 | self.rngorder = { 155 | 'LFI18M' : 0, 156 | 'LFI18S' : 1, 157 | 'LFI19M' : 2, 158 | 'LFI19S' : 3, 159 | 'LFI20M' : 4, 160 | 'LFI20S' : 5, 161 | 'LFI21M' : 6, 162 | 'LFI21S' : 7, 163 | 'LFI22M' : 8, 164 | 'LFI22S' : 9, 165 | 'LFI23M' : 10, 166 | 'LFI23S' : 11, 167 | 'LFI24M' : 12, 168 | 'LFI24S' : 13, 169 | 'LFI25M' : 14, 170 | 'LFI25S' : 15, 171 | 'LFI26M' : 16, 172 | 'LFI26S' : 17, 173 | 'LFI27M' : 18, 174 | 'LFI27S' : 19, 175 | 'LFI28M' : 20, 176 | 'LFI28S' : 21, 177 | '100-1a' : 22, 178 | '100-1b' : 23, 179 | '100-2a' : 24, 180 | '100-2b' : 25, 181 | '100-3a' : 26, 182 | '100-3b' : 27, 183 | '100-4a' : 28, 184 | '100-4b' : 29, 185 | '143-1a' : 30, 186 | '143-1b' : 31, 187 | '143-2a' : 32, 188 | '143-2b' : 33, 189 | '143-3a' : 34, 190 | '143-3b' : 35, 191 | '143-4a' : 36, 192 | '143-4b' : 37, 193 | '143-5' : 38, 194 | '143-6' : 39, 195 | '143-7' : 40, 196 | '143-8' : 41, 197 | '217-5a' : 42, 198 | '217-5b' : 43, 199 | '217-6a' : 44, 200 | '217-6b' : 45, 201 | '217-7a' : 46, 202 | '217-7b' : 47, 203 | '217-8a' : 48, 204 | '217-8b' : 49, 205 | '217-1' : 50, 206 | '217-2' : 51, 207 | '217-3' : 52, 208 | '217-4' : 53, 209 | '353-3a' : 54, 210 | '353-3b' : 55, 211 | '353-4a' : 56, 212 | '353-4b' : 57, 213 | '353-5a' : 58, 214 | '353-5b' : 59, 215 | '353-6a' : 60, 216 | '353-6b' : 61, 217 | '353-1' : 62, 218 | '353-2' : 63, 219 | '353-7' : 64, 220 | '353-8' : 65, 221 | '545-1' : 66, 222 | '545-2' : 67, 223 | '545-3' : 68, 224 | '545-4' : 69, 225 | '857-1' : 70, 226 | '857-2' : 71, 227 | '857-3' : 72, 228 | '857-4' : 73, 229 | 'LFI18' : 74, 230 | 'LFI19' : 75, 231 | 'LFI20' : 76, 232 | 'LFI21' : 77, 233 | 'LFI22' : 78, 234 | 'LFI23' : 79, 235 | 'LFI24' : 80, 236 | 'LFI25' : 81, 237 | 'LFI26' : 82, 238 | 'LFI27' : 83, 239 | 'LFI28' : 84, 240 | '100-1' : 85, 241 | '100-2' : 86, 242 | '100-3' : 87, 243 | '100-4' : 88, 244 | '143-1' : 89, 245 | '143-2' : 90, 246 | '143-3' : 91, 247 | '143-4' : 92, 248 | '217-5' : 93, 249 | '217-6' : 94, 250 | '217-7' : 95, 251 | '217-8' : 96, 252 | '353-3' : 97, 253 | '353-4' : 98, 254 | '353-5' : 99, 255 | '353-6' : 100, 256 | } 257 | 258 | self.config = {} 259 | if self.f.inst.name == 'LFI': 260 | self.config['pairflags'] = True 261 | else: 262 | self.config['pairflags'] = False 263 | 264 | if efftype is None: 265 | efftype ='R' 266 | if self.f.inst.name == 'LFI' and (not calibration_file is None): 267 | efftype ='C' 268 | self.data_selector = DataSelector(channels=self.channels, efftype=efftype, include_preFLS=include_preFLS) 269 | 270 | self.exchange_weights = exchange_weights 271 | 272 | if remote_exchange_folder: 273 | if isinstance(remote_exchange_folder, str): 274 | remote_exchange_folder = [remote_exchange_folder] 275 | if remote_exchange_folder[-1] != '/': 276 | remote_exchange_folder += '/' 277 | 278 | self.remote_exchange_folder = remote_exchange_folder 279 | if remote_ahf_folder: 280 | if remote_ahf_folder[-1] != '/': 281 | remote_ahf_folder += '/' 282 | self.remote_ahf_folder = remote_ahf_folder 283 | if exchange_folder: 284 | if isinstance(exchange_folder, str): 285 | exchange_folder = [exchange_folder] 286 | self.exchange_folder = exchange_folder 287 | 288 | self.data_selector.config[ 'exchangefolder' ] = exchange_folder[0] 289 | 290 | if ahf_folder: 291 | self.data_selector.config['ahf_folder'] = ahf_folder 292 | 293 | if self.odrange: 294 | self.data_selector.by_od_range(self.odrange) 295 | elif self.lfi_ring_range: 296 | self.data_selector.by_lfi_rings(self.lfi_ring_range) 297 | elif self.hfi_ring_range: 298 | self.data_selector.by_hfi_rings(self.hfi_ring_range) 299 | else: 300 | raise Exception('Must specify one type of data span') 301 | 302 | 303 | self.wobble = private.WOBBLE 304 | self.components = components 305 | 306 | self.obtmask = obtmask or DEFAULT_OBTMASK[self.f.inst.name] 307 | self.flagmask = flagmask or DEFAULT_FLAGMASK[self.f.inst.name] 308 | 309 | self.calibration_file = calibration_file 310 | self.dipole_removal = dipole_removal 311 | 312 | if flag_HFI_bad_rings is None: 313 | if self.f.inst.name == 'HFI': 314 | flag_HFI_bad_rings = True 315 | else: 316 | flag_HFI_bad_rings = False 317 | if flag_HFI_bad_rings: 318 | if ( os.path.isfile(str(flag_HFI_bad_rings)) ): 319 | self.bad_rings = flag_HFI_bad_rings 320 | else: 321 | self.bad_rings = private.HFI_badrings 322 | else: 323 | self.bad_rings = None 324 | 325 | self.eff_is_for_flags = eff_is_for_flags 326 | 327 | self.fptab = None 328 | 329 | def parse_fpdb(self, channel, key): 330 | if self.fptab == None: 331 | fptab = pyfits.getdata(self.fpdb, 1) 332 | ind = (fptab.field('DETECTOR') == channel).ravel() 333 | if np.sum(ind) != 1: 334 | raise Exception('Error matching {} in {}: {} matches.'.format(channel, self.fpdb, np.sum(ind))) 335 | return fptab.field(key)[ind][0] 336 | 337 | def run(self, write=True): 338 | """Call the python-toast bindings to create the xml configuration file""" 339 | self.conf = Run() 340 | 341 | if self.noise_tod or self.horn_noise_tod: 342 | self.conf.variable_add ( "rngbase", "native", Params({"default":"0"}) ) 343 | 344 | sky = self.conf.sky_add ( "sky", "native", ParMap() ) 345 | 346 | mapset = sky.mapset_add ( '_'.join(['healpix',self.components, self.ordering]), "healpix", 347 | Params({ 348 | "path" : self.outmap, 349 | "fullsky" : "TRUE", 350 | "stokes" : self.components, 351 | "order" : self.ordering, 352 | "coord" : self.coord, 353 | "nside" : str(self.nside), 354 | "units" : "micro-K" 355 | })) 356 | 357 | #if self.f.inst.name == 'LFI': 358 | # wobble_offset = 0; 359 | #else: 360 | # wobble_offset = self.wobble["psi2_offset"] 361 | 362 | if self.no_wobble: 363 | teleparams = { 364 | "wobble_ahf_high":"FALSE", 365 | "wobble_ahf_obs":"FALSE", 366 | "wobblepsi2dir":"" 367 | } 368 | else: 369 | if self.wobble_high: 370 | wobble_obs = 'FALSE' 371 | wobble_high = 'TRUE' 372 | else: 373 | wobble_obs = 'TRUE' 374 | wobble_high = 'FALSE' 375 | 376 | teleparams = { 377 | #"wobblepsi2dir":self.wobble["psi2_dir"], 378 | "wobblepsi2_ref":self.wobble["psi2_ref"], 379 | "wobblepsi1_ref":self.wobble["psi1_ref"], 380 | "wobble_ahf_obs":wobble_obs, 381 | "wobble_ahf_high":wobble_high 382 | #"wobblepsi2_offset":wobble_offset 383 | } 384 | 385 | if self.ptcorfile: 386 | teleparams['ptcorfile'] = self.ptcorfile 387 | 388 | if self.deaberrate != None: 389 | if self.deaberrate: 390 | teleparams['deaberrate'] = 'TRUE' 391 | else: 392 | teleparams['deaberrate'] = 'FALSE' 393 | 394 | tele = self.conf.telescope_add ( "planck", "planck", 395 | Params(teleparams)) 396 | 397 | fp = tele.focalplane_add ( "FP_%s" % self.f.inst.name, "planck_rimo", Params({"path":self.fpdb}) ) 398 | 399 | self.add_pointing(tele) 400 | self.add_observations(tele) 401 | self.add_streams() 402 | self.add_eff_tods() 403 | self.add_noise() 404 | self.add_channels(tele) 405 | if write: 406 | self.write() 407 | 408 | 409 | def write(self): 410 | # write out XML 411 | self.conf.write ( self.output_xml ) 412 | 413 | 414 | def add_pointing(self, telescope): 415 | # Add pointing files 416 | for i,ahf in enumerate(self.data_selector.get_AHF()): 417 | path = str(ahf[0]) 418 | if self.remote_ahf_folder: 419 | path = path.replace(self.data_selector.config['ahf_folder'], self.remote_ahf_folder) 420 | telescope.pointing_add ( "%04d" % i, "planck_ahf", Params({"path": path})) 421 | 422 | 423 | @property 424 | def observations(self): 425 | try: 426 | return self._observations 427 | except: 428 | self._observations = self.data_selector.get_OBS() 429 | return self.observations 430 | 431 | 432 | def add_observations(self, telescope): 433 | """Each observation is an OD as specified in the AHF files""" 434 | # Add streamset 435 | self.strset = telescope.streamset_add ( self.f.inst.name, "native", Params() ) 436 | 437 | # Add observations 438 | 439 | # For Planck, each observation must cache the timestamps for all days included 440 | # in the observation, which is very expensive. For this reason, the number of 441 | # ODs in a single observation should be the minimum necessary for the size of 442 | # the interval being considered. For applications which do not care about noise 443 | # stationarity or which are only dealing with ring-by-ring quantities, one OD 444 | # per observation is fine. If you wish to consider intervals longer than a day 445 | # as a single stationary interval, then each observation will need to include 446 | # multiple ODs. 447 | 448 | # For "planck_exchange" format, if no "start" or "stop" times are specified, 449 | # then the observation will span the time range of the EFF data specified in 450 | # the "times1", "times2", "times3", etc parameters. 451 | 452 | broken_od = defaultdict(None) 453 | 454 | # Observations are same for all datasets but now there may be 455 | # several exchange folders and raw streams to add. Therefore 456 | # tod_name_list and tod_par_list are lists of dictionaries. 457 | 458 | self.tod_name_list = [] 459 | self.tod_par_list = [] 460 | for i in range(len(self.exchange_folder)): 461 | self.tod_name_list.append( defaultdict(list) ) 462 | self.tod_par_list.append( defaultdict(list) ) 463 | 464 | # Add observations 465 | 466 | for iobs, observation in enumerate(self.observations): 467 | params = {"start":observation.start, "stop":observation.stop} 468 | for i, eff in enumerate(observation.EFF): 469 | if self.remote_exchange_folder: 470 | params[ "times%d" % (i+1) ] = eff.replace(self.exchange_folder[0], self.remote_exchange_folder[0]) 471 | else: 472 | params[ "times%d" % (i+1) ] = eff 473 | obs = self.strset.observation_add ( "%04d%s" % (observation.od, observation.tag) , "planck_exchange", Params(params) ) 474 | 475 | if self.observation_is_interval: 476 | # intervals are observations 477 | obs.interval_add( '{:04}'.format(iobs), "native", Params({"start":observation.start, "stop":observation.stop}) ) 478 | else: 479 | pointing_periods = observation.PP 480 | if self.include_repointings: 481 | # First interval begins with the operational day, last one ends with it. New interval begins when the old stable pointing ends. 482 | # First and last included samples remain the same. 483 | for ipp, pp in enumerate(pointing_periods): 484 | if ipp == 0: 485 | # Remove the comments in this section to include period between OD and ring start 486 | #if iobs == 0: 487 | obs.interval_add( "%05d-%d" % (pp.number, pp.splitnumber), "native", Params({"start":pp.start, "stop":pointing_periods[ipp+1].start}) ) 488 | #else: 489 | # obs.interval_add( "%05d-%d" % (pp.number, pp.splitnumber), "native", Params({"start":observation.start, "stop":pointing_periods[ipp+1].start}) ) 490 | elif ipp == len(pointing_periods) - 1: 491 | if iobs == len(self.observations) - 1: 492 | obs.interval_add( "%05d-%d" % (pp.number, pp.splitnumber), "native", Params({"start":pp.start, "stop":pp.stop}) ) 493 | else: 494 | obs.interval_add( "%05d-%d" % (pp.number, pp.splitnumber), "native", Params({"start":pp.start, "stop":observation.stop}) ) 495 | else: 496 | obs.interval_add( "%05d-%d" % (pp.number, pp.splitnumber), "native", Params({"start":pp.start, "stop":pointing_periods[ipp+1].start}) ) 497 | else: 498 | # Intervals are the stable pointing periods 499 | for pp in pointing_periods: 500 | obs.interval_add( "%05d-%d" % (pp.number, pp.splitnumber), "native", Params({"start":pp.start, "stop":pp.stop}) ) 501 | 502 | for ch in self.channels: 503 | print("Observation %d%s, EFF ODs:%s" % (observation.od, observation.tag, str(map(get_eff_od, observation.EFF)))) 504 | for ix, fx in enumerate(self.exchange_folder): 505 | for i, file_path in enumerate(observation.EFF): 506 | eff_od = get_eff_od(file_path) 507 | # Add TODs for this stream 508 | params = {} 509 | params[ "flagmask" ] = self.flagmask 510 | params[ "obtmask" ] = self.obtmask 511 | params[ "hdu" ] = ch.eff_tag 512 | if self.config['pairflags']: 513 | params[ "pairflags" ] = 'TRUE' 514 | if self.remote_exchange_folder: 515 | params[ "path" ] = file_path.replace(self.exchange_folder[0], self.remote_exchange_folder[ix]) 516 | else: 517 | params[ "path" ] = file_path.replace(self.exchange_folder[0], self.exchange_folder[ix]) 518 | tag = '' 519 | if i==(len(observation.EFF)-1) and not observation.break_startrow is None: 520 | params['rows'] = observation.break_startrow + 1 521 | tag = 'a' 522 | broken_od[ch.tag] = eff_od 523 | if not observation.break_stoprow is None and broken_od[ch.tag]==eff_od: 524 | params['startrow'] = observation.break_stoprow 525 | tag = 'b' 526 | broken_od[ch.tag] = None 527 | name = "%s_%d%s" % (ch.tag, eff_od, tag) 528 | if name not in self.tod_name_list[ix][ch.tag]: 529 | print('add ' + name) 530 | self.tod_name_list[ix][ch.tag].append(name) 531 | self.tod_par_list[ix][ch.tag].append(params) 532 | else: 533 | print("skip " + name) 534 | 535 | 536 | def add_streams(self): 537 | # Add streams for data components 538 | basename = "@rngbase@" 539 | 540 | self.strm = {} 541 | 542 | for ch in self.channels: 543 | stack_elements = [] 544 | 545 | # add simulated noise stream 546 | if self.noise_tod: 547 | rngstream = self.rngorder[ ch.tag ] * 100000 548 | 549 | noisename = "/planck/" + self.f.inst.name + "/noise_" + ch.tag 550 | self.strm["simnoise_" + ch.tag] = self.strset.stream_add( "simnoise_" + ch.tag, "native", Params( ) ) 551 | suffix = '' 552 | if self.noise_tod_weight: 553 | suffix += ',PUSH:$' + strconv(self.noise_tod_weight) + ',MUL' 554 | stack_elements.append( "PUSH:simnoise_" + ch.tag + suffix) 555 | if self.observation_is_interval: 556 | # one noise tod per observation. 557 | # 558 | # FIXME: this code will not work. the start and stop times 559 | # must be the *detector* start and stop times inside 560 | # the observation boundaries (which are set by the AHF). 561 | # so you must iterate over self.pp_boundaries and find 562 | # the first and last valid detector times inside this observation. 563 | # 564 | for iobs, observation in enumerate(self.observations): 565 | self.strm["simnoise_" + ch.tag].tod_add ( "nse_%s_%05d" % (ch.tag, iobs), "sim_noise", Params({ 566 | "noise" : noisename, 567 | "base" : basename, 568 | "start" : observation.start, 569 | "stop" : observation.stop, 570 | "offset" : rngstream + iobs 571 | })) 572 | else: 573 | # one noise tod per pointing period 574 | self.pp_boundaries = PPBoundaries(self.f.freq, self.data_selector.config['database']) 575 | for row, pp_boundaries in enumerate(self.pp_boundaries.ppf): 576 | if pp_boundaries[1] < self.observations[0].start or pp_boundaries[0] > self.observations[-1].stop: 577 | continue 578 | self.strm["simnoise_" + ch.tag].tod_add ( "nse_%s_%05d" % (ch.tag, row), "sim_noise", Params({ 579 | "noise" : noisename, 580 | "base" : basename, 581 | "start" : pp_boundaries[0], 582 | "stop" : pp_boundaries[1], 583 | "offset" : rngstream + row 584 | })) 585 | 586 | # add simulated noise stream common to each horn 587 | if self.horn_noise_tod and ch.tag[-1] in 'MSab': 588 | horn = ch.tag[:-1] 589 | rngstream = self.rngorder[ horn ] * 100000 590 | 591 | noisename = "/planck/" + self.f.inst.name + "/noise_" + horn 592 | self.strm["simnoise_" + horn] = self.strset.stream_add( "simnoise_" + horn, "native", Params( ) ) 593 | suffix = '' 594 | if self.horn_noise_weight: 595 | suffix += ',PUSH:$' + strconv(self.horn_noise_weight) + ',MUL' 596 | if len(stack_elements) != 0: 597 | suffix += ',ADD' 598 | stack_elements.append( "PUSH:simnoise_" + horn + suffix) 599 | if self.observation_is_interval: 600 | # one noise tod per observation 601 | for iobs, observation in enumerate(self.observations): 602 | self.strm["simnoise_" + horn].tod_add ( "nse_%s_%05d" % (horn, iobs), "sim_noise", Params({ 603 | "noise" : noisename, 604 | "base" : basename, 605 | "start" : observation.start, 606 | "stop" : observation.stop, 607 | "offset" : rngstream + iobs 608 | })) 609 | else: 610 | # one noise tod per pointing period 611 | self.pp_boundaries = PPBoundaries(self.f.freq) 612 | for row, pp_boundaries in enumerate(self.pp_boundaries.ppf): 613 | if pp_boundaries[1] < self.observations[0].start or pp_boundaries[0] > self.observations[-1].stop: 614 | continue 615 | self.strm["simnoise_" + horn].tod_add ( "nse_%s_%05d" % (horn, row), "sim_noise", Params({ 616 | "noise" : noisename, 617 | "base" : basename, 618 | "start" : pp_boundaries[0], 619 | "stop" : pp_boundaries[1], 620 | "offset" : rngstream + row 621 | })) 622 | 623 | # add the beam sky 624 | if self.beamsky: 625 | epsilon = self.parse_fpdb(ch.tag, 'epsilon') 626 | #beamskyname = '/planck/' + self.f.inst.name + '/' + ch.tag 627 | beamskyname = '/planck/' + ch.tag 628 | self.strm["beamsky_" + ch.tag] = self.strset.stream_add( "beamsky_" + ch.tag, "planck_beamsky", Params({ 629 | 'path' : self.beamsky.replace('CHANNEL', ch.tag), 630 | 'epsilon' : str(epsilon), 631 | 'interp_order' : str(self.interp_order), 632 | 'coord' : self.coord, 633 | 'channel' : beamskyname 634 | }) ) 635 | suffix = '' 636 | if self.beamsky_weight: 637 | suffix += ',PUSH:$' + strconv(self.beamsky_weight) + ',MUL' 638 | if len(stack_elements) != 0: 639 | suffix += ',ADD' 640 | stack_elements.append( "PUSH:beamsky_" + ch.tag + suffix) 641 | 642 | # add real data streams, either for flags or data plus flags 643 | for i, x in enumerate(self.exchange_folder): 644 | self.strm[ 'raw{}_{}'.format(i, ch.tag) ] = self.strset.stream_add( "raw{}_{}".format(i, ch.tag), "native", Params() ) 645 | if self.eff_is_for_flags: 646 | suffix = ',FLG' 647 | else: 648 | suffix = '' 649 | if self.exchange_weights: 650 | suffix = ',PUSH:$' + strconv(self.exchange_weights[i]) + ',MUL' 651 | if len(stack_elements) != 0: 652 | suffix += ',ADD' 653 | stack_elements.append( "PUSH:raw{}_{}{}".format(i, ch.tag, suffix) ) 654 | 655 | # add calibration stream 656 | if (not self.calibration_file is None): 657 | self.strm["cal_" + ch.tag] = self.strset.stream_add( "cal_" + ch.tag, "planck_cal", Params( {"hdu":ch.tag, "path":self.calibration_file } ) ) 658 | stack_elements.append("PUSH:cal_" + ch.tag + ",MUL") 659 | 660 | # dipole subtract 661 | if self.dipole_removal: 662 | self.strm["dipole_" + ch.tag] = self.strset.stream_add( "dipole_" + ch.tag, "dipole", Params( {"channel":ch.tag, "coord":"E"} ) ) 663 | stack_elements.append("PUSH:dipole_" + ch.tag + ",SUB") 664 | 665 | # bad rings 666 | if not self.bad_rings is None: 667 | self.strm["bad_" + ch.tag] = self.strset.stream_add ( "bad_" + ch.tag, "planck_bad", Params({'detector':ch.tag, 'path':self.bad_rings}) ) 668 | stack_elements.append("PUSH:bad_" + ch.tag + ",FLG") 669 | 670 | # stack 671 | expr = ','.join([el for el in stack_elements]) 672 | self.strm["stack_" + ch.tag] = self.strset.stream_add ( "stack_" + ch.tag, "stack", Params( {"expr":expr} ) ) 673 | 674 | 675 | def add_eff_tods(self): 676 | """Add TOD files already included in tod_name_list and tod_par_list to the streamset""" 677 | for ix in range(len(self.exchange_folder)): 678 | # remove duplicate files on breaks 679 | for ch in self.channels: 680 | for name in [n for n in self.tod_name_list[ix][ch.tag] if n.endswith('a')]: 681 | try: 682 | delindex = self.tod_name_list[ix][ch.tag].index(name.rstrip('a')) 683 | print('Removing %s because of breaks' % self.tod_name_list[ix][ch.tag][delindex]) 684 | del self.tod_name_list[ix][ch.tag][delindex] 685 | del self.tod_par_list[ix][ch.tag][delindex] 686 | except exceptions.ValueError: 687 | pass 688 | 689 | # add EFF to stream 690 | for ch in self.channels: 691 | for name, par in zip(self.tod_name_list[ix][ch.tag], self.tod_par_list[ix][ch.tag]): 692 | self.strm[ "raw{}_{}".format(ix, ch.tag) ].tod_add ( name, "planck_exchange", Params(par) ) 693 | 694 | 695 | def add_noise(self): 696 | # Add RIMO noise model (LFI) or mission average PSD (HFI) 697 | 698 | for ch in self.channels: 699 | noise = self.strset.noise_add ( "noise_" + ch.tag, "native", Params() ) 700 | 701 | # add PSD 702 | if self.psd: 703 | psdname = self.psd.replace('CHANNEL', ch.tag) 704 | noise.psd_add ( "psd", "ascii", Params({ 705 | "start" : self.strset.observations()[0].start(), 706 | "stop" : self.strset.observations()[-1].stop(), 707 | "path": psdname 708 | })) 709 | else: 710 | noise.psd_add ( "psd", "planck_rimo", Params({ 711 | "start" : self.strset.observations()[0].start(), 712 | "stop" : self.strset.observations()[-1].stop(), 713 | "path": self.fpdb, 714 | "detector": ch.tag 715 | })) 716 | # add horn noise psd 717 | if self.horn_noise_tod and ch.tag[-1] in 'aM': 718 | horn = ch.tag[:-1] 719 | noise = self.strset.noise_add ( "noise_" + horn, "native", Params() ) 720 | psdname = self.horn_noise_psd.replace('HORN', horn) 721 | noise.psd_add ( "psd", "ascii", Params({ 722 | "start" : self.strset.observations()[0].start(), 723 | "stop" : self.strset.observations()[-1].stop(), 724 | "path": psdname 725 | })) 726 | 727 | 728 | def add_channels(self, telescope): 729 | params = ParMap() 730 | params[ "focalplane" ] = self.conf.telescopes()[0].focalplanes()[0].name() 731 | for ch in self.channels: 732 | params[ "detector" ] = ch.tag 733 | params[ "stream" ] = "/planck/%s/stack_%s" % (self.f.inst.name, ch.tag) 734 | params[ "noise" ] = "/planck/%s/noise_%s" % (self.f.inst.name, ch.tag) 735 | telescope.channel_add ( ch.tag, "native", params ) 736 | 737 | 738 | if __name__ == '__main__': 739 | 740 | # Default LFI run 741 | 742 | conf = ToastConfig([740, 760], 30, nside=1024, ordering='RING', coord='E', efftype='R', output_xml='test_30_default.xml') 743 | conf.run() 744 | 745 | # # LFI run with noise simulation and real data flags 746 | # 747 | #conf = ToastConfig([450, 460], 30, nside=1024, ordering='RING', coord='E', efftype='C', output_xml='test_30_simnoise.xml', noise_tod=True) 748 | #conf.run() 749 | # 750 | # # LFI real data run with calibration and dipole subtraction 751 | # 752 | # conf = ToastConfig([97, 101], 30, nside=1024, ordering='RING', coord='E', efftype='C', output_xml='test_30_dical.xml', calibration_file='/project/projectdirs/planck/data/mission/calibration/dx7/lfi/369S/C030-0000-369S-20110713.fits', dipole_removal=True) 753 | # conf.run() 754 | # 755 | # # LFI noise simulation with real flags, calibration and dipole subtraction 756 | # 757 | # conf = ToastConfig([97, 101], 30, nside=1024, ordering='RING', coord='E', efftype='C', output_xml='test_30_simdical.xml', calibration_file='/project/projectdirs/planck/data/mission/calibration/dx7/lfi/369S/C030-0000-369S-20110713.fits', dipole_removal=True, noise_tod=True) 758 | # conf.run() 759 | # 760 | # # HFI default run 761 | # 762 | # conf = ToastConfig([97, 101], 100, nside=2048, ordering='NEST', coord='G', output_xml='test_100_default.xml') 763 | # conf.run() 764 | # 765 | # # HFI noise simulation 766 | # 767 | # conf = ToastConfig([97, 101], 100, nside=2048, ordering='NEST', coord='G', output_xml='test_100_simnoise.xml', noise_tod=True) 768 | # conf.run() 769 | # 770 | # # HFI real data run with calibration and dipole subtraction 771 | # 772 | # conf = ToastConfig([97, 101], 100, nside=2048, ordering='NEST', coord='G', output_xml='test_100_dical.xml', calibration_file='/project/projectdirs/planck/data/mission/calibration/dx7/hfi/variable_gains_100GHz.fits', dipole_removal=True) 773 | # conf.run() 774 | # 775 | # # HFI noise simulation with real flags, calibration and dipole subtraction 776 | # 777 | # conf = ToastConfig([97, 101], 100, nside=2048, ordering='NEST', coord='G', output_xml='test_100_simdical.xml', calibration_file='/project/projectdirs/planck/data/mission/calibration/dx7/hfi/variable_gains_100GHz.fits', dipole_removal=True, noise_tod=True) 778 | # conf.run() 779 | # 780 | -------------------------------------------------------------------------------- /planck/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import numpy as np 3 | from calendar import timegm 4 | import ephem 5 | import datetime 6 | from . import private 7 | try: 8 | from itertools import zip 9 | except: 10 | pass 11 | from itertools import chain, repeat 12 | import os 13 | try: 14 | from exceptions import ValueError 15 | except: 16 | pass 17 | 18 | OBTSTARTDATE = datetime.datetime(1958,1,1,0,0,0) 19 | LAUNCH = datetime.datetime(2009, 5, 13, 13, 11, 57, 565826) 20 | SECONDSPERDAY = 3600 * 24 21 | 22 | def pix2od(ch, pixels): 23 | """ nside 512 NEST pixel number to OD [91-563 excluding 454-455] for Planck channels 24 | it returns a list of sets. 25 | Each set contains the ODs hit by each pixel 26 | """ 27 | from bitstring import ConstBitArray 28 | filename = os.path.join(private.PIX2ODPATH, 'od_by_pixel_%s.bin' % ch.replace('M','S')) 29 | pixels_by_od = ConstBitArray(filename = filename) 30 | odrange = [91, 563+1] 31 | num_ods = odrange[1] - odrange[0] 32 | NSIDE = 512 33 | NPIX = 12 * NSIDE**2 34 | tot_ods = list() 35 | if np.any(np.array(pixels) >= NPIX): 36 | raise ValueError('ERROR: input pixels must be NSIDE 512, RTFM!') 37 | for pix in pixels: 38 | ods = set(np.array(list(pixels_by_od[num_ods*pix:num_ods*pix+num_ods].findall([True]))) + odrange[0]) 39 | tot_ods.append(ods) 40 | return tot_ods 41 | 42 | def grouper(n, iterable, padvalue=None): 43 | "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" 44 | return zip(*[chain(iterable, repeat(padvalue, n-1))]*n) 45 | 46 | def ahfdate2obt(ahfdate): 47 | from dipole import jd2obt 48 | jd = ephem.Date(ahfdate.replace('T',' ').replace('-','/')) - ephem.Date('-4713/1/1 12:00:0') 49 | return jd2obt(jd) 50 | 51 | def jd2scet(jd): 52 | intPart = np.floor(jd + .5) 53 | f = jd + .5 - intPart 54 | tempYear = np.ones_like(jd) * intPart 55 | tempVal = np.floor((intPart-1867216.25)/36524.25) 56 | tempYear[intPart>2299160] = (intPart+1+tempVal-np.floor(tempVal/4))[intPart>2299160] 57 | c = tempYear + 1524 58 | d = np.floor((c-122.1)/365.25) 59 | e = np.floor(365.25*d) 60 | h = np.floor((c-e)/30.6001) 61 | 62 | day = c-e+f-np.floor(30.6001*h) 63 | month = np.where(h<14, h-1, h-13) 64 | year = np.where(month<3, d-4715, d-4716) 65 | 66 | jdOff=jd+0.5 67 | dayOffset = (jdOff-np.floor(jdOff))*86400 68 | hours = np.floor(dayOffset/3600); 69 | minutes = np.floor((dayOffset-3600*hours)/60); 70 | seconds = dayOffset-3600*hours-60*minutes; 71 | 72 | tm_year = (year).astype(np.int) 73 | tm_mon = (month).astype(np.int) 74 | tm_mday = (np.floor(day)).astype(np.int) 75 | tm_hour = (hours).astype(np.int) 76 | tm_min = (minutes).astype(np.int) 77 | tm_sec = (np.floor(seconds)).astype(np.int) 78 | 79 | scet = np.zeros_like(jd) 80 | 81 | for i,(y,m,d,h,mi,s) in enumerate(zip(tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec)): 82 | scet[i] = timegm((y,m,d,h,mi,s)) + 4383*86400 83 | 84 | return scet 85 | 86 | 87 | def time2sample(freq, time): 88 | if freq == 30: 89 | return int((time - 1621174818.021514892578125) * 32.5079365079365) 90 | elif freq == 44: 91 | return int((time - 1621174818.012481689453125) * 46.5454545454545) 92 | elif freq == 70: 93 | return int((time - 1621174818.008087158203125) * 78.7692307692308) 94 | else: 95 | return None 96 | 97 | def ndsample2time(freq, sample): 98 | if freq == 30: 99 | time_flat = 1621174818.021514892578125 + (sample / 32.5079365079365) 100 | BREAK98 = 1629377124.0625305 101 | BREAK98LEN = 3.573974609375 102 | afterbreak, = np.where(time_flat >= BREAK98) 103 | correction = np.zeros_like(time_flat) 104 | correction[afterbreak] = BREAK98LEN 105 | time_corrected = time_flat + correction 106 | return time_corrected 107 | 108 | def sample2time(freq, sample): 109 | if freq == 30: 110 | return 1621174818.021514892578125 + (sample / 32.5079365079365) 111 | elif freq == 44: 112 | return 1621174818.012481689453125 + (sample / 46.5454545454545) 113 | elif freq == 70: 114 | return 1621174818.008087158203125 + (sample / 78.7692307692308) 115 | else: 116 | return None 117 | 118 | def timedelta2seconds(diff): 119 | return diff.days * 24 * 3600 + diff.seconds + diff.microseconds * 1e-3 120 | 121 | def obt2utc(obt): 122 | '''Convert OBT (s) to UTC''' 123 | return OBTSTARTDATE + datetime.timedelta(0,obt) 124 | 125 | def utc2obt(utc): 126 | '''Convert UTC (datetime object) to OBT (s)''' 127 | return timedelta2seconds(utc - OBTSTARTDATE) 128 | 129 | def approxod2utc(od): 130 | return LAUNCH + datetime.timedelta(od) 131 | 132 | def utc2approxod(utc): 133 | return timedelta2seconds(utc - LAUNCH) / SECONDSPERDAY 134 | 135 | def approxod2obt(od): 136 | return utc2obt(approxod2utc(od)) 137 | 138 | def obt2approxod(obt): 139 | return utc2approxod(obt2utc(obt)) 140 | 141 | 142 | def nps(s, Fs=1, nfft=None, minfreq=None): 143 | """Normalized power spectrum 144 | 145 | Parameters 146 | ---------- 147 | s : array 148 | signal timeline 149 | Fs : float 150 | sampling frequency 151 | nfft : int 152 | if set, NFFT of mlab.psd is not computed from minfreq 153 | minfreq : float 154 | target minimum frequency of the power spectrum, 155 | if None, all timeline is used 156 | 157 | Returns 158 | ------- 159 | freqs : array 160 | frequency array 161 | Pxx : power spectrum 162 | """ 163 | 164 | import matplotlib.pyplot as plt 165 | if nfft is None: 166 | if minfreq is None: 167 | nfft=len(s) 168 | nfft=2**(np.int(np.log2(nfft))) 169 | else: 170 | nfft=min(len(s),np.int(2.*Fs/minfreq)) 171 | nfft=2**(int(np.log2(nfft))) 172 | Pxx, freqs = plt.mlab.psd(s, NFFT=nfft, Fs = Fs) 173 | return freqs, Pxx 174 | 175 | def whitenoise(lenght): 176 | return np.random.standard_normal(size=lenght) 177 | 178 | def interp_floor(x, xp, fp): 179 | i_interp = np.interp(x, xp, np.arange(len(fp))) 180 | i_rounded = np.floor(i_interp).astype(np.int) 181 | return fp[i_rounded] 182 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | setup( 3 | name = "planck", 4 | version = "0.3", 5 | packages = ['planck'], 6 | 7 | # Project uses reStructuredText, so ensure that the docutils get 8 | # installed or upgraded on the target machine 9 | install_requires = ['docutils>=0.3'], 10 | 11 | package_data = { 12 | # If any package contains *.txt or *.rst files, include them: 13 | '': ['*.txt', '*.rst'], 14 | }, 15 | 16 | # metadata for upload to PyPI 17 | author = "Andrea Zonca", 18 | author_email = "code@andreazonca.com", 19 | description = "Python package for working with Planck data", 20 | license = "PSF", 21 | keywords = "Planck science data", 22 | url = "http://andreazonca.com/software/planck/", # project home page, if any 23 | 24 | # could also include long_description, download_url, classifiers, etc. 25 | ) 26 | --------------------------------------------------------------------------------