├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── conf.py ├── index.rst ├── make.bat └── tomography.rst ├── environment.yml ├── requirements.txt ├── setup.py └── tomography_tutorial ├── __init__.py ├── ancillary.py ├── functions.py ├── plotting.py └── tutorial.ipynb /LICENSE: -------------------------------------------------------------------------------- 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 | . -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include tomography_tutorial/tutorial.ipynb 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Documentation Status][1]][2] [![PyPI version][11]][12] 2 | 3 | # EO-College tomography tutorial 4 | 5 | This tutorial, developed by the [EO-College][3] learning initiative, 6 | explores Synthetic Aperture Radar (SAR) tomography 7 | with data from DLR's [F-SAR][4] system. 8 | It consists of a Python package, containing several functions for processing and displaying the data, 9 | a Jupyter notebook, a test data set, which can be downloaded [here][5], and a [video tutorial][13]. 10 | Please follow the steps below to get started. 11 | 12 | ## Installation 13 | 14 | The following subsections describe the installation process for different operating systems. 15 | Please mind that this tutorial depends on Python 3. 16 | 17 | #### Ubuntu 18 | 19 | First we want to install [GDAL][9] to read our data. For this we add the [UbuntuGIS][10] package 20 | repository so we can install a more recent version than that supplied by Ubuntu. 21 | After this we install GDAL together with its Python bindings: 22 | ```sh 23 | sudo add-apt-repository ppa:ubuntugis/ppa 24 | sudo apt-get update 25 | sudo apt-get install gdal-bin python3-gdal 26 | ``` 27 | 28 | Next we install Tkinter for graphical support: 29 | ```sh 30 | sudo apt-get install python3-tk 31 | ``` 32 | 33 | As a last step we install the tomography module including its direct Python package 34 | dependencies: 35 | 36 | ```sh 37 | sudo python3 -m pip install tomography_tutorial 38 | ``` 39 | 40 | #### Windows 41 | 42 | The easiest way to install Python and Jupyter on Windows is via [Anaconda][6]. 43 | Please make sure to install the Python 3 version. 44 | Once you have installed it, please add its installation directory to the PATH environment variable. 45 | See e.g. [here][7] for instructions. 46 | Now we can install GDAL via Anaconda's own command line installation program: 47 | ```sh 48 | conda install -c conda gdal 49 | ``` 50 | 51 | Finally we can install the tutorial package: 52 | ```sh 53 | python -m pip install tomography_tutorial 54 | ``` 55 | 56 | ## download of tutorial test data 57 | Prior to starting the tutorial you need to download and unpack the data found 58 | [here][5]. 59 | 60 | ## Starting the notebook 61 | 62 | Now that everything is installed you can start the notebook via the tutorial Python module. 63 | In the command prompt, start Python and execute the function [start][8]: 64 | ```Python 65 | from tomography_tutorial import start 66 | start('/your/custom/notebook.ipynb') 67 | ``` 68 | This will create a custom copy of the notebook if it does not yet exist and start it in the browser. 69 | If the directory in which the custom notebook is to be stored does not yet exist, it is created 70 | automatically. Please mind that under Windows paths need to be separated with `\\` or `/`, 71 | a single backslash will cause an error. 72 | You now have a custom version of the tutorial, 73 | which you can modify as you like and restart later via function `start`. 74 | If you want to restore the original notebook, which was delivered with the Python package, just delete 75 | your custom version and run function `start` again. 76 | 77 | ## API documentation 78 | 79 | The documentation of the package functionality which is used in the notebook can be found 80 | [here][2]. 81 | 82 | [1]: https://readthedocs.org/projects/eocollege-tomography/badge/?version=latest 83 | [2]: http://eocollege-tomography.readthedocs.io/en/latest/?badge=latest 84 | [3]: https://eo-college.org/landingpage/ 85 | [4]: https://www.dlr.de/hr/en/desktopdefault.aspx/tabid-2326/3776_read-5691 86 | [5]: https://cloud.uni-jena.de/s/62kB6qjZYiXKSQz/download 87 | [6]: https://conda.io/docs/user-guide/install/windows.html 88 | [7]: https://www.computerhope.com/issues/ch000549.htm 89 | [8]: https://eocollege-tomography.readthedocs.io/en/latest/tomography.html#tomography_tutorial.functions.start 90 | [9]: https://www.gdal.org/ 91 | [10]: https://wiki.ubuntu.com/UbuntuGIS 92 | [11]: https://badge.fury.io/py/tomography-tutorial.svg 93 | [12]: https://badge.fury.io/py/tomography-tutorial 94 | [13]: https://eo-college.org/resource/sar-tomography-tutorial/ 95 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = tomography 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | import os 10 | import sys 11 | import datetime 12 | 13 | # -- Path setup -------------------------------------------------------------- 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | # 19 | # sys.path.insert(0, os.path.abspath('.')) 20 | sys.path.insert(0, os.path.abspath('..') + os.sep) 21 | 22 | # -- Project information ----------------------------------------------------- 23 | 24 | project = 'tomography_tutorial' 25 | author = 'Nesrin Salepci, John Truckenbrodt, Robert Eckhardt' 26 | year = datetime.datetime.now().year 27 | copyright = '{}, {}'.format(year, author) 28 | 29 | # The short X.Y version 30 | version = '1.0' 31 | # The full version, including alpha/beta/rc tags 32 | release = '1.0' 33 | 34 | # -- General configuration --------------------------------------------------- 35 | autodoc_mock_imports = ['osgeo', 'numpy', 'scipy', 'matplotlib', 'mpl_toolkits', 'IPython', 'ipywidgets'] 36 | 37 | # If your documentation needs a minimal Sphinx version, state it here. 38 | needs_sphinx = '1.6' 39 | 40 | # Add any Sphinx extension module names here, as strings. They can be 41 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 42 | # ones. 43 | extensions = [ 44 | 'sphinx.ext.autodoc', 45 | 'sphinx.ext.doctest', 46 | 'sphinx.ext.coverage', 47 | 'sphinx.ext.imgmath', 48 | 'sphinx.ext.viewcode', 49 | 'sphinx.ext.intersphinx', 50 | 'sphinx.ext.napoleon', 51 | ] 52 | 53 | intersphinx_mapping = {'python': ('https://docs.python.org/3', None), 54 | 'matplotlib': ('https://matplotlib.org', None), 55 | 'numpy': ('https://docs.scipy.org/doc/numpy', None)} 56 | 57 | napoleon_google_docstring = False 58 | napoleon_numpy_docstring = True 59 | napoleon_include_init_with_doc = False 60 | napoleon_include_private_with_doc = False 61 | napoleon_include_special_with_doc = True 62 | napoleon_use_admonition_for_examples = False 63 | napoleon_use_admonition_for_notes = False 64 | napoleon_use_admonition_for_references = False 65 | napoleon_use_ivar = False 66 | napoleon_use_param = True 67 | napoleon_use_rtype = True 68 | 69 | # Add any paths that contain templates here, relative to this directory. 70 | templates_path = ['_templates'] 71 | 72 | # The suffix(es) of source filenames. 73 | # You can specify multiple suffix as a list of string: 74 | # 75 | # source_suffix = ['.rst', '.md'] 76 | source_suffix = '.rst' 77 | 78 | # The master toctree document. 79 | master_doc = 'index' 80 | 81 | # The language for content autogenerated by Sphinx. Refer to documentation 82 | # for a list of supported languages. 83 | # 84 | # This is also used if you do content translation via gettext catalogs. 85 | # Usually you set "language" from the command line for these cases. 86 | language = None 87 | 88 | # List of patterns, relative to source directory, that match files and 89 | # directories to ignore when looking for source files. 90 | # This pattern also affects html_static_path and html_extra_path . 91 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 92 | 93 | # The name of the Pygments (syntax highlighting) style to use. 94 | pygments_style = 'sphinx' 95 | 96 | 97 | # -- Options for HTML output ------------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | # 102 | html_theme = 'default' 103 | 104 | # Theme options are theme-specific and customize the look and feel of a theme 105 | # further. For a list of options available for each theme, see the 106 | # documentation. 107 | # 108 | # html_theme_options = {} 109 | 110 | # Add any paths that contain custom static files (such as style sheets) here, 111 | # relative to this directory. They are copied after the builtin static files, 112 | # so a file named "default.css" will overwrite the builtin "default.css". 113 | html_static_path = ['_static'] 114 | 115 | # Custom sidebar templates, must be a dictionary that maps document names 116 | # to template names. 117 | # 118 | # The default sidebars (for documents that don't match any pattern) are 119 | # defined by theme itself. Builtin themes are using these templates by 120 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 121 | # 'searchbox.html']``. 122 | # 123 | # html_sidebars = {} 124 | 125 | # If false, no index is generated. 126 | html_use_index = True 127 | 128 | # -- Options for HTMLHelp output --------------------------------------------- 129 | 130 | # Output file base name for HTML help builder. 131 | htmlhelp_basename = '{}doc'.format(project) 132 | 133 | 134 | # -- Options for LaTeX output ------------------------------------------------ 135 | 136 | latex_elements = { 137 | # The paper size ('letterpaper' or 'a4paper'). 138 | # 139 | # 'papersize': 'letterpaper', 140 | 141 | # The font size ('10pt', '11pt' or '12pt'). 142 | # 143 | # 'pointsize': '10pt', 144 | 145 | # Additional stuff for the LaTeX preamble. 146 | # 147 | # 'preamble': '', 148 | 149 | # Latex figure (float) alignment 150 | # 151 | # 'figure_align': 'htbp', 152 | } 153 | 154 | # Grouping the document tree into LaTeX files. List of tuples 155 | # (source start file, target name, title, 156 | # author, documentclass [howto, manual, or own class]). 157 | latex_documents = [ 158 | (master_doc, 159 | '{}.tex'.format(project), 160 | u'{} Documentation'.format(project), 161 | author, 'manual'), 162 | ] 163 | 164 | 165 | # -- Options for manual page output ------------------------------------------ 166 | 167 | # One entry per manual page. List of tuples 168 | # (source start file, name, description, authors, manual section). 169 | man_pages = [ 170 | (master_doc, project, u'{} Documentation'.format(project), 171 | [author], 1) 172 | ] 173 | 174 | 175 | # -- Options for Texinfo output ---------------------------------------------- 176 | 177 | # Grouping the document tree into Texinfo files. List of tuples 178 | # (source start file, target name, title, author, 179 | # dir menu entry, description, category) 180 | texinfo_documents = [ 181 | (master_doc, project, u'{} Documentation'.format(project), 182 | author, project, 'One line description of project.', 183 | 'Miscellaneous'), 184 | ] 185 | 186 | 187 | # -- Extension configuration ------------------------------------------------- 188 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. tomography documentation master file, created by 2 | sphinx-quickstart on Wed May 2 13:27:30 2018. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | EO-College tomography tutorial API documentation 7 | ================================================ 8 | 9 | .. toctree:: 10 | 11 | tomography 12 | 13 | * :ref:`genindex` 14 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | set SPHINXPROJ=tomography 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 20 | echo.installed, then set the SPHINXBUILD environment variable to point 21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 22 | echo.may add the Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /docs/tomography.rst: -------------------------------------------------------------------------------- 1 | main functions 2 | -------------- 3 | 4 | The core functions of the tomography package. 5 | 6 | .. automodule:: tomography_tutorial.functions 7 | :members: 8 | :undoc-members: 9 | :show-inheritance: 10 | 11 | ancillary functions 12 | ------------------- 13 | 14 | Additional general functions for the tomography package. 15 | 16 | .. automodule:: tomography_tutorial.ancillary 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | plotting 22 | -------- 23 | 24 | Plotting utilities for the Jupyter notebook. 25 | 26 | .. automodule:: tomography_tutorial.plotting 27 | :members: 28 | :undoc-members: 29 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | channels: 2 | - conda-forge 3 | - defaults 4 | dependencies: 5 | - gdal 6 | - matplotlib 7 | - scipy 8 | - jupyter 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | jupyter 3 | matplotlib 4 | scipy -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | from setuptools import setup, find_packages 4 | 5 | directory = os.path.abspath(os.path.dirname(__file__)) 6 | if sys.version_info >= (3, 0): 7 | with open(os.path.join(directory, 'README.md'), encoding='utf-8') as f: 8 | long_description = f.read() 9 | else: 10 | with open(os.path.join(directory, 'README.md')) as f: 11 | long_description = f.read() 12 | 13 | setup(name='tomography_tutorial', 14 | packages=find_packages(), 15 | include_package_data=True, 16 | version='1.0.1', 17 | description='A tutorial package for Synthetic Aperture Radar Tomography', 18 | classifiers=[ 19 | 'Programming Language :: Python', 20 | ], 21 | python_requires='>3.0.0', 22 | install_requires=['numpy', 23 | 'jupyter', 24 | 'matplotlib', 25 | 'scipy'], 26 | url='https://github.com/EO-College/tomography_tutorial', 27 | author='John Truckenbrodt', 28 | author_email='john.truckenbrodt@uni-jena.de', 29 | license='GPL-3', 30 | zip_safe=False, 31 | long_description=long_description, 32 | long_description_content_type='text/markdown') 33 | -------------------------------------------------------------------------------- /tomography_tutorial/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from .functions import \ 3 | start, \ 4 | read_data, \ 5 | topo_phase_removal, \ 6 | calculate_covariance_matrix, \ 7 | capon_beam_forming_inversion 8 | -------------------------------------------------------------------------------- /tomography_tutorial/ancillary.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import numpy as np 4 | 5 | from osgeo import gdal, gdal_array 6 | 7 | from scipy.ndimage.measurements import label 8 | from scipy.ndimage import generate_binary_structure, find_objects 9 | 10 | 11 | def listfiles(path, pattern): 12 | """ 13 | list files in a directory whose names match a regular expression 14 | 15 | Parameters 16 | ---------- 17 | path: str 18 | the directory to be searched 19 | pattern: str 20 | the regular expression search pattern 21 | Returns 22 | ------- 23 | list 24 | a list of absolute file names 25 | Example 26 | ------- 27 | >>> listfiles('/path/to/somedata', 'file[0-9].tif') 28 | ['/path/to/somedata/file1.tif', '/path/to/somedata/file2.tif', '/path/to/somedata/file3.tif'] 29 | """ 30 | return sorted([os.path.join(path, x) for x in os.listdir(path) if re.search(pattern, x)]) 31 | 32 | 33 | def normalize(slice): 34 | """ 35 | normalize a 1D array by its minimum and maximum values: 36 | 37 | .. math:: 38 | y = \\frac{x-min(x)}{max(x)-min(x)} 39 | 40 | Parameters 41 | ---------- 42 | slice: numpy.ndarray 43 | the 1d input array to be normalized 44 | 45 | Returns 46 | ------- 47 | numpy.ndarray 48 | the normalized array 49 | """ 50 | max = np.amax(slice) 51 | min = np.amin(slice) 52 | return np.divide((slice - min), (max - min)) 53 | 54 | 55 | def cbfi(slice, nTrack, height): 56 | """ 57 | computation of capon beam forming inversion for a single pixel. 58 | This function is used internally by the core function 59 | :func:`~tomography_tutorial.functions.capon_beam_forming_inversion`. 60 | 61 | Parameters 62 | ---------- 63 | slice: numpy.ndarray 64 | an array containing the covariance matrix and wave number for a single pixel 65 | nTrack: int 66 | the number of original SLC files 67 | height: int 68 | the maximum inversion height 69 | 70 | Returns 71 | ------- 72 | numpy.ndarray 73 | the tomographic result for one pixel 74 | """ 75 | kz = np.transpose([slice[(nTrack ** 2):]]) 76 | r0 = slice[0:(nTrack ** 2)].reshape((nTrack, nTrack)) 77 | 78 | z_vector = np.matrix(np.arange(-height, height + 1, 1)) 79 | 80 | # define the loading factor 81 | load_fac = (1 / 25.) * np.identity(nTrack) 82 | 83 | # define the steering matrix 84 | a_steer = np.exp(np.dot(complex(0, 1) * kz, z_vector)) 85 | 86 | # define the numerator of the filter habf 87 | hnum = np.dot(np.linalg.inv(r0 + load_fac), a_steer) 88 | 89 | # define the denominator of the filter habf 90 | hden0 = np.diag(np.dot(np.conjugate(np.transpose(a_steer)), hnum)) 91 | 92 | # replicate the diagonal by number of Tracks 93 | hden = np.array([hden0] * nTrack, dtype=np.complex64) 94 | 95 | h_abf = np.divide(hnum, hden) 96 | 97 | return np.diag(np.dot(np.dot(np.conjugate(np.transpose(h_abf)), r0), h_abf)) 98 | 99 | 100 | def lut_crop(lut_rg, lut_az, 101 | range_min=0, range_max=None, 102 | azimuth_min=0, azimuth_max=None): 103 | """ 104 | compute indices for subsetting the range and azimuth lookup tables (LUTs). 105 | The returned slices describe the minimum LUT subset, 106 | which contains all radar coordinates within the range-azimuth subset. 107 | 108 | Parameters 109 | ---------- 110 | lut_rg: numpy.ndarray 111 | the lookup table for range direction 112 | lut_az: numpy.ndarray 113 | the lookup table for azimuth direction 114 | range_min: int 115 | first range pixel 116 | range_max: int 117 | last range pixel 118 | azimuth_min: int 119 | first azimuth pixel 120 | azimuth_max: int 121 | last azimuth pixel 122 | 123 | Returns 124 | ------- 125 | tuple of slices 126 | the pixel indices for subsetting: (ymin:ymax, xmin:xmax) 127 | """ 128 | 129 | def get_indices(mask): 130 | """ 131 | helper function to get the array slices containing all rows and columns 132 | where a binary mask is one/True 133 | Parameters 134 | ---------- 135 | mask: numpy.ndarray 136 | the mask to be subsetted 137 | 138 | Returns 139 | ------- 140 | tuple of slices 141 | two slices for subsetting numpy arrays in the row (azimuth) and column (range) dimension 142 | """ 143 | # get the azimuth array indices for subsetting the LUT files 144 | az_index = np.where(np.any(mask, axis=1)) 145 | azmin = np.min(az_index) 146 | azmax = np.max(az_index) + 1 147 | 148 | # get the range array indices for subsetting the LUT files 149 | rg_index = np.where(np.any(mask, axis=0)) 150 | rgmin = np.min(rg_index) 151 | rgmax = np.max(rg_index) + 1 152 | return slice(azmin, azmax), slice(rgmin, rgmax) 153 | 154 | # create a LUT mask containing all radar coordinates of the defined subset 155 | lut_mask = (float(range_min) <= lut_rg) & \ 156 | (lut_rg <= float(range_max)) & \ 157 | (float(azimuth_min) <= lut_az) & \ 158 | (lut_az <= float(azimuth_max)) 159 | 160 | # subset the original mask to the computed subset coordinates 161 | indices = get_indices(lut_mask) 162 | lut_mask_sub = lut_mask[indices] 163 | 164 | # refine the mask using an image segmentation approach 165 | # create a new mask by selecting only the largest segment of the original mask 166 | s = generate_binary_structure(2, 2) 167 | labeled_array, num_features = label(lut_mask_sub, structure=s) 168 | obj_slices = find_objects(labeled_array) 169 | # identify the largest object 170 | obj_sizes = [(x.stop - x.start) * (y.stop - y.start) for x, y in obj_slices] 171 | obj_max = obj_sizes.index(max(obj_sizes)) 172 | 173 | # create a new mask subset containing only the largest object 174 | lut_mask_sub = labeled_array == (obj_max + 1) 175 | 176 | # create a new mask with original extent and place the values of the mask subset 177 | lut_mask = np.zeros(lut_mask.shape) 178 | lut_mask[indices] = lut_mask_sub 179 | 180 | # return the position indices of the mask object on the main mask 181 | return get_indices(lut_mask) 182 | 183 | 184 | def geowrite(data, outname, reference, indices, nodata=-99): 185 | """ 186 | write an array to a file using an already geocoded file as reference. 187 | The output format is either GeoTiff (for 2D arrays) or ENVI (for 3D arrays). 188 | 189 | Parameters 190 | ---------- 191 | data: numpy.ndarray 192 | the array to write to the file; must be either 2D or 3D 193 | outname: str 194 | the file name 195 | reference: `gdal.Dataset `_ 196 | the geocoded reference dataset 197 | indices: tuple of slices 198 | the slices which define the subset of data in reference, 199 | i.e. where is the data located within the reference pixel dimensions; 200 | see :func:`lut_crop` 201 | nodata: int 202 | the nodata value to write to the file 203 | 204 | Returns 205 | ------- 206 | 207 | """ 208 | 209 | geo_keys = ['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'] 210 | geo = dict(zip(geo_keys, reference.GetGeoTransform())) 211 | 212 | row_f, row_l = indices[0].start, indices[0].stop 213 | col_f, col_l = indices[1].start, indices[1].stop 214 | 215 | if data.ndim == 2: 216 | nrow, ncol = data.shape 217 | nbands = 1 218 | elif data.ndim == 3: 219 | nrow, ncol, nbands = data.shape 220 | else: 221 | raise RuntimeError("parameter 'data' must be an array with either two or three dimensions") 222 | 223 | if (row_l - row_f, col_l - col_f) != (nrow, ncol): 224 | raise IndexError('mismatch of data dimensions and subset indices') 225 | 226 | geo['xmin'] += col_f * geo['xres'] 227 | geo['ymax'] -= row_f * abs(geo['yres']) 228 | geotransform = [geo[x] for x in geo_keys] 229 | 230 | driver = gdal.GetDriverByName('GTiff' if nbands == 1 else 'ENVI') 231 | dtype = gdal_array.NumericTypeCodeToGDALTypeCode(data.dtype) 232 | outDataset = driver.Create(outname, ncol, nrow, nbands, dtype) 233 | driver = None 234 | outDataset.SetMetadata(reference.GetMetadata()) 235 | outDataset.SetGeoTransform(geotransform) 236 | outDataset.SetProjection(reference.GetProjection()) 237 | 238 | if nbands == 1: 239 | outband = outDataset.GetRasterBand(1) 240 | outband.SetNoDataValue(nodata) 241 | outband.WriteArray(data) 242 | outband.FlushCache() 243 | else: 244 | for i in range(nbands): 245 | outband = outDataset.GetRasterBand(i+1) 246 | outband.SetNoDataValue(nodata) 247 | outband.WriteArray(data[:, :, i]) 248 | outband.FlushCache() 249 | 250 | ref_data = None 251 | outband = None 252 | outDataset = None 253 | 254 | 255 | def geocode(data, lut_rg_name, lut_az_name, outname=None, 256 | range_min=0, range_max=None, azimuth_min=0, azimuth_max=None): 257 | """ 258 | Geocode a radar image using lookup tables. 259 | The LUTs are expected to be georeferenced and contain range and azimuth radar coordinates 260 | for a specific image data set which is linked to these LUTs. 261 | If parameter `data` is a subset of this data set, 262 | the pixel coordinates of this subset need to be defined. 263 | 264 | Parameters 265 | ---------- 266 | data: numpy.ndarray 267 | the image data in radar coordinates 268 | lut_rg_name: str 269 | the name of the range coordinates lookup table file 270 | lut_az_name: str 271 | the name of the azimuth coordinates lookup table file 272 | outname: str or None 273 | the name of the file to write; 274 | if None, the geocoded array is returned and no file is written. 275 | See function :func:`geowrite` for details on how the file is written. 276 | range_min: int 277 | the minimum range coordinate 278 | range_max: int 279 | the maximum range coordinate 280 | azimuth_min: int 281 | the minimum azimuth coordinate 282 | azimuth_max: int 283 | the maximum azimuth coordinate 284 | 285 | Returns 286 | ------- 287 | 288 | Example 289 | ------- 290 | >>> from osgeo import gdal 291 | >>> from tomography_tutorial.ancillary import geocode 292 | >>> image_name = 'path/to/somedata/image.tif' 293 | >>> lut_rg_name = 'path/to/somedata/lut_rg.tif' 294 | >>> lut_az_name = 'path/to/somedata/lut_az.tif' 295 | >>> outname = 'path/to/somedata/image_sub_geo.tif' 296 | >>> image_ras = gdal.Open(image_name) 297 | >>> image_mat = image_ras.ReadAsArray() 298 | >>> image_ras = None 299 | >>> image_mat_sub = image_mat[0:100, 200:400] 300 | >>> geocode(image_mat_sub, outname, lut_rg_name, lut_az_name, \ 301 | range_min=200, range_max=400, azimuth_min=0, azimuth_max=100) 302 | """ 303 | if data.ndim == 2: 304 | nazimuth, nrange = data.shape 305 | nbands = 1 306 | elif data.ndim == 3: 307 | nazimuth, nrange, nbands = data.shape 308 | else: 309 | raise RuntimeError("parameter 'data' must be an array with either two or three dimensions") 310 | 311 | if not range_max: 312 | range_max = nrange 313 | 314 | if not azimuth_max: 315 | azimuth_max = nazimuth 316 | 317 | imgfile = gdal.Open(lut_rg_name) 318 | lut_rg = imgfile.ReadAsArray() 319 | 320 | imgfile = gdal.Open(lut_az_name) 321 | lut_az = imgfile.ReadAsArray() 322 | 323 | # compute indices for subsetting the LUTs to only contain the subset of selected radar coordinates 324 | indices = lut_crop(lut_rg, lut_az, range_min, range_max, azimuth_min, azimuth_max) 325 | 326 | # crop the LUTs to the selected subset 327 | lut_rg_sub = lut_rg[indices] 328 | lut_az_sub = lut_az[indices] 329 | 330 | # recompute the LUT radar coordinates 331 | lut_rg_sub = lut_rg_sub - range_min 332 | lut_az_sub = lut_az_sub - azimuth_min 333 | 334 | ######################################################################################################## 335 | # actual geocoding 336 | 337 | # create a mask containing only radar coordinates of the selected subset 338 | mask = ((lut_rg_sub < 0) | (lut_rg_sub > nrange)) | ((lut_az_sub < 0) | (lut_az_sub > nazimuth)) 339 | 340 | # combine the two LUTs by computing indices for a 1-D row-major flattened array 341 | lut_combi = lut_az_sub.astype(int) * nrange + lut_rg_sub.astype(int) 342 | 343 | # set all indices out of bounds to zero 344 | lut_combi[(lut_combi < 0) | ((nrange * nazimuth) < lut_combi)] = 0 345 | 346 | if nbands == 1: 347 | # create the geo-coded array by flattening the radar image to 1D and indexing it by the combined LUT 348 | # the resulting array has the same dimensions as the LUT, which is still 2D 349 | mat_geo = data.flatten()[lut_combi] 350 | 351 | # mask out all areas outside the selected subset 352 | mat_geo[mask] = np.nan 353 | else: 354 | mat_geo = np.empty(lut_combi.shape + (nbands,), data.dtype) 355 | for i in range(nbands): 356 | sub = data[:, :, i].flatten()[lut_combi] 357 | sub[mask] = np.nan 358 | mat_geo[:, :, i] = sub 359 | ######################################################################################################## 360 | # write the result to disk 361 | if outname: 362 | geowrite(mat_geo, outname, imgfile, indices) 363 | imgfile = None 364 | if not outname: 365 | return mat_geo 366 | -------------------------------------------------------------------------------- /tomography_tutorial/functions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | import shutil 4 | import numpy as np 5 | from osgeo import gdal 6 | from scipy import ndimage 7 | import subprocess as sp 8 | from .ancillary import cbfi 9 | 10 | 11 | def start(notebook): 12 | """ 13 | Create a custom copy of the jupyter notebook with a name defined buy the user and start it. 14 | The notebook is only copied from the package if it does not yet exist. 15 | Jupyter notebook files have the extension '.ipynb'. 16 | If the defined notebook does not contain this extension it is appended automatically. 17 | 18 | Parameters 19 | ---------- 20 | directory: str 21 | the name of the custom notebook 22 | 23 | Returns 24 | ------- 25 | 26 | """ 27 | source_basename = 'tutorial.ipynb' 28 | target_dir = os.path.dirname(notebook) 29 | if not os.path.isdir(target_dir): 30 | os.makedirs(target_dir) 31 | if not notebook.endswith('.ipynb'): 32 | notebook += '.ipynb' 33 | if not os.path.isfile(notebook): 34 | source = os.path.join(os.path.dirname(os.path.realpath(__file__)), source_basename) 35 | # copy the tutorial notebook from the directory of the installed package to the user directory 36 | shutil.copyfile(source, notebook) 37 | sp.check_call(['jupyter', 'notebook', notebook], cwd=target_dir) 38 | 39 | 40 | def read_data(input, outname, overwrite=False): 41 | """ 42 | read the raw input data into a numpy array and write the results 43 | 44 | Parameters 45 | ---------- 46 | input: str or list 47 | a single image file name or a list of multiple files 48 | outname: str 49 | the name of the file to be written. 50 | overwrite: bool 51 | overwrite an existing file? Otherwise it is read from file and returned 52 | 53 | Returns 54 | ------- 55 | numpy.ndarray 56 | an array in 2D (one file) or 3D (multiple files) 57 | """ 58 | 59 | if overwrite or not os.path.isfile(outname): 60 | if len(input) == 0: 61 | raise RuntimeError('img_list is empty') 62 | 63 | imgfile = gdal.Open(input[0]) 64 | rows = imgfile.RasterYSize 65 | cols = imgfile.RasterXSize 66 | dtype = gdal.GetDataTypeName(imgfile.GetRasterBand(1).DataType) 67 | imgfile = None 68 | 69 | if dtype == 'CFloat32': 70 | offset = 0 71 | elif dtype == 'Float32': 72 | offset = 1 73 | else: 74 | raise RuntimeError('data type must be either "CFloat32" or "Float32"') 75 | 76 | img_stack = np.empty((rows, cols, len(input) + offset), np.complex64) 77 | for ii, img_path in enumerate(input): 78 | # Read the image file into the array 79 | imgfile = gdal.Open(img_path) 80 | img_stack[:, :, ii + offset] = imgfile.ReadAsArray() 81 | imgfile = None 82 | 83 | # save the variable 84 | with open(outname, 'wb') as f: 85 | pickle.dump(img_stack, f, 2) 86 | else: 87 | with open(outname, 'rb') as f: 88 | img_stack = pickle.load(f) 89 | return img_stack 90 | 91 | 92 | def topo_phase_removal(img_stack, dem_stack, outname, overwrite=False): 93 | """ 94 | Removal of Topographical Phase. 95 | If the target file already exists and ``overwrite=False`` this function acts as a simple file reader. 96 | 97 | Parameters 98 | ---------- 99 | img_stack: numpy.ndarray 100 | the SLC image stack 101 | dem_stack: numpy.ndarray 102 | the image stack containing flat earth and topographic phase 103 | outname: str 104 | the name of the file to be written 105 | overwrite: bool 106 | overwrite an existing file? Otherwise it is read from file and returned 107 | 108 | Returns 109 | ------- 110 | numpy.ndarray 111 | the normalized SLC stack 112 | """ 113 | if overwrite or not os.path.isfile(outname): 114 | 115 | normalized_stack = img_stack * np.exp(complex(0, 1) * dem_stack, dtype=np.complex64) 116 | 117 | # save the variable 118 | with open(outname, 'wb') as f: 119 | pickle.dump(normalized_stack, f, 2) 120 | else: 121 | with open(outname, 'rb') as f: 122 | normalized_stack = pickle.load(f) 123 | return normalized_stack 124 | 125 | 126 | def calculate_covariance_matrix(img_stack, outname, kernelsize=10, overwrite=False): 127 | """ 128 | compute the covariance matrix. 129 | If the target file already exists and ``overwrite=False`` this function acts as a simple file reader. 130 | 131 | Parameters 132 | ---------- 133 | img_stack: numpy.ndarray 134 | the normalized SLC image stack 135 | outname: str 136 | the name of the file to be written 137 | kernelsize: int 138 | the boxcar smoothing dimension 139 | overwrite: bool 140 | overwrite an existing file? Otherwise it is read from file and returned 141 | 142 | Returns 143 | ------- 144 | numpy.ndarray 145 | the covariance matrix 146 | """ 147 | 148 | if overwrite or not os.path.isfile(outname): 149 | rows, cols, nTrack = img_stack.shape 150 | 151 | kernel = np.ones((kernelsize, kernelsize)) 152 | weight = kernel / np.sum(kernel) 153 | 154 | cov_matrix = np.empty((rows, cols, nTrack, nTrack), np.complex64) 155 | smooth = np.empty((rows, cols, nTrack), np.float32) 156 | 157 | for i in range(0, nTrack): 158 | mm = np.absolute(img_stack[:, :, i]) ** 2 159 | smooth[:, :, i] = ndimage.convolve(mm, weight, mode='reflect') 160 | 161 | for i in range(0, nTrack): 162 | for j in range(0, nTrack): 163 | # multiply S1 and complex conjugate of S2 164 | ms = np.multiply(img_stack[:, :, i], np.conjugate(img_stack[:, :, j])) 165 | 166 | ms_real_smooth = ndimage.convolve(ms.real, weight, mode='reflect') 167 | ms_imag_smooth = complex(0, 1) * ndimage.convolve(ms.imag, weight, mode='reflect') 168 | ms_smooth = ms_real_smooth + ms_imag_smooth 169 | 170 | cov_matrix[:, :, i, j] = ms_smooth / (smooth[:, :, i] * smooth[:, :, j]) ** 0.5 171 | 172 | # save the variable 173 | with open(outname, 'wb') as f: 174 | pickle.dump(cov_matrix, f, 2) 175 | else: 176 | with open(outname, 'rb') as f: 177 | cov_matrix = pickle.load(f) 178 | return cov_matrix 179 | 180 | 181 | def capon_beam_forming_inversion(covmatrix, kz_array, outname, height=70, overwrite=False): 182 | """ 183 | perform the capon beam forming inversion to create the final tomographic result. 184 | If the target file already exists and ``overwrite=False`` this function acts as a simple file reader. 185 | 186 | Parameters 187 | ---------- 188 | covmatrix: numpy.ndarray 189 | the covariance matrix 190 | kz_array: numpy.ndarray 191 | the wave number stack 192 | outname: str 193 | the name of the file to be written 194 | height: int 195 | the maximum inversion height 196 | overwrite: bool 197 | overwrite an existing file? Otherwise it is read from file and returned 198 | 199 | Returns 200 | ------- 201 | numpy.ndarray 202 | the tomographic array 203 | """ 204 | if overwrite or not os.path.isfile(outname): 205 | 206 | rows, cols, nTrack = covmatrix.shape[0:3] 207 | 208 | # reshape and stack the input arrays for easier vectorization 209 | stack = np.empty((rows, cols, nTrack + nTrack ** 2), np.complex64) 210 | stack[:, :, 0:(nTrack ** 2)] = covmatrix.reshape((rows, cols, nTrack ** 2)) 211 | stack[:, :, (nTrack ** 2):] = kz_array 212 | 213 | # perform the actual computations 214 | capon_bf = np.apply_along_axis(cbfi, axis=2, arr=stack, nTrack=nTrack, height=height) 215 | 216 | capon_bf = np.real(capon_bf).astype(np.float32) 217 | with open(outname, 'wb') as f: 218 | pickle.dump(capon_bf, f, 2) 219 | else: 220 | with open(outname, 'rb') as f: 221 | capon_bf = pickle.load(f) 222 | return capon_bf 223 | -------------------------------------------------------------------------------- /tomography_tutorial/plotting.py: -------------------------------------------------------------------------------- 1 | import os 2 | from osgeo import gdal, osr 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | from IPython.display import display 6 | from ipywidgets import IntSlider, IntRangeSlider, Checkbox, Button, Layout, HBox, VBox, interactive_output 7 | from mpl_toolkits.axes_grid1 import make_axes_locatable 8 | 9 | 10 | class DataViewer(object): 11 | """ 12 | functionality for displaying the input data (SLC, topographic phase and wave number) 13 | 14 | Parameters 15 | ---------- 16 | slc_list: list of str 17 | the names of the SLC input files 18 | phase_list: list of str 19 | the names of the topographic phase input files 20 | kz_list: list of str 21 | the names of the Kappa-Zeta wave number input files 22 | slc_stack: numpy.ndarray 23 | the SLC images 24 | phase_stack: numpy.ndarray 25 | the topographic phase images 26 | kz_stack: numpy.ndarray 27 | the wave number images 28 | """ 29 | 30 | def __init__(self, slc_list, phase_list, kz_list, slc_stack, phase_stack, kz_stack): 31 | self.slc_list = slc_list 32 | self.phase_list = phase_list 33 | self.kz_list = kz_list 34 | 35 | self.slc_stack = slc_stack 36 | self.phase_stack = phase_stack 37 | self.kz_stack = kz_stack 38 | 39 | # define some options for display of the widget box 40 | self.layout = Layout( 41 | display='flex', 42 | flex_flow='row', 43 | border='solid 2px', 44 | align_items='stretch', 45 | width='94.5%' 46 | ) 47 | 48 | # define a slider for changing a plotted image 49 | self.slider = IntSlider(min=1, max=len(self.slc_list) - 1, step=1, continuous_update=False, 50 | description='image number', 51 | style={'description_width': 'initial'}, 52 | layout=self.layout) 53 | 54 | display(self.slider) 55 | 56 | self.fig = plt.figure(num='visualization of input data') 57 | # display of SLC amplitude 58 | self.ax1 = self.fig.add_subplot(131) 59 | # display of topographical phase 60 | self.ax2 = self.fig.add_subplot(132) 61 | # display of wave number 62 | self.ax3 = self.fig.add_subplot(133) 63 | 64 | self.ax1.set_xlabel('range', fontsize=12) 65 | self.ax1.set_ylabel('azimuth', fontsize=12) 66 | 67 | # format the cursor value displays 68 | self.ax1.format_coord = lambda x, y: 'range={0}, azimuth={1}, amplitude='.format(int(x), int(y)) 69 | self.ax2.format_coord = lambda x, y: 'range={0}, azimuth={1}, phase='.format(int(x), int(y)) 70 | self.ax3.format_coord = lambda x, y: 'range={0}, azimuth={1}, wave number='.format(int(x), int(y)) 71 | 72 | # enable interaction with the slider 73 | out = interactive_output(self.__onslide, {'h': self.slider}) 74 | 75 | plt.tight_layout() 76 | 77 | def __onslide(self, h): 78 | """ 79 | a function to respond to slider value changes 80 | 81 | Parameters 82 | ---------- 83 | h: int 84 | the slider value 85 | 86 | Returns 87 | ------- 88 | """ 89 | slc_name = os.path.basename(self.slc_list[h]) 90 | phase_name = os.path.basename(self.phase_list[h - 1]) 91 | kz_name = os.path.basename(self.kz_list[h - 1]) 92 | self.ax1.set_title('SLC intensity: {}'.format(slc_name), fontsize=12) 93 | self.ax2.set_title('phase: {}'.format(phase_name), fontsize=12) 94 | self.ax3.set_title('wavenumber: {}'.format(kz_name), fontsize=12) 95 | # logarithmic scaling of SLC amplitude 96 | amp_log = 10 * np.log10(np.absolute(self.slc_stack[:, :, h])) 97 | # computation of image percentiles for linear image stretching 98 | p02, p98 = np.percentile(amp_log, (2, 98)) 99 | self.ax1.imshow(amp_log, cmap='gray', vmin=p02, vmax=p98) 100 | self.ax2.imshow(np.absolute(self.phase_stack[:, :, h])) 101 | self.ax3.imshow(np.absolute(self.kz_stack[:, :, h])) 102 | self._set_colorbar(self.ax1, 'amplitude [$dB$]') 103 | self._set_colorbar(self.ax2, 'phase [$rad$]') 104 | self._set_colorbar(self.ax3, 'wave number [$m\cdot rad^{-1}$]') 105 | 106 | def _set_colorbar(self, axis, label): 107 | if len(axis.images) > 1: 108 | axis.images[0].colorbar.remove() 109 | del axis.images[0] 110 | 111 | divider = make_axes_locatable(axis) 112 | cax = divider.append_axes('right', size='5%', pad=0.05) 113 | 114 | cbar = self.fig.colorbar(axis.images[0], cax=cax) 115 | cbar.ax.set_ylabel(label, fontsize=12) 116 | 117 | 118 | class Tomographyplot(object): 119 | """ 120 | functionality for creating the main tomography_tutorial analysis plot 121 | 122 | Parameters 123 | ---------- 124 | capon_bf_abs: numpy.ndarray 125 | the absolute result of the capon beam forming inversion 126 | caponnorm: numpy.ndarray 127 | the normalized version of `capon_bf_abs`; 128 | see function :func:`~tomography_tutorial.ancillary.normalize`. 129 | """ 130 | 131 | def __init__(self, capon_bf_abs, caponnorm): 132 | if not caponnorm.shape == capon_bf_abs.shape: 133 | raise RuntimeError('mismatch of input arrays') 134 | 135 | self.height = capon_bf_abs.shape[2] // 2 136 | self.capon_bf_abs = capon_bf_abs 137 | self.caponnorm = caponnorm 138 | ############################################################################################# 139 | # widget box setup 140 | 141 | # define a slider for changing the horizontal slice image 142 | self.slider = IntSlider(min=-self.height, 143 | max=self.height, 144 | step=1, 145 | continuous_update=False, 146 | description='inversion height', 147 | style={'description_width': '140px'}, 148 | layout={'width': '400px'}) 149 | 150 | self.rangeslider = IntRangeSlider(value=[-self.height, self.height], 151 | min=-self.height, 152 | max=self.height, 153 | step=1, 154 | continuous_update=False, 155 | description='inversion height range', 156 | style={'description_width': '140px'}, 157 | layout={'width': '400px'}) 158 | 159 | # an internal variable to keep track of the set inversion height range 160 | self.heightrange = (-self.height, self.height) 161 | 162 | # a simple checkbox to enable/disable stacking of vertical profiles into one plot 163 | self.checkbox = Checkbox(value=True, description='stack vertical profiles', indent=False) 164 | 165 | # a button to clear the vertical profile plot 166 | self.clearbutton = Button(description='clear vertical plot') 167 | self.clearbutton.on_click(lambda x: self.__init_vertical_plot()) 168 | 169 | layout = Layout( 170 | justify_content='space-around', 171 | border='solid 2px', 172 | width='88%' 173 | ) 174 | 175 | form = HBox(children=[VBox([self.slider, self.rangeslider]), 176 | VBox([self.checkbox, self.clearbutton])], 177 | layout=layout) 178 | 179 | display(form) 180 | ############################################################################################# 181 | # main plot setup 182 | 183 | # set up the subplot layout 184 | self.fig = plt.figure() 185 | # the horizontal slice plot 186 | self.ax1 = self.fig.add_subplot(221) 187 | # the vertical profile plot 188 | self.ax2 = self.fig.add_subplot(222) 189 | # the range slice plot 190 | self.ax3 = self.fig.add_subplot(413) 191 | # the azimuth slice plot 192 | self.ax4 = self.fig.add_subplot(414) 193 | plt.subplots_adjust(left=0.1, right=0.2, top=0.3, bottom=0.2) 194 | 195 | # set up the plots for range and azimuth slices 196 | self.ax3.set_xlim(0, capon_bf_abs.shape[1]) 197 | self.ax4.set_xlim(0, capon_bf_abs.shape[0]) 198 | self.ax3.set_ylim(0, self.height * 2) 199 | self.ax4.set_ylim(0, self.height * 2) 200 | 201 | # set up the vertical profile plot 202 | self.__init_vertical_plot() 203 | 204 | # add a cross-hair to the horizontal slice plot 205 | self.lhor = self.ax1.axhline(0, linewidth=1, color='r') 206 | self.lver = self.ax1.axvline(0, linewidth=1, color='r') 207 | 208 | # make the figure respond to mouse clicks by executing method __onclick 209 | self.cid1 = self.fig.canvas.mpl_connect('button_press_event', self.__onclick) 210 | 211 | # enable interaction with the sliders 212 | out1 = interactive_output(self.__onslide, {'h': self.slider}) 213 | out2 = interactive_output(self.__onslide_range, {'h': self.rangeslider}) 214 | ############################################################################################# 215 | # general formatting 216 | 217 | # format the cursor value displays 218 | self.ax1.format_coord = lambda x, y: \ 219 | 'range={0}, azimuth={1}, reflectivity='.format(int(x), int(y)) 220 | self.ax2.format_coord = lambda x, y: \ 221 | 'reflectivity={0:.3f}, height={1}'.format(x, int(y)) 222 | self.ax3.format_coord = lambda x, y: \ 223 | 'range={0}, height={1}, reflectivity='.format(int(x), int(y - self.height)) 224 | self.ax4.format_coord = lambda x, y: \ 225 | 'range={0}, height={1}, reflectivity='.format(int(x), int(y - self.height)) 226 | 227 | # arrange the subplots to make best use of space 228 | plt.tight_layout(pad=1.0, w_pad=0.1, h_pad=0.1) 229 | ############################################################################################# 230 | 231 | def __reset_crosshair(self, range, azimuth): 232 | """ 233 | redraw the cross-hair on the horizontal slice plot 234 | 235 | Parameters 236 | ---------- 237 | range: int 238 | the range image coordinate 239 | azimuth: int 240 | the azimuth image coordinate 241 | 242 | Returns 243 | ------- 244 | """ 245 | self.lhor.set_ydata(azimuth) 246 | self.lver.set_xdata(range) 247 | plt.draw() 248 | 249 | def __init_vertical_plot(self): 250 | """ 251 | set up the vertical profile plot 252 | 253 | Returns 254 | ------- 255 | """ 256 | # clear the plot if lines have already been drawn on it 257 | if len(self.ax2.lines) > 0: 258 | self.ax2.cla() 259 | # set up the vertical profile plot 260 | self.ax2.set_ylabel('height [m]', fontsize=12) 261 | self.ax2.set_xlabel('reflectivity', fontsize=12) 262 | self.ax2.set_title('vertical point profiles', fontsize=12) 263 | self.ax2.set_ylim(self.heightrange[0], self.heightrange[1]) 264 | 265 | def __rename_sliceplot_ticklabels(self): 266 | """ 267 | rename the ticks of the slice plots from pixel coordinates (0:nbands) to 268 | inversion height range (-height:height) 269 | 270 | Returns 271 | ------- 272 | 273 | """ 274 | ticks = self.ax3.get_yticks() 275 | labels_new = [str(int(x - self.height)) for x in ticks] 276 | self.ax3.set_yticklabels(labels_new) 277 | self.ax4.set_yticklabels(labels_new) 278 | 279 | def __onslide(self, h): 280 | """ 281 | a function to respond to slider value changes by redrawing the horizontal slice plot 282 | 283 | Parameters 284 | ---------- 285 | h: int 286 | the slider value 287 | Returns 288 | ------- 289 | """ 290 | p1 = self.ax1.imshow(self.caponnorm[:, :, self.height - h], origin='upper', cmap='jet') 291 | self.ax1.set_xlabel('range', fontsize=12) 292 | self.ax1.set_ylabel('azimuth', fontsize=12) 293 | self.ax1.set_title('horizontal slice at height {} m'.format(h), fontsize=12) 294 | # remove the previous plot and its color bar 295 | if len(self.ax1.images) > 1: 296 | self.ax1.images[0].colorbar.remove() 297 | del self.ax1.images[0] 298 | cbar = self.fig.colorbar(p1, ax=self.ax1) 299 | cbar.ax.set_ylabel('reflectivity', fontsize=12) 300 | plt.show() 301 | 302 | def __onslide_range(self, h): 303 | """ 304 | respond to changes on the range slider. 305 | This changes the displayed y-axis range of the vertical profile and 306 | slice plots and renames the tick labels 307 | Parameters 308 | ---------- 309 | h 310 | 311 | Returns 312 | ------- 313 | 314 | """ 315 | self.heightrange = h 316 | self.ax2.set_ylim(self.heightrange[0], self.heightrange[1]) 317 | self.ax3.set_ylim(self.heightrange[0] + self.height, self.heightrange[1] + self.height) 318 | self.ax4.set_ylim(self.heightrange[0] + self.height, self.heightrange[1] + self.height) 319 | self.__rename_sliceplot_ticklabels() 320 | 321 | def __onclick(self, event): 322 | """ 323 | respond to mouse clicks in the plot. 324 | This function responds to clicks on the first (horizontal slice) plot and 325 | updates the vertical profile and slice plots 326 | 327 | Parameters 328 | ---------- 329 | event: matplotlib.backend_bases.MouseEvent 330 | the click event object containing image coordinates 331 | 332 | """ 333 | # only do something if the first plot has been clicked on 334 | if event.inaxes == self.ax1: 335 | 336 | # retrieve the click coordinates 337 | rg = int(event.xdata) 338 | az = int(event.ydata) 339 | 340 | # redraw the cross-hair 341 | self.__reset_crosshair(rg, az) 342 | 343 | subset_vertical = self.capon_bf_abs[az, rg, :] 344 | subset_range = self.caponnorm[az, :, :] 345 | subset_azimuth = self.caponnorm[:, rg, :] 346 | 347 | # redraw/clear the vertical profile plot in case stacking is disabled 348 | if not self.checkbox.value: 349 | self.__init_vertical_plot() 350 | 351 | # plot the vertical profile 352 | label = 'rg: {0:03}; az: {1:03}'.format(rg, az) 353 | self.ax2.plot(np.flipud(subset_vertical), range(-self.height, self.height + 1), label=label) 354 | self.ax2_legend = self.ax2.legend(loc=0, prop={'size': 7}, markerscale=1) 355 | 356 | # plot the range slice 357 | self.ax3.imshow(np.rot90(subset_range, 1), origin='lower', cmap='jet', aspect='auto') 358 | self.ax3.set_title('range slice at azimuth line {}'.format(az), fontsize=12) 359 | 360 | # plot the azimuth slice 361 | self.ax4.imshow(np.rot90(subset_azimuth, 1), origin='lower', cmap='jet', aspect='auto') 362 | self.ax4.set_title('azimuth slice at range line {}'.format(rg), fontsize=12) 363 | 364 | self.__rename_sliceplot_ticklabels() 365 | 366 | 367 | class GeoViewer(object): 368 | """ 369 | plotting utility for displaying a geocoded image stack file. 370 | 371 | On moving the slider, the band at the slider position is read from the file and displayed. 372 | 373 | Parameters 374 | ---------- 375 | filename: str 376 | the name of the file to display 377 | cmap: str 378 | the color map for displaying the image. See :func:`matplotlib.pyplot.imshow`. 379 | band_indices: list 380 | a list of indices for renaming the individual bands in `filename` such that one can 381 | scroll trough the range of inversion heights, e.g. -70:70, instead of the raw band 382 | indices, e.g. 1:140. 383 | The number of unique elements must of same length as the number of bands in `filename`. 384 | """ 385 | 386 | def __init__(self, filename, cmap='jet', band_indices=None): 387 | self.filename = filename 388 | ras = gdal.Open(filename) 389 | self.rows = ras.RasterYSize 390 | self.cols = ras.RasterXSize 391 | self.bands = ras.RasterCount 392 | geo = ras.GetGeoTransform() 393 | srs = osr.SpatialReference(wkt=ras.GetProjection()) 394 | ras = None 395 | srs.AutoIdentifyEPSG() 396 | epsg = int(srs.GetAuthorityCode(None)) 397 | 398 | xmin = geo[0] 399 | ymax = geo[3] 400 | xres = geo[1] 401 | yres = abs(geo[5]) 402 | 403 | xmax = xmin + xres * self.cols 404 | ymin = ymax - yres * self.rows 405 | 406 | self.extent = (xmin, xmax, ymin, ymax) 407 | 408 | # define some options for display of the widget box 409 | self.layout = Layout( 410 | display='flex', 411 | flex_flow='row', 412 | border='solid 2px', 413 | align_items='stretch', 414 | width='88%' 415 | ) 416 | 417 | self.colormap = cmap 418 | 419 | if band_indices is not None: 420 | if len(list(set(band_indices))) != self.bands: 421 | raise RuntimeError('length mismatch of unique provided band indices ({0}) ' 422 | 'and image bands ({1})'.format(len(band_indices), self.bands)) 423 | else: 424 | self.indices = sorted(band_indices) 425 | else: 426 | self.indices = range(1, self.bands + 1) 427 | 428 | # define a slider for changing a plotted image 429 | self.slider = IntSlider(min=min(self.indices), 430 | max=max(self.indices), 431 | step=1, 432 | continuous_update=False, 433 | value=self.indices[len(self.indices)//2], 434 | description='band index', 435 | style={'description_width': 'initial'}, 436 | layout=self.layout) 437 | 438 | display(self.slider) 439 | 440 | self.fig = plt.figure() 441 | self.ax = plt.gca() 442 | self.ax.get_xaxis().get_major_formatter().set_useOffset(False) 443 | self.ax.get_yaxis().get_major_formatter().set_useOffset(False) 444 | 445 | self.ax.set_xlabel('easting [m]', fontsize=12) 446 | self.ax.set_ylabel('northing [m]', fontsize=12) 447 | 448 | self.ax.format_coord = lambda x, y: \ 449 | 'easting={0:.2f}, northing={1:.2f}, reflectivity='.format(x, y) 450 | 451 | # enable interaction with the slider 452 | out = interactive_output(self.__onslide, {'h': self.slider}) 453 | 454 | def __onslide(self, h): 455 | mat = self.__read_band(self.indices.index(h) + 1) 456 | self.ax.imshow(mat, extent=self.extent, cmap=self.colormap) 457 | 458 | def __read_band(self, band): 459 | ras = gdal.Open(self.filename) 460 | mat = ras.GetRasterBand(band).ReadAsArray() 461 | ras = None 462 | return mat 463 | --------------------------------------------------------------------------------