├── .DS_Store ├── .gitignore ├── LICENSE ├── README.md ├── week-1 ├── Introduction to convolutional neural networks.ipynb ├── Large_scale_galaxy_formation_simulations_and_machine_learning_approaches_(Part_2)_Gaussian_process_regression_for_emulation.ipynb ├── Large_scale_galaxy_formation_simulations_and_machine_learning_approaches_Part1_Simulated_absorption_spectra.ipynb └── README.md ├── week-2 ├── README.md ├── tutorial_on_halo-galaxy_connection │ ├── Part2 - Normalizing_flows.ipynb │ ├── README.md │ ├── halo-galaxy_connection.ipynb │ └── model_transform.txt └── tutorial_on_universemachine │ └── UniverseMachine_Tutorial.ipynb ├── week-3 ├── KITP-CCA-GNN-tutorial.ipynb ├── KITP-CCA-Mangrove.ipynb ├── README.md ├── robust_uncertainties.ipynb └── sbi_tutorial.ipynb ├── week-4 ├── Malz_KITPCCA_photo-z_tutorial.ipynb ├── README.md ├── goldenspike_Colabified.ipynb ├── teddyAflow.pkl ├── teddyBflow.pkl └── teddyCflow.pkl ├── week-5 ├── README.md ├── jax_demo_diffmah.ipynb └── jax_overview.ipynb └── week-6 └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataDrivenGalaxyEvolution/galevo23-tutorials/487503a8ac3b05cf8c017bab163880b8ff36e498/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # KITP Galevo23 Tutorials 2 | 3 | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/) 4 | 5 | This repository contains tutorials for the 2023 KITP hybrid program *Building a Physical Understanding of Galaxy Evolution with Data-driven Astronomy*. For the program schedule and additional information, take a look at our [website](https://datadrivengalaxyevolution.github.io) or [KITP listing](https://www.kitp.ucsb.edu/activities/galevo23). 6 | 7 | ## What are these tutorials? 8 | 9 | The tutorial sessions will cover various topics in galaxy evolution and scientific machine learning. Some are designed to provide an introduction or overview of statistical and machine learning methods. Others focus on machine learning applications or answering specific scientific questions. 10 | 11 | Although each tutorial session is 1.5 hours long, we expect that the tutorial leads should keep their presentation to under an hour, which allows attendees to ask questions, work interactively, or discuss added topics. 12 | 13 | ## Which topics are being covered in the tutorials? 14 | 15 | Each week we will address a different set of scientific topics, and these **weekly themes** are now set for the virtual programs (see [here](https://datadrivengalaxyevolution.github.io/#virtualweeks)). We aim to have two tutorials per week, and will update this page as more details are finalized. 16 | 17 | 18 | - **Week 1 Tutorials** 19 | * Wed 1/18 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-1/Large_scale_galaxy_formation_simulations_and_machine_learning_approaches_Part1_Simulated_absorption_spectra.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/qezlou_ho/) Large-scale galaxy formation simulations and machine learning approaches, part 1: Absorption spectra in hydro simulations, by Mahdi Qezlou 20 | * Wed 1/18 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-1/Large_scale_galaxy_formation_simulations_and_machine_learning_approaches_(Part_2)_Gaussian_process_regression_for_emulation.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/qezlou_ho/) Large-scale galaxy formation simulations and machine learning approaches, part 2: Gaussian process regression for emulation, by Ming-Feng Ho 21 | * Thurs 1/19 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-1/Introduction%20to%20convolutional%20neural%20networks.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/wu/) Introduction to convolutional neural networks, by John Wu 22 | - **Week 2 Tutorials** 23 | * Tues 1/24 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-2/tutorial_on_halo-galaxy_connection/halo-galaxy_connection.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/desanti_lovell/) The galaxy-halo connection and machine learning approaches, part 1: Modeling the halo-galaxy connection, by Natalí de Santi 24 | * Tues 1/24 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-2/tutorial_on_halo-galaxy_connection/Part2%20-%20Normalizing_flows.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/desanti_lovell/) The galaxy-halo connection and machine learning approaches, part 2: Density estimation with normalizing flows, by Christopher Lovell 25 | * Wed 1/25 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-2/tutorial_on_universemachine/UniverseMachine_Tutorial.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/behroozi/) Galaxy scaling relations through working with UniverseMachine, by Peter Behroozi 26 | - **Week 3 Tutorials (CCA hybrid workshop)** 27 | * Mon 1/30 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-3/robust_uncertainties.ipynb) [[Recording]](https://www.dropbox.com/scl/fo/tgpwe1ljr4i9go4ajnsq6/h?dl=0&rlkey=mwl1zi14okj5k1pnbflcgnz3l) Robust Uncertainty Estimation in Machine Learning, by Aritra Ghosh 28 | * Tues 1/31 - [[Github]](https://github.com/MilesCranmer/pysr_tutorial) [[Recording]](https://www.dropbox.com/scl/fo/tgpwe1ljr4i9go4ajnsq6/h?dl=0&rlkey=mwl1zi14okj5k1pnbflcgnz3l) Symbolic Regression with PySR, by Miles Cranmer 29 | * Wed 2/1 - [[Colab]](https://colab.research.google.com/github/changhoonhahn/galevo23-tutorials/blob/main/week-3/sbi_tutorial.ipynb) [[Recording]](https://www.dropbox.com/scl/fo/tgpwe1ljr4i9go4ajnsq6/h?dl=0&rlkey=mwl1zi14okj5k1pnbflcgnz3l) Simulation-Based Inference, by ChangHoon Hahn 30 | * Thurs 2/2 - [[Github]](https://github.com/drtobybrown/KITP-CCA-Demo/blob/main/notebooks/PyCaret_Regression_Tutorial-Frozen.ipynb) Short tutorial on PyCaret, by Toby Brown 31 | * Thurs 2/2 - [[Recording]](https://www.dropbox.com/scl/fo/tgpwe1ljr4i9go4ajnsq6/h?dl=0&rlkey=mwl1zi14okj5k1pnbflcgnz3l) Spectral energy distribution modeling, by Kartheik Iyer 32 | * Fri 2/3 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-3/KITP-CCA-GNN-tutorial.ipynb) [[Recording]](https://www.dropbox.com/scl/fo/tgpwe1ljr4i9go4ajnsq6/h?dl=0&rlkey=mwl1zi14okj5k1pnbflcgnz3l) Graph neural networks and merger trees, by Christian Kragh Jespersen 33 | - **Week 4 Tutorials** 34 | * Wed 2/8 - [[Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-4/Malz_KITPCCA_photo-z_tutorial.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/malz/) Photometric redshifts and uncertainties thereof, by Alex Malz 35 | - **Week 5 Tutorials** 36 | * Wed 2/15 - [[Github]](https://github.com/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-5/) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/hearin/) Autodifferentiation and JAX, by Andrew Hearin 37 | - **Week 6 Tutorials** 38 | * Wed 2/22 - [[Colab]](https://colab.research.google.com/github/mhsotoudeh/ProbUNet-Tutorial/blob/main/02%20Rescue%20The%20Randomness.ipynb) [[Recording]](https://online.kitp.ucsb.edu/online/galevo23/sotoudeh/) Probabilistic U-Nets, by Hadi Sotoudeh 39 | 40 | ## Navigating through the tutorials 41 | 42 | We hope that most of these tutorials can be run on the cloud (e.g. through Google Colab) or locally with minimal dependencies. However, we note that different tutorials have different authors, so the coding and writing style will not be consistent throughout the repository. 43 | 44 | To navigate to a tutorial, simply click on the week you're interested in (see above schedule) and find the relevant files for each tutorial. For example, if you want to open the *Introduction to Convolutional Neural Networks* tutorial, go to `week-1` and then open `Introduction to convolutional neural networks.ipynb`. Note that you can also open this repository or the subdirectories in [Google Colab](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/). 45 | -------------------------------------------------------------------------------- /week-1/README.md: -------------------------------------------------------------------------------- 1 | # Week 1 Tutorials 2 | 3 | - **(1/18) Galaxy simulations, part 1: Absorption spectra in hydro simulations - [Open in Colab](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-1/Large_scale_galaxy_formation_simulations_and_machine_learning_approaches_Part1_Simulated_absorption_spectra.ipynb)** 4 | - **(1/18) Galaxy simulations, part 2: Gaussian process regression for emulation - [Open in Colab](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-1/Large_scale_galaxy_formation_simulations_and_machine_learning_approaches_(Part_2)_Gaussian_process_regression_for_emulation.ipynb)** 5 | 6 | - **(1/19) Introduction to convolutional neural networks - [Open in Colab](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-1/Introduction%20to%20convolutional%20neural%20networks.ipynb)** 7 | 8 | -------------------------------------------------------------------------------- /week-2/README.md: -------------------------------------------------------------------------------- 1 | # Week 2 Tutorials 2 | 3 | - **(1/24) Galaxy-halo connection, part 1: Modelling the Halo-Galaxy Connection - [Open in Colab](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-2/tutorial_on_halo-galaxy_connection/halo-galaxy_connection.ipynb)** 4 | 5 | - **(1/24) Galaxy-halo connection, part 2: Density Estimation with Normalizing Flows - [Open in Colab]( 6 | https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-2/tutorial_on_halo-galaxy_connection/Part2%20-%20Normalizing_flows.ipynb)** 7 | 8 | - **(1/25) An Introduction to UniverseMachine - [Open in Colab](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-2/tutorial_on_universemachine/UniverseMachine_Tutorial.ipynb)** 9 | -------------------------------------------------------------------------------- /week-2/tutorial_on_halo-galaxy_connection/README.md: -------------------------------------------------------------------------------- 1 | # Tutorial on halo-galaxy connection 2 | 3 | Hello there! Here you will find a tutorial on halo-galaxy connection developed by [@christopherlovell](https://www.christopherlovell.co.uk/) and ([@natalidesanti](https://natalidesanti.github.io/)). This tutorial will happen virtually on January 24th as part of the second week of the 4 | [Building a physical understanding of galaxy evolution with data-driven astronomy](https://datadrivengalaxyevolution.github.io/#description). 5 | 6 | ## Material 7 | 8 | Here you can find two jupyter notebooks: 9 | 10 | * The galaxy-halo relationship: 11 | * **Handling data:** general data details, including how to read the files, get halo/galaxy properties and pre-process everthing 12 | * **Neural Networks:** linking halo to galaxies using neural networks 13 | * **Optuna:** hyperparameter optmization with `optuna` 14 | * **SMOGN:** data augmentation using `SMOGN` 15 | * **SMOGN predictions using optuna:** getting the predictions using the augmented datasets in an optimized model 16 | * Matching between halo catalogues in DMO and Hydro simulations 17 | 18 | * Normalizing flows 19 | * Background 20 | * Multivariate transforms 21 | * Couple transforms 22 | * Conditional transforms 23 | * An application to galaxy-halo data 24 | 25 | ## Supplementary material 26 | 27 | We organized the tutorial based on: 28 | 29 | * Wechsler, R. H. and Tinker, J. L. 2018, [arXiv: 1804.03097](https://arxiv.org/abs/1804.03097) 30 | * Lovell, C. C., Wilkins, S. M., Thomas, P. A., Schaller, M., Baugh, C. M., Fabbian, G. and Bahé, Y., [arXiv: 2106.04980](https://arxiv.org/abs/2106.04980) 31 | * de Santi, N. S. M., Rodrigues, N. V. N., Montero-Dorta, A. D., Abramo, L. R., Tucci, B. and Artale, M. C., [arXiv: 2201.06054](https://arxiv.org/abs/2201.06054) 32 | -------------------------------------------------------------------------------- /week-2/tutorial_on_halo-galaxy_connection/model_transform.txt: -------------------------------------------------------------------------------- 1 | 1.072031403698943564e+01 -6.692464552540304368e+00 2.144412014177698556e+00 2 | 5.783104140814606664e-01 1.927702834214697070e-01 2.407389074117468886e-01 3 | -------------------------------------------------------------------------------- /week-3/README.md: -------------------------------------------------------------------------------- 1 | # Week 3 Tutorials 2 | 3 | - **(1/30) Robust Uncertainty Estimation in Machine Learning** [[Open in Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-3/robust_uncertainties.ipynb) 4 | - **(1/31) Symbolic Regression with PySR** [[View repository]](https://github.com/MilesCranmer/pysr_tutorial) 5 | - **(2/1) Simulation-Based Inference** [[Open in Colab]](https://colab.research.google.com/github/changhoonhahn/galevo23-tutorials/blob/main/week-3/sbi_tutorial.ipynb) 6 | - **(2/2) PyCaret** [[View repository]](https://github.com/drtobybrown/KITP-CCA-Demo/blob/main/notebooks/PyCaret_Regression_Tutorial-Frozen.ipynb) 7 | - **(2/2) Spectral energy distribution modeling** 8 | - **(2/3) Graph neural networks and merger trees** [[Open in Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-3/KITP-CCA-GNN-tutorial.ipynb) 9 | -------------------------------------------------------------------------------- /week-4/Malz_KITPCCA_photo-z_tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "view-in-github", 7 | "colab_type": "text" 8 | }, 9 | "source": [ 10 | "\"Open" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "source": [ 16 | "#
Photo-$z$s and uncertainties thereof: A tutorial
\n", 17 | "####
**[Alex I. Malz](https://github.com/aimalz)**
\n", 18 | "####
LINCC Frameworks @ Carnegie Mellon University
\n", 19 | "####
\n", 20 | "####
[KITP-CCA Workshop: Data Driven Galaxy Evolution](https://datadrivengalaxyevolution.github.io/#ccaweek)
" 21 | ], 22 | "metadata": { 23 | "id": "s0TLpSfV1iug" 24 | } 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": { 29 | "id": "TJJCNEYMp64R" 30 | }, 31 | "source": [ 32 | "This tutorial was adapted from [a problem set](https://github.com/LSSTC-DSFP/LSSTC-DSFP-Sessions/blob/main/Sessions/Session16/Day4/expdes-photoz.ipynb) at the [LSSTC Data Science Fellowship Program](https://astrodatascience.org/), which was in turn adapted from a data challenge at a workshop;\n", 33 | "if you use anything from here in a publication, cite [the repo it originally came from](https://github.com/aimalz/qtc2021) and acknowledge \"[From Quarks to Cosmos with AI](https://events.mcs.cmu.edu/qtc2021/), a conference supported by the NSF AI Institute: Physics of the Future, NSF PHY-2020295.\" \n", 34 | "\n", 35 | "## Overview\n", 36 | "\n", 37 | "As we look ahead to inferring the physics of galaxy evolution from deep catalogs lacking spectroscopy, we will very likely need to rely on photometric redshifts (photo-$z$s) for large-scale analyses.\n", 38 | "This tutorial assumes you know the basic idea and have some familiarity with how redshift estimates factor into the kinds of analyses you want to do.\n", 39 | "My goal is to impart an appreciation for the nuances of photo-$z$s we have to anticipate for LSST data to help us all get the most out of them.\n", 40 | "\n", 41 | "This notebook provides some choices of photo-$z$ estimation models, options for data and priors upon which to test the models, and a variety of metrics to evaluate the estimates, an end-to-end pipeline for \n", 42 | "Your objective is to uncover the unstated assumptions, probe the limiting cases, and overall figure out how to break the experiment, thereby identifying what you need to do to ensure photo-$z$ data products suit your needs." 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": { 48 | "id": "2O19PzXur-GF" 49 | }, 50 | "source": [ 51 | "## Motivation\n", 52 | "\n", 53 | "More and more data-driven methods yield uncertainties $\\hat{p}(y | x_{i})$ of target parameters $y$ given observed random variables $x_{i}$, rather than just point estimates $\\hat{y}_{i}$.\n", 54 | "Though rarely framed as such, these uncertainties are _posteriors_, and there's more than meets the eye to what lies on the righthand side of the conditional.\n", 55 | "\n", 56 | "Really, an estimated posterior should be writen as $p(y | x_{i}, \\pi, M)$ for prior $\\pi$ (which is training data $\\{y_{n}, x_{n}\\}_{N}$ for a machine learning approach and takes other forms for physics-informed models) and algorithm (model) $M$.\n", 57 | "Though the dependence on prior information is straightforward, the dependence on the algorithm, meaning the estimation model and its implementation, is subtle.\n", 58 | "However, if it were not there, then every model with the same prior information would yield identical estimated uncertainties, which is not observed.\n", 59 | "While the $\\pi$ (e.g. training set $\\{y_{n}, x_{n}\\}_{N}$) is equivalent to an _explicit prior_, the algorithm $M$ must be considered an _implicit prior_, in that we don't know how to write down how it projects onto the space of data.\n", 60 | "\n", 61 | "Another way of looking at estimated posteriors is in terms of the type of uncertainty encompassed by each term on the righthand side of the conditional.\n", 62 | "For a noisy measurement or a stochastic generative process, the random variable $x_{i} \\sim p(x | y_{i})$ represents the _aleatoric uncertainty_, the uncertainty inherent to the data.\n", 63 | "However, the training set $\\{y_{n}, x_{n}\\}_{N}$ and implemented etimation model $M$ could potentially be improved to yield a better estimate and thus constitute sources of _epistemic uncertainty_, the uncertainty due to an imperfect model.\n", 64 | "In physics, we want to learn the aleatoric uncertainty $p(x | y_{i})$, which we can't get from the estimated posteriors $p(y | x_{i}, \\{y_{n}, x_{n}\\}_{N}, M)$ in hand without knowing $p(y | \\{y_{n}, x_{n}\\}_{N}, M)$.\n", 65 | "\n", 66 | "Meanwhile, assessments of the performance of estimated $p(y | x_{i}, \\{y_{n}, x_{n}\\}_{N}, M)$ are almost always made by comparison to known $y_{i}$, leaving unanswered the question of how well the estimator approximates $p(y | x_{i})$.\n", 67 | "Why?\n", 68 | "The problem is that $p(y | x_{i})$ is not necessarily known, certainly not for observed $y_{i}$ measured in nature, but also generally for simulated $y_{i}$, at least in astrophysics." 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": { 74 | "id": "QW-T6Zq70MwL" 75 | }, 76 | "source": [ 77 | "## Context: Photometric redshifts\n", 78 | "\n", 79 | "[Photo-$z$s](https://en.wikipedia.org/wiki/Photometric_redshift) provide an excellent testbed for addressing these issues but require some introduction.\n", 80 | "There isn't a definitive primer, but here are several overviews that are informative, if a bit dry.\n", 81 | "- [basic intro from Rubin Observatory](https://www.lsst.org/science/dark-energy/photometric-redshift)\n", 82 | "- [old overview covering classic concepts](https://ned.ipac.caltech.edu/level5/Glossary/Essay_photredshifts.html)\n", 83 | "- [recent review of estimation methods](https://arxiv.org/abs/1805.12574)\n", 84 | "If these don't answer your questions, Chapter 0 of [my thesis](https://zenodo.org/record/3973536) might, or, better yet, [the slides from my defense](https://github.com/aimalz/ship-of-theses/tree/master/presentation) make for a better tl;dr.\n", 85 | "\n", 86 | "Photo-$z$s are an ideal system to study because they are simple enough to obtain $p(y | x_{i})$ along the way to generating a sample of $(y_{i}, x_{i})$ pairs.\n", 87 | "Here, the target variable $y \\to z$ is redshift, a scalar, and the data $x \\to \\vec{d} = (u, g, r, i, z, y)$, or some trivial function thereof, is a vector of length $<10$ observed [photometric magnitudes](https://en.wikipedia.org/wiki/Magnitude_(astronomy)) of galaxies through [broadband optical filters](https://en.wikipedia.org/wiki/Photometric_system) (which I somewhat arbitrarily choose to be those of [the Vera C. Rubin Observatory](https://www.lsst.org/)).\n", 88 | "Because of the extremely low dimensionality of the problem, we can forward model not just individual pairs $(z_{i}, \\vec{d}_{i})$ but the entire joint probability space $p(z, \\vec{d})$, thereby obtaining $p(y | x_{i})$ for every $(z_{i}, \\vec{d}_{i})$.\n", 89 | "That doesn't mean it's trivial to do so -- most of this tutorial concerns that forward-modeling procedure -- but it is possible.\n", 90 | "\n", 91 | "Another reason photo-$z$s are apt is that comprehensive uncertainty quantification for galaxy redshifts in the absence of spectroscopy are crucial for the Legacy Survey of Space and Time (LSST), an upcoming photometric survey on the Rubin Observatory.\n", 92 | "This tutorial makes use of two pieces of software under public development, [RAIL](https://github.com/LSSTDESC/RAIL) and [qp](https://github.com/LSSTDESC/qp), whose functionality will be introduced where relevant, along with other code dependencies.\n", 93 | "Participants need not use either in their responses to the challenge questions, but the development team welcomes feedback from potential users and new developers, no collaboration membership required." 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": { 99 | "id": "ZIOag5iVqZPW" 100 | }, 101 | "source": [ 102 | "# Tutorial and challenge prompts\n", 103 | "\n", 104 | "Finally, without more ado, we set the stage with a tutorial that:\n", 105 | "1. creates realistically complex mock photo-$z$ posteriors, redshifts, and photometry to define training and test sets;\n", 106 | "2. estimates photo-$z$ posteriors of the test set given the training set;\n", 107 | "3. quantifies how closely the estimated posteriors approximate the true ones.\n", 108 | "\n", 109 | "The three-pronged structure of this tutorial is inspired by that of [RAIL](https://github.com/LSSTDESC/RAIL), which has subpackages corresponding to each of the enumerated parts of the tutorial: `rail.creation`, `rail.estimation`, and `rail.evaluation`.\n", 110 | "You can explore them in their native habitat [in this separate Colab notebook](https://colab.research.google.com/drive/1YCWRdbNfslAhuxYaxgp_3M9Q37jBPLd6?usp=sharing) (also in the tutorial repository), but I took out the pieces here to make it easier to see what's going on, even though RAIL would be far more appropriate for an at-scale pipeline. \n", 111 | "\n", 112 | "The challenge comes from building on the tutorial content to conduct a self-guided investigation of the open questions.\n", 113 | "To get the most out of this opportunity, think of this tutorial as a lab manual that presents an experimental procedure to answer each question and includes an example of a possible solution, then invites participants to \"riff\" on those solutions to devise and implement their own.\n", 114 | "Some opportunities for such investigations can be found under the \"Challenge\" headings throughout the tutorial, but feel free to make your own!" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "metadata": { 120 | "id": "JituVGNVZ7bg" 121 | }, 122 | "source": [ 123 | "## 0. Setup" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": null, 129 | "metadata": { 130 | "id": "_2llNhgut6jM", 131 | "collapsed": true 132 | }, 133 | "outputs": [], 134 | "source": [ 135 | "!pip install scikit-learn scipy==1.10.0 corner\n", 136 | "!pip install cde-diagnostics cdetools FlexCode xgboost==0.90\n", 137 | "!pip install pz-rail" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": { 144 | "id": "hNhx0u1vszZN" 145 | }, 146 | "outputs": [], 147 | "source": [ 148 | "import jax.numpy as jnp\n", 149 | "import numpy as np\n", 150 | "import pandas as pd\n", 151 | "import sklearn" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "metadata": { 158 | "id": "XHM0pdtvLdG2" 159 | }, 160 | "outputs": [], 161 | "source": [ 162 | "import cdetools\n", 163 | "import flexcode\n", 164 | "import pzflow\n", 165 | "import qp" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": null, 171 | "metadata": { 172 | "id": "lZs_a1wy0EbC" 173 | }, 174 | "outputs": [], 175 | "source": [ 176 | "import matplotlib as mpl\n", 177 | "import matplotlib.pyplot as plt\n", 178 | "import matplotlib.patches as mpl_patches\n", 179 | "mpl.rc('text', usetex=False)\n", 180 | "\n", 181 | "import corner" 182 | ] 183 | }, 184 | { 185 | "cell_type": "markdown", 186 | "metadata": { 187 | "id": "O9imLKSxZ_F1" 188 | }, 189 | "source": [ 190 | "## 1. Generating mock data, including true photo-$z$ posteriors\n", 191 | "\n", 192 | "This is the most complex of the parts of the tutorial, which should leave readers with a sense of why this kind of experiment has not been done for higher-dimensional data.\n", 193 | "There are three main steps:\n", 194 | "1. Prepare and explore data to use as the basis for a realistically complex generative model.\n", 195 | "2. Emulate a few realistically complex $p(z, \\vec{d})$ probability spaces using input data.\n", 196 | "3. Sample $p(z, \\vec{d})$ and $p'(z, \\vec{d})$ to produce photometric data sets to use as explicit prior information and on which to estimate redshift posteriors, with known $z$, $\\vec{d}$, and $p(z | \\vec{d})$." 197 | ] 198 | }, 199 | { 200 | "cell_type": "markdown", 201 | "metadata": { 202 | "id": "7pexhHnZsoNq" 203 | }, 204 | "source": [ 205 | "### Data\n", 206 | "\n", 207 | "Though we're going to forward-model mock data to experiment on, we want it to be _realistically complex_, meaning it shares the physical degeneracies and systematic errors that would be present in a real data set.\n", 208 | "The [Happy/Teddy data sets](https://github.com/COINtoolbox/photoz_catalogues) (see [Beck, et al 2017](https://arxiv.org/abs/1701.08748) for full release notes) are curated subsamples of the [Sloan Digital Sky Survey (SDSS) Data Release (DR) 12](https://www.sdss.org/dr12/), a spectroscopic survey with high-fidelity redshift measurements, and were created by the [Cosmostatistics Initiative (COIN)](https://cosmostatistics-initiative.org/).\n", 209 | "The data sets are defined to emulate the kinds of differences in observational properties of galaxies with measured spectroscopic redshifts and those for which only photometry is available, and they were created with the goal of determining the impact of imbalance between training, validation, and test sets for photo-$z$ point estimation.\n", 210 | "They are thus an appropriate starting point for creating a realistically complex model of the joint probability space $p(z, \\vec{d})$.\n", 211 | "\n", 212 | "Of course there are plenty of other potential data sets available, including those that are simulated, which may be advantageous for the potential to estimate other galaxy properties such as stellar mass and star formation rate that are known in a simulation but not directly measurable with real data." 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "source": [ 218 | "!git clone https://github.com/COINtoolbox/photoz_catalogues.git" 219 | ], 220 | "metadata": { 221 | "id": "SK9BYiudQnQy" 222 | }, 223 | "execution_count": null, 224 | "outputs": [] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": { 230 | "id": "71MdMCuXn16X" 231 | }, 232 | "outputs": [], 233 | "source": [ 234 | "happy_path = './photoz_catalogues/Happy/happy_'\n", 235 | "header = pd.read_csv(happy_path+'A', delim_whitespace=True, nrows=0).columns[1:]\n", 236 | "teddy_path = './photoz_catalogues/Teddy/teddy_'\n", 237 | "\n", 238 | "happy, teddy = {}, {}\n", 239 | "for lett in ['A', 'B', 'C', 'D']:\n", 240 | " happy[lett] = pd.read_csv(happy_path+lett, delim_whitespace=True, header=None, skiprows=1, names=header)\n", 241 | " happy[lett] = happy[lett].rename(columns={'z_spec':'redshift', 'mag_r': 'r'})[['redshift', 'r', 'u-g', 'g-r', 'r-i', 'i-z']]\n", 242 | "# happy[lett]\n", 243 | " teddy[lett] = pd.read_csv(teddy_path+lett, delim_whitespace=True, header=None, skiprows=7, names=header)\n", 244 | " teddy[lett] = teddy[lett].rename(columns={'z_spec':'redshift', 'mag_r': 'r'})[['redshift', 'r', 'u-g', 'g-r', 'r-i', 'i-z']]\n", 245 | "# teddy[lett]" 246 | ] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": null, 251 | "metadata": { 252 | "id": "TV_VxG8CtoDW" 253 | }, 254 | "outputs": [], 255 | "source": [ 256 | "fig, ax = plt.subplots(2, 2, figsize=(10, 10))\n", 257 | "for j, col in enumerate(['redshift', 'r']):\n", 258 | " for i, lett in enumerate(['A', 'B', 'C', 'D']):\n", 259 | " ax[j][0].hist(happy[lett][col], alpha=0.25, bins=100, density=False, label='happy_'+lett)\n", 260 | " ax[j][1].hist(teddy[lett][col], alpha=0.25, bins=100, density=False, label='teddy_'+lett)\n", 261 | " ax[j][0].set_xlabel(col)\n", 262 | " ax[j][0].legend()\n", 263 | " ax[j][1].set_xlabel(col)\n", 264 | " ax[j][1].legend()" 265 | ] 266 | }, 267 | { 268 | "cell_type": "markdown", 269 | "metadata": { 270 | "id": "kRQblNfe0cCQ" 271 | }, 272 | "source": [ 273 | "For convenience later on, we can safely cut off the tiny fraction of outliers in redshift and $r$-band magnitude." 274 | ] 275 | }, 276 | { 277 | "cell_type": "code", 278 | "execution_count": null, 279 | "metadata": { 280 | "id": "WutxjLl4YvLG" 281 | }, 282 | "outputs": [], 283 | "source": [ 284 | "z_min, z_max = 0., 1.5\n", 285 | "r_min, r_max = 10., 25." 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": null, 291 | "metadata": { 292 | "id": "C9YMBF_NsekS" 293 | }, 294 | "outputs": [], 295 | "source": [ 296 | "colorcycle = 'rbgcmy'\n", 297 | "fig = corner.corner(happy['A'][['u-g', 'g-r', 'r-i', 'i-z']], color='k', alpha=0.25)\n", 298 | "for i, lett in enumerate(['B', 'C', 'D']):\n", 299 | " corner.corner(happy[lett][['u-g', 'g-r', 'r-i', 'i-z']], fig=fig, color=colorcycle[i], alpha=0.25)\n", 300 | " \n", 301 | "fig = corner.corner(teddy['A'][['u-g', 'g-r', 'r-i', 'i-z']], color='k', alpha=0.25)\n", 302 | "for i, lett in enumerate(['B', 'C', 'D']):\n", 303 | " corner.corner(teddy[lett][['u-g', 'g-r', 'r-i', 'i-z']], fig=fig, color=colorcycle[i], alpha=0.25)" 304 | ] 305 | }, 306 | { 307 | "cell_type": "markdown", 308 | "metadata": { 309 | "id": "AuzPDc5WsrUK" 310 | }, 311 | "source": [ 312 | "### Emulating $p(z, \\vec{d})$ from input data\n", 313 | "\n", 314 | "[`pzflow`](https://github.com/jfcrenshaw/pzflow) is a package for making normalizing flows from sets of redshifts and photometry in order to estimate or otherwise model photo-$z$ posteriors.\n", 315 | "We'll use it to make a normalizing flow that will serve as the model for $p(z, \\vec{d})$.\n", 316 | "\n", 317 | "_This content is adapted from pzflow's [demo](https://github.com/jfcrenshaw/pzflow/blob/main/docs/tutorials/intro.ipynb), written by John Franklin Crenshaw (UW)._" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "metadata": { 324 | "id": "9yW3ONw4q9pw" 325 | }, 326 | "outputs": [], 327 | "source": [ 328 | "from pzflow import Flow\n", 329 | "from pzflow.bijectors import Chain, ColorTransform, InvSoftplus, StandardScaler, RollingSplineCoupling, ShiftBounds\n", 330 | "from pzflow.examples import get_galaxy_data\n", 331 | "from pzflow.distributions import Uniform" 332 | ] 333 | }, 334 | { 335 | "cell_type": "markdown", 336 | "metadata": { 337 | "id": "nFJ8Lwxz0cCS" 338 | }, 339 | "source": [ 340 | "Let's start with a demonstration of how pzflow makes a model of $p(z, \\vec{d})$ from its own demo data." 341 | ] 342 | }, 343 | { 344 | "cell_type": "code", 345 | "execution_count": null, 346 | "metadata": { 347 | "id": "wV1CUpkA0cCT" 348 | }, 349 | "outputs": [], 350 | "source": [ 351 | "data = get_galaxy_data()" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": null, 357 | "metadata": { 358 | "id": "ZxmVog1_kTqu" 359 | }, 360 | "outputs": [], 361 | "source": [ 362 | "data = get_galaxy_data()\n", 363 | "\n", 364 | "# restrict to Happy/Teddy range for coverage in demo\n", 365 | "data = data[(data['redshift'] > z_min) & (data['redshift'] < z_max) & (data['r'] > r_min) & (data['r'] < r_max)]\n", 366 | "\n", 367 | "# normalize\n", 368 | "data = data\n", 369 | "\n", 370 | "# use fewer bands to be able to compare with Happy/Teddy\n", 371 | "data = data[['redshift', 'u', 'g', 'r', 'i', 'z']]\n", 372 | "\n", 373 | "# convert magnitudes to a reference magnitude and colors\n", 374 | "data['u-g'] = data['u'] - data['g']\n", 375 | "data['g-r'] = data['g'] - data['r']\n", 376 | "data['r-i'] = data['r'] - data['i']\n", 377 | "data['i-z'] = data['i'] - data['z']\n", 378 | "\n", 379 | "# save the new set\n", 380 | "data = data[['redshift', 'r', 'u-g', 'g-r', 'r-i', 'i-z']]" 381 | ] 382 | }, 383 | { 384 | "cell_type": "code", 385 | "source": [ 386 | "corner.corner(data)" 387 | ], 388 | "metadata": { 389 | "id": "W-qzrL_bRMDP" 390 | }, 391 | "execution_count": null, 392 | "outputs": [] 393 | }, 394 | { 395 | "cell_type": "code", 396 | "execution_count": null, 397 | "metadata": { 398 | "id": "4KdppeUD5t7l" 399 | }, 400 | "outputs": [], 401 | "source": [ 402 | "# set the inverse softplus parameters, estimated\n", 403 | "# to ensure that sampled redshifts are positive\n", 404 | "column_idx = 0\n", 405 | "\n", 406 | "n_epoch = 30\n", 407 | "\n", 408 | "mins = [z_min, r_min, -1, -1, -1, -1]\n", 409 | "maxs = [z_max, r_max, 5, 5, 5, 5]\n", 410 | "\n", 411 | "# construct our bijector\n", 412 | "# by chaining all these layers\n", 413 | "bijector = Chain(\n", 414 | " ShiftBounds(mins, maxs, B=5),\n", 415 | " RollingSplineCoupling(nlayers=6)\n", 416 | ")\n", 417 | "\n", 418 | "\n", 419 | "flow = Flow(data.columns, bijector)" 420 | ] 421 | }, 422 | { 423 | "cell_type": "markdown", 424 | "metadata": { 425 | "id": "dIk6pJim0cCU" 426 | }, 427 | "source": [ 428 | "This step may be slow (~minutes) if you don't have a GPU runtime enabled (or if jax can't find the Colab GPU?)." 429 | ] 430 | }, 431 | { 432 | "cell_type": "code", 433 | "execution_count": null, 434 | "metadata": { 435 | "id": "hWxpXjO10cCV" 436 | }, 437 | "outputs": [], 438 | "source": [ 439 | "losses = flow.train(data, epochs=n_epoch, verbose=True)" 440 | ] 441 | }, 442 | { 443 | "cell_type": "code", 444 | "execution_count": null, 445 | "metadata": { 446 | "id": "B2d6air_0cCV" 447 | }, 448 | "outputs": [], 449 | "source": [ 450 | "plt.plot(losses)\n", 451 | "plt.xlabel(\"Epoch\")\n", 452 | "plt.ylabel(\"Training loss\")\n", 453 | "plt.show()" 454 | ] 455 | }, 456 | { 457 | "cell_type": "code", 458 | "execution_count": null, 459 | "metadata": { 460 | "id": "qEZM40DR0cCW" 461 | }, 462 | "outputs": [], 463 | "source": [ 464 | "flow.save('default_flow.pkl')\n", 465 | "flow = Flow(file='default_flow.pkl')" 466 | ] 467 | }, 468 | { 469 | "cell_type": "markdown", 470 | "metadata": { 471 | "id": "NUcXXdjo0cCW" 472 | }, 473 | "source": [ 474 | "We need to choose a redshift grid upon which to evaluate the posterior PDFs.\n", 475 | "(Different engines for creating mock data may have different parameterizations that don't require this specification.)" 476 | ] 477 | }, 478 | { 479 | "cell_type": "code", 480 | "execution_count": null, 481 | "metadata": { 482 | "id": "QNl-Q4YqXaxc" 483 | }, 484 | "outputs": [], 485 | "source": [ 486 | "granularity = 100\n", 487 | "grid = np.linspace(z_min, z_max, granularity)" 488 | ] 489 | }, 490 | { 491 | "cell_type": "markdown", 492 | "metadata": { 493 | "id": "Alnb-qN40cCX" 494 | }, 495 | "source": [ 496 | "Let's check one of them before making more." 497 | ] 498 | }, 499 | { 500 | "cell_type": "code", 501 | "execution_count": null, 502 | "metadata": { 503 | "id": "qS_Zs9Vqbs3x" 504 | }, 505 | "outputs": [], 506 | "source": [ 507 | "chosen = 999\n", 508 | "\n", 509 | "galaxy = data.iloc[[chosen]]\n", 510 | "pdf = flow.posterior(galaxy, column=\"redshift\", grid=grid)\n", 511 | "\n", 512 | "plt.plot(grid, pdf[0], label='Posterior')\n", 513 | "plt.axvline(galaxy['redshift'].values[0], 0, 1, c='C3', label='True redshift')\n", 514 | "plt.legend()\n", 515 | "plt.xlabel(\"redshift\")\n", 516 | "plt.show()" 517 | ] 518 | }, 519 | { 520 | "cell_type": "markdown", 521 | "metadata": { 522 | "id": "9t6TnQ5e0cCY" 523 | }, 524 | "source": [ 525 | "Sample from the model of $p(z, data)$.\n", 526 | "(If you run out of memory, take fewer samples.)" 527 | ] 528 | }, 529 | { 530 | "cell_type": "code", 531 | "execution_count": null, 532 | "metadata": { 533 | "id": "OGrTo5J4TKuQ" 534 | }, 535 | "outputs": [], 536 | "source": [ 537 | "samples = flow.sample(10000, conditions=data[:5000], seed=0)\n", 538 | "plt.hist(data['redshift'], range=(0, 2.5), bins=40, histtype='step', label='data', density=True)\n", 539 | "plt.hist(samples['redshift'], range=(0, 2.5), bins=40, histtype='step', label='samples', density=True)\n", 540 | "plt.xlabel('z')\n", 541 | "plt.legend()\n", 542 | "plt.show()" 543 | ] 544 | }, 545 | { 546 | "cell_type": "code", 547 | "execution_count": null, 548 | "metadata": { 549 | "id": "UwGykJnbmqys" 550 | }, 551 | "outputs": [], 552 | "source": [ 553 | "z = samples['redshift']\n", 554 | "z.to_csv('test_set_redshifts.csv')\n", 555 | "\n", 556 | "phot = samples[['r', 'u-g', 'g-r', 'r-i', 'i-z']]\n", 557 | "phot.to_csv('test_set_photometry.csv')\n", 558 | "\n", 559 | "posteriors = flow.posterior(samples, column=\"redshift\", grid=grid)\n", 560 | "with open('test_set_posteriors.csv', 'wb') as fn:\n", 561 | " jnp.save(fn, posteriors)" 562 | ] 563 | }, 564 | { 565 | "cell_type": "markdown", 566 | "metadata": { 567 | "id": "eyecUsXrJJ7R" 568 | }, 569 | "source": [ 570 | "We can do this procedure for all the Happy/Teddy samples so we can experiment with them later.\n", 571 | "It's slow without using GPU, but it only needs to be done once.\n", 572 | "(The repo also contains a few of these trained models to play with.)" 573 | ] 574 | }, 575 | { 576 | "cell_type": "code", 577 | "source": [ 578 | "full_data = {'teddy': teddy}#'happy': happy\n", 579 | "# not sure why Happy data sets won't train on colab now?\n", 580 | "n_out = 1000" 581 | ], 582 | "metadata": { 583 | "id": "D4EQPfAgGIf6" 584 | }, 585 | "execution_count": null, 586 | "outputs": [] 587 | }, 588 | { 589 | "cell_type": "code", 590 | "execution_count": null, 591 | "metadata": { 592 | "id": "dvYgIMnWuq9b" 593 | }, 594 | "outputs": [], 595 | "source": [ 596 | "for name, dat in full_data.items():\n", 597 | " for lett in ['A', 'B', 'C':]#, 'D']:\n", 598 | " # also not sure why teddyD won't train anymore. . .\n", 599 | " print(name+lett)\n", 600 | " print(dat[lett].columns)\n", 601 | " print(len(dat[lett]))\n", 602 | " \n", 603 | " flow = Flow(dat[lett].columns, bijector)\n", 604 | "\n", 605 | " losses = flow.train(dat[lett], epochs=n_epoch, verbose=True)\n", 606 | " flow.save(name+lett+'flow.pkl')\n", 607 | " print('done with '+name+lett)" 608 | ] 609 | }, 610 | { 611 | "cell_type": "code", 612 | "execution_count": null, 613 | "metadata": { 614 | "id": "tU-efFb50cCa" 615 | }, 616 | "outputs": [], 617 | "source": [ 618 | "for name, dat in full_data.items():\n", 619 | " for lett in ['A', 'B', 'C']:#, 'D']: \n", 620 | " print(name+lett)\n", 621 | " flow = Flow(file=name+lett+'flow.pkl')\n", 622 | "\n", 623 | " samples = flow.sample(10000, conditions=dat[lett].sample(n_out), seed=0)\n", 624 | "\n", 625 | " z = samples['redshift']\n", 626 | " z.to_csv(name+lett+'redshifts.csv', index=False)\n", 627 | "\n", 628 | " phot = samples[['r', 'u-g', 'g-r', 'r-i', 'i-z']]\n", 629 | " phot.to_csv(name+lett+'photometry.csv', index=False)\n", 630 | "\n", 631 | " posteriors = flow.posterior(samples, column=\"redshift\", grid=grid)\n", 632 | " with open(name+lett+'posteriors.csv', 'wb') as fn:\n", 633 | " jnp.save(fn, posteriors)" 634 | ] 635 | }, 636 | { 637 | "cell_type": "markdown", 638 | "metadata": { 639 | "id": "BHVvqswx0cCa" 640 | }, 641 | "source": [ 642 | "### Challenge 1\n", 643 | "\n", 644 | "Try to \"degrade\" the drawn data to introduce degeneracies, inconsistencies, and nonrepresentativity that could trip up an estimator with or without being missed by a metric.\n", 645 | "Show what that photometry looks like and save it to feed into estimators later in the tutorial." 646 | ] 647 | }, 648 | { 649 | "cell_type": "code", 650 | "execution_count": null, 651 | "metadata": { 652 | "id": "IvB8x8sE0cCa" 653 | }, 654 | "outputs": [], 655 | "source": [] 656 | }, 657 | { 658 | "cell_type": "markdown", 659 | "metadata": { 660 | "id": "0xpQw49TaR03" 661 | }, 662 | "source": [ 663 | "## 2. Estimating photo-z posterior PDFs\n", 664 | "\n", 665 | "There are many estimators of photo-$z$ posteriors, and many of those are compared to one another in [Schmidt & Malz, et al. 2020](https://arxiv.org/abs/2001.03621).\n", 666 | "The outcomes of that experiment inspired the design of the [Redshift Assessment Infrastructure Layers (RAIL](https://github.com/LSSTDESC/RAIL) codebase, an open-source toolkit that provides a unified API for many photo-$z$ estimators and instructions for wrapping additional ones to be included.\n", 667 | "If you need to obtain photo-$z$ PDFs at scale, the [Golden Spike](https://github.com/LSSTDESC/RAIL/tree/main/examples/goldenspike) end-to-end demo is a great starting point.\n", 668 | "(This repository also now has a Colab-ified version of the Golden Spike for convenience.)\n", 669 | "\n", 670 | "For many galaxy evolution applications, a template-based estimator would be more appropriate, as it could output a posterior $p(z, \\alpha | data)$, where $\\alpha$ could be parameters like SFR or stellar mass.\n", 671 | "There are a couple reasons why I'm omitting them from this tutorial:\n", 672 | "1. Storage of the multivariate posteriors $\\{p(z, \\alpha | data)\\}$ is nontrivial; there is no recommended compression scheme so no infrastructure for it in `qp` yet.\n", 673 | "2. Template-based estimators tend to have complicated setups due to needing data files for the physical information, i.e. templates, priors, etc.; the paths for these are a bit difficult to wrangle on Colab and I didn't leave enough time to prepare for it before this tutorial. XD" 674 | ] 675 | }, 676 | { 677 | "cell_type": "markdown", 678 | "metadata": { 679 | "id": "2ZsmK6L8v9OO" 680 | }, 681 | "source": [ 682 | "### Estimating photo-$z$ posterior PDFs with FlexCode\n", 683 | "\n", 684 | "\n", 685 | "Of the tested estimators in the aforementioned experiment, including ML and non-ML methods, the most promising was [`FlexCode`](https://github.com/tpospisi/FlexCode) ([Izbicki & Lee, 2017](https://arxiv.org/abs/1704.08095)), which also happens to be one of the easiest to install and apply as a standalone code, so we'll use it as an example of an estimator of photo-$z$ posteriors.\n", 686 | "\n", 687 | "A demonstration of `FlexCode` in the context of photo-$z$s can be found in [Dalmasso, et al 2019](https://arxiv.org/abs/1908.11523), with demos in `R` published on [GitHub](https://github.com/Mr8ND/cdetools_applications).\n", 688 | "We'll demonstrate it on the pzflow-based samples generated from the Happy/Teddy data sets.\n", 689 | "\n", 690 | "_This content is adapted from FlexCode's [Teddy tutorial](https://github.com/tpospisi/FlexCode/blob/master/tutorial/Flexcode-tutorial-teddy.ipynb), written by Nic Dalmasso (CMU)._" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "execution_count": null, 696 | "metadata": { 697 | "id": "MGZ8i_opZiFY" 698 | }, 699 | "outputs": [], 700 | "source": [ 701 | "n_grid = granularity\n", 702 | "\n", 703 | "# Select regression method\n", 704 | "from flexcode.regression_models import NN\n", 705 | "\n", 706 | "# Parameters\n", 707 | "basis_system = \"cosine\" # Basis system\n", 708 | "max_basis = 31 # Maximum number of basis. If the model is not tuned,\n", 709 | " # max_basis is set as number of basis\n", 710 | "\n", 711 | "n_estimators = 100\n", 712 | "criterion = 'mse'\n", 713 | "max_depth = 5\n", 714 | " \n", 715 | "# Regression Parameters \n", 716 | "# If a list is passed for any parameter automatic 5-fold CV is used to\n", 717 | "# determine the best parameter combination.\n", 718 | "params = {\"k\": 20}#[5, 10, 15, 20]} # A dictionary with method-specific regression parameters." 719 | ] 720 | }, 721 | { 722 | "cell_type": "markdown", 723 | "metadata": { 724 | "id": "udbXVbiDZwie" 725 | }, 726 | "source": [ 727 | "Let's try first with a representative training/validation set." 728 | ] 729 | }, 730 | { 731 | "cell_type": "code", 732 | "execution_count": null, 733 | "metadata": { 734 | "id": "kb0yIUIjXSJm" 735 | }, 736 | "outputs": [], 737 | "source": [ 738 | "x_orig = pd.read_csv('test_set_photometry.csv')[['r', 'u-g', 'g-r', 'r-i', 'i-z']].to_numpy()\n", 739 | "y_orig = pd.read_csv('test_set_redshifts.csv')[['redshift']].to_numpy()\n", 740 | "posteriors_orig = pd.DataFrame(np.load('test_set_posteriors.csv')).to_numpy()\n", 741 | "\n", 742 | "# n_samp = 10000\n", 743 | "from sklearn.model_selection import train_test_split\n", 744 | "x_train, x_test, y_train, y_test, posteriors_train, posteriors_test = train_test_split(x_orig, y_orig, posteriors_orig, \n", 745 | " train_size=2000, random_state=42)\n", 746 | "x_train, x_validation, y_train, y_validation, posteriors_train, posteriors_validation = train_test_split(x_train, y_train, posteriors_train, \n", 747 | " train_size=1000, random_state=42)" 748 | ] 749 | }, 750 | { 751 | "cell_type": "code", 752 | "execution_count": null, 753 | "metadata": { 754 | "id": "lo6J8wY7pb1U" 755 | }, 756 | "outputs": [], 757 | "source": [ 758 | "# Parameterize model\n", 759 | "model = flexcode.FlexCodeModel(NN, max_basis, basis_system, regression_params=params)\n", 760 | "\n", 761 | "# Fit model - this will also choose the optimal number of neighbors `k`\n", 762 | "model.fit(x_train, y_train)\n", 763 | "\n", 764 | "# Tune model - Select the best number of basis\n", 765 | "model.tune(x_validation, y_validation)\n", 766 | "\n", 767 | "# Predict new densities on grid\n", 768 | "cde_test, y_grid = model.predict(x_test, n_grid=n_grid)" 769 | ] 770 | }, 771 | { 772 | "cell_type": "markdown", 773 | "metadata": { 774 | "id": "jXNaeqy80cCc" 775 | }, 776 | "source": [ 777 | "We can examine one of the photo-$z$ posteriors estimated with the perfectly representative training/validation set." 778 | ] 779 | }, 780 | { 781 | "cell_type": "code", 782 | "execution_count": null, 783 | "metadata": { 784 | "id": "sQ8plrbNCoLn" 785 | }, 786 | "outputs": [], 787 | "source": [ 788 | "chosen = 9\n", 789 | "\n", 790 | "plt.plot(y_grid, cde_test[chosen], label='Estimated posterior')\n", 791 | "plt.plot(grid, posteriors_test[chosen], label='True posterior')\n", 792 | "plt.axvline(y_test[chosen], 0, 1, c='C3', label='True redshift')\n", 793 | "plt.legend()\n", 794 | "plt.xlabel(\"redshift\")\n", 795 | "plt.show()" 796 | ] 797 | }, 798 | { 799 | "cell_type": "markdown", 800 | "metadata": { 801 | "id": "fAF62sfOawmd" 802 | }, 803 | "source": [ 804 | "It looks pretty good!\n", 805 | "Now let's try training and validating with some Happy/Teddy data but estimating posteriors on the test set from the pzflow demo." 806 | ] 807 | }, 808 | { 809 | "cell_type": "code", 810 | "execution_count": null, 811 | "metadata": { 812 | "id": "aWljb73yRRlT" 813 | }, 814 | "outputs": [], 815 | "source": [ 816 | "y_train = pd.read_csv('teddyAredshifts.csv')['redshift'].to_numpy()\n", 817 | "x_train = pd.read_csv('teddyAphotometry.csv')[['r', 'u-g', 'g-r', 'r-i', 'i-z']].to_numpy()\n", 818 | "\n", 819 | "y_validation = pd.read_csv('teddyBredshifts.csv')['redshift'].to_numpy()\n", 820 | "x_validation = pd.read_csv('teddyBphotometry.csv')[['r', 'u-g', 'g-r', 'r-i', 'i-z']].to_numpy()\n", 821 | "\n", 822 | "# similar for TeddyC?" 823 | ] 824 | }, 825 | { 826 | "cell_type": "code", 827 | "execution_count": null, 828 | "metadata": { 829 | "id": "qmNhNgiIZp12" 830 | }, 831 | "outputs": [], 832 | "source": [ 833 | "# Parameterize model\n", 834 | "model = flexcode.FlexCodeModel(NN, max_basis, basis_system, regression_params=params)\n", 835 | "\n", 836 | "# Fit model - this will also choose the optimal number of neighbors `k`\n", 837 | "model.fit(x_train, y_train)\n", 838 | "\n", 839 | "# # # Tune model - Select the best number of basis\n", 840 | "model.tune(x_validation, y_validation)\n", 841 | "\n", 842 | "# # Predict new densities on grid\n", 843 | "cde_test_bias, y_grid_bias = model.predict(x_test, n_grid=n_grid)" 844 | ] 845 | }, 846 | { 847 | "cell_type": "code", 848 | "execution_count": null, 849 | "metadata": { 850 | "id": "IwnYgZL6aWUP" 851 | }, 852 | "outputs": [], 853 | "source": [ 854 | "plt.plot(y_grid_bias, cde_test_bias[chosen], label='Estimated posterior (biased training set)')\n", 855 | "plt.plot(y_grid, cde_test[chosen], label='Estimated posterior (unbiased training set)')\n", 856 | "plt.plot(grid, posteriors_test[chosen], label='True posterior')\n", 857 | "plt.axvline(y_test[chosen], 0, 1, c='C3', label='True redshift')\n", 858 | "plt.legend()\n", 859 | "plt.xlabel(\"redshift\")\n", 860 | "plt.show()" 861 | ] 862 | }, 863 | { 864 | "cell_type": "markdown", 865 | "metadata": { 866 | "id": "DS6e_O5z0cCf" 867 | }, 868 | "source": [ 869 | "As expected, the biased training and validation sets worsen the estimated posterior PDFs." 870 | ] 871 | }, 872 | { 873 | "cell_type": "markdown", 874 | "metadata": { 875 | "id": "6r3n6nO80cCf" 876 | }, 877 | "source": [ 878 | "### Challenge 2a\n", 879 | "\n", 880 | "Try retraining `FlexCode` and estimating photo-$z$ posteriors on different combinations of the data sets, as well as different hyperparameters of the estimator, so you have some options to compare.\n", 881 | "Hypothesize which test cases will perform well and which will not." 882 | ] 883 | }, 884 | { 885 | "cell_type": "code", 886 | "execution_count": null, 887 | "metadata": { 888 | "id": "MOazR3ZT0cCf" 889 | }, 890 | "outputs": [], 891 | "source": [] 892 | }, 893 | { 894 | "cell_type": "markdown", 895 | "metadata": { 896 | "id": "8AfY78ne0cCf" 897 | }, 898 | "source": [ 899 | "### Challenge 2b\n", 900 | "\n", 901 | "`trainZ` was the \"winner\" of the DESC PZ DC1 experiment by traditional metrics.\n", 902 | "The algorithm is simple: $\\hat{p}(z | \\vec{d}_{i}) = p(z | \\{d_{train}\\})$, i.e. each test set galaxy's estimated photo-$z$ posterior is the redshift distribution of the training set.\n", 903 | "Try implementing it here and saving the outputs for comparison." 904 | ] 905 | }, 906 | { 907 | "cell_type": "code", 908 | "execution_count": null, 909 | "metadata": { 910 | "id": "FrbFvclE0cCf" 911 | }, 912 | "outputs": [], 913 | "source": [] 914 | }, 915 | { 916 | "cell_type": "markdown", 917 | "source": [], 918 | "metadata": { 919 | "id": "B30Mv427j5td" 920 | } 921 | }, 922 | { 923 | "cell_type": "markdown", 924 | "source": [ 925 | "### Challenge 2c\n", 926 | "\n", 927 | "`pzflow` is itself an estimator, even though we used it as a forward model of mock data here.\n", 928 | "Try using one of the models trained earlier as an estimator for data generated by another model to see how it performs in the absence of representativity." 929 | ], 930 | "metadata": { 931 | "id": "fyh6M3qEj51R" 932 | } 933 | }, 934 | { 935 | "cell_type": "markdown", 936 | "source": [], 937 | "metadata": { 938 | "id": "4JswNJ2mkNOf" 939 | } 940 | }, 941 | { 942 | "cell_type": "markdown", 943 | "metadata": { 944 | "id": "fg4SzDIYiTGf" 945 | }, 946 | "source": [ 947 | "## 3. Evaluating the performance of estimated photo-$z$ posterior PDFs\n", 948 | "\n", 949 | "Once we have estimated photo-$z$ posterior PDFs, we need a way to determine if they're actually any good.\n", 950 | "Since the tutorial has only one method but multiple training/validation sets, that's all we can compare for now." 951 | ] 952 | }, 953 | { 954 | "cell_type": "markdown", 955 | "metadata": { 956 | "id": "3fQCmfJE0cCg" 957 | }, 958 | "source": [ 959 | "### Photo-$z$ point estimates (summary statistics)\n", 960 | "\n", 961 | "A lot of use cases of photo-$z$ data products accept only a point estimate $\\hat{z}$, so many science-motivated metrics will be defined in terms of the ultimate output of an analysis that ingests such point estimates." 962 | ] 963 | }, 964 | { 965 | "cell_type": "markdown", 966 | "metadata": { 967 | "id": "nsqLV2Pv0cCh" 968 | }, 969 | "source": [ 970 | "###Challenge 3a\n", 971 | "\n", 972 | "Implement a few scalar summary statistics from the PDFs, e.g. the mean, median, and mode.\n", 973 | "Derive those point estimates from the different sets of estimated photo-$z$ posteriors." 974 | ] 975 | }, 976 | { 977 | "cell_type": "code", 978 | "execution_count": null, 979 | "metadata": { 980 | "id": "Gj8IUMIa0cCh" 981 | }, 982 | "outputs": [], 983 | "source": [] 984 | }, 985 | { 986 | "cell_type": "markdown", 987 | "metadata": { 988 | "id": "HMurG0Pk0cCi" 989 | }, 990 | "source": [ 991 | "### Metrics of photo-$z$ point estimates and reference redshifts\n", 992 | "\n", 993 | "Traditional metrics of photo-$z$ data products compare the estimates $\\{\\hat{z}_{i}\\}$ to reference values, either true redshifts from a simulation or spectroscopic redshifts." 994 | ] 995 | }, 996 | { 997 | "cell_type": "markdown", 998 | "metadata": { 999 | "id": "5jSOjNf60cCh" 1000 | }, 1001 | "source": [ 1002 | "###Challenge 3b\n", 1003 | "\n", 1004 | "Make a scatterplot of the point estimates versus the true redshifts.\n", 1005 | "Include marginal histograms of the distributions of true and point-estimate redshifts." 1006 | ] 1007 | }, 1008 | { 1009 | "cell_type": "code", 1010 | "execution_count": null, 1011 | "metadata": { 1012 | "id": "Xj_-rnwt0cCi" 1013 | }, 1014 | "outputs": [], 1015 | "source": [] 1016 | }, 1017 | { 1018 | "cell_type": "markdown", 1019 | "metadata": { 1020 | "id": "nmR8iJII0cCi" 1021 | }, 1022 | "source": [ 1023 | "### Challenge 3c\n", 1024 | "\n", 1025 | "The _bias_ is usually defined as $\\frac{\\hat{z} - z_{true}}{1+z_{true}}$, although [Graham+18](http://stacks.iop.org/1538-3881/155/i=1/a=1) defines a \"robust\" version as $\\frac{\\hat{z} - z_{true}}{1+\\hat{z}}$.\n", 1026 | "Implement these, evaluate them on your test cases, and plot the results as histograms or averages in redshift bins." 1027 | ] 1028 | }, 1029 | { 1030 | "cell_type": "code", 1031 | "execution_count": null, 1032 | "metadata": { 1033 | "id": "JNLf29eo0cCi" 1034 | }, 1035 | "outputs": [], 1036 | "source": [] 1037 | }, 1038 | { 1039 | "cell_type": "markdown", 1040 | "metadata": { 1041 | "id": "_8PH_fAw0cCi" 1042 | }, 1043 | "source": [ 1044 | "### Challenge 3d\n", 1045 | "\n", 1046 | "The _scatter_ is usually defined as $\\sigma_{z} = \\frac{(\\hat{z} - z_{true})^{2}}{1+z_{true}}$.\n", 1047 | "Implement it, evaluate it on your test cases, and plot the results as histograms or averages in redshift bins." 1048 | ] 1049 | }, 1050 | { 1051 | "cell_type": "code", 1052 | "execution_count": null, 1053 | "metadata": { 1054 | "id": "Lw-qCpJX0cCj" 1055 | }, 1056 | "outputs": [], 1057 | "source": [] 1058 | }, 1059 | { 1060 | "cell_type": "markdown", 1061 | "metadata": { 1062 | "id": "2Pq5uDBh0cCk" 1063 | }, 1064 | "source": [ 1065 | "### Challenge 3e\n", 1066 | "The catastrophic outlier rate is defined as the fraction of galaxies for which $|\\hat{z} - z_{true}| > 3 * \\sigma_{z}$.\n", 1067 | "Implement it, calculate it on your test cases, and plot the results as histograms or averages in redshift bins." 1068 | ] 1069 | }, 1070 | { 1071 | "cell_type": "code", 1072 | "execution_count": null, 1073 | "metadata": { 1074 | "id": "Qi7AdQIm0cCk" 1075 | }, 1076 | "outputs": [], 1077 | "source": [] 1078 | }, 1079 | { 1080 | "cell_type": "markdown", 1081 | "metadata": { 1082 | "id": "FYd_evyhw3pC" 1083 | }, 1084 | "source": [ 1085 | "### Metrics of estimated photo-$z$ posteriors and reference redshifts\n", 1086 | "\n", 1087 | "First, let's try out a couple metrics of estimated photo-$z$ posteriors that do not require knowledge of the true photo-$z$ posteriors.\n", 1088 | "There's additional functionality for the case of having true redshifts but not true posteriors in [cdetools](https://github.com/tpospisi/cdetools) and [cde-diagnostics](https://github.com/zhao-david/CDE-diagnostics), but this should give a general idea." 1089 | ] 1090 | }, 1091 | { 1092 | "cell_type": "code", 1093 | "execution_count": null, 1094 | "metadata": { 1095 | "id": "L53A-iBubIvZ" 1096 | }, 1097 | "outputs": [], 1098 | "source": [ 1099 | "from cdetools import cde_loss, cdf_coverage, hpd_coverage" 1100 | ] 1101 | }, 1102 | { 1103 | "cell_type": "markdown", 1104 | "metadata": { 1105 | "id": "2sVDo_DLgGit" 1106 | }, 1107 | "source": [ 1108 | "The Probability Integral Transform (PIT) is defined as \n", 1109 | "\\begin{equation}\n", 1110 | "PIT = \\int_{-\\infty}^{z_{true}} p(z | \\vec{d}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi) dz .\n", 1111 | "\\end{equation}\n", 1112 | "A histogram of PIT values is commonly used to assess how consistent a population of photo-$z$ PDFs are with the true redshifts.\n", 1113 | "Ideally, it would be a uniform distribution, meaning N% of galaxies have their true redshift within the Nth percentile of their estimated photo-$z$ posterior PDF." 1114 | ] 1115 | }, 1116 | { 1117 | "cell_type": "code", 1118 | "execution_count": null, 1119 | "metadata": { 1120 | "id": "uCWuAkGWk2ik" 1121 | }, 1122 | "outputs": [], 1123 | "source": [ 1124 | "pit_values = cdf_coverage.cdf_coverage(cde_test, y_grid, y_test)\n", 1125 | "pit_values_bias = cdf_coverage.cdf_coverage(cde_test_bias, y_grid_bias, y_test)\n", 1126 | "\n", 1127 | "plt.hist(pit_values, alpha=0.5, bins=100, label='representative', density=True)\n", 1128 | "plt.hist(pit_values_bias, alpha=0.5, bins=100, label='biased', density=True)\n", 1129 | "# plt.ylim(0, 100)\n", 1130 | "plt.legend()\n", 1131 | "plt.xlabel('PIT')" 1132 | ] 1133 | }, 1134 | { 1135 | "cell_type": "markdown", 1136 | "metadata": { 1137 | "id": "nKxtSTGtlrbq" 1138 | }, 1139 | "source": [ 1140 | "The Highest Predictive Density (HPD) \n", 1141 | "\\begin{equation}\n", 1142 | "HPD = \\int_{z': p(z' | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi) \\geq p(z | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)} p(z' | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi) dz\n", 1143 | "\\end{equation}\n", 1144 | "is like the area of the PDF where it exceeds a given value.\n", 1145 | "Over a population, it would ideally be flat, like the PIT.\n", 1146 | "[A talk by David Zhao (CMU)](https://drive.google.com/file/d/1uvPtK_RcTUHEwt0ZYld41VKEPHnehWbN/view) has a lovely visualization of the HPD." 1147 | ] 1148 | }, 1149 | { 1150 | "cell_type": "code", 1151 | "execution_count": null, 1152 | "metadata": { 1153 | "id": "84WUFQ8rfVtZ" 1154 | }, 1155 | "outputs": [], 1156 | "source": [ 1157 | "hpd_cov = hpd_coverage.hpd_coverage(cde_test, y_grid, y_test)\n", 1158 | "hpd_cov_bias = hpd_coverage.hpd_coverage(cde_test_bias, y_grid_bias, y_test)\n", 1159 | "\n", 1160 | "plt.hist(hpd_cov, alpha=0.5, bins=100, label='representative', density=True)\n", 1161 | "plt.hist(hpd_cov_bias, alpha=0.5, bins=100, label='biased', density=True)\n", 1162 | "# plt.ylim(0, 100)\n", 1163 | "plt.legend()\n", 1164 | "plt.xlabel('HPD')" 1165 | ] 1166 | }, 1167 | { 1168 | "cell_type": "markdown", 1169 | "metadata": { 1170 | "id": "hgkvMM8enL48" 1171 | }, 1172 | "source": [ 1173 | "The CDE loss \n", 1174 | "\\begin{equation}\n", 1175 | "\\hat{L} = \\frac{1}{K} \\sum_{i=1}^{K} \\int \\left(p(z | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)\\right)^{2} dz - \\frac{2}{K} \\sum_{i=1}^{K} p(z_{i} | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)\n", 1176 | "\\end{equation}\n", 1177 | "approximates the true posterior from the estimated posterior evaluated at the true redshift.\n", 1178 | "It's explained quite well in [a talk by Nic Dalmasso (CMU)](https://www.dropbox.com/s/2r4tl4qv0iyqo9b/STAMPS_LSST_CDE_Tools_Presentation.pdf?dl=0).\n", 1179 | "A lower value indicates a better estimator." 1180 | ] 1181 | }, 1182 | { 1183 | "cell_type": "code", 1184 | "execution_count": null, 1185 | "metadata": { 1186 | "id": "aQq6sv7JV4bH" 1187 | }, 1188 | "outputs": [], 1189 | "source": [ 1190 | "print(cde_loss.cde_loss(cde_test, y_grid, y_test))\n", 1191 | "print(cde_loss.cde_loss(cde_test_bias, y_grid_bias, y_test))" 1192 | ] 1193 | }, 1194 | { 1195 | "cell_type": "markdown", 1196 | "source": [ 1197 | "### Challenge 3f\n", 1198 | "\n", 1199 | "The implementations of the PIT, HPD, and CDE Loss above are evaluated on just a subset of the possible combinations of priors (training sets), test set data, and estimator hyperparameters.\n", 1200 | "Evaluate them on the test cases you considered and compare them to the point estimate metrics.\n", 1201 | "Do they tell you the same thing or something different?" 1202 | ], 1203 | "metadata": { 1204 | "id": "y6koX3_FSzf9" 1205 | } 1206 | }, 1207 | { 1208 | "cell_type": "code", 1209 | "source": [], 1210 | "metadata": { 1211 | "id": "ECou4SgJiQXN" 1212 | }, 1213 | "execution_count": null, 1214 | "outputs": [] 1215 | }, 1216 | { 1217 | "cell_type": "markdown", 1218 | "metadata": { 1219 | "id": "HbTHU-y6xNKX" 1220 | }, 1221 | "source": [ 1222 | "### Comparison of estimated and true photo-$z$ posterior PDFs\n", 1223 | "\n", 1224 | "Of course what we really want to know is how well the estimator captures the uncertainty inherent to the photometric data, i.e. how well it approximates the true posterior PDF!\n", 1225 | "(Although we also want to know how that uncertainty quantification impacts \n", 1226 | "\n", 1227 | "`qp` [(Malz, et al 2018)](https://arxiv.org/abs/1806.00014) is a package for manipulating univariate PDFs under many parameterizations and includes a few comparison metrics.\n", 1228 | "We'll use [the new version of qp](https://github.com/LSSTDESC/qp) for the sake of speed but evaluate metrics using simplified functions ported from [the old version](https://github.com/aimalz/qp) for robustness (because the new qp still has some bugs in checking the normalization of PDFs, oops).\n", 1229 | "\n", 1230 | "_This content is adapted from the [qp demo](https://github.com/LSSTDESC/qp/blob/master/docs/notebooks/demo.ipynb), written by Alex Malz (CMU), Phil Marshall (SLAC), and Eric Charles (SLAC), and [qp metrics demo](https://github.com/LSSTDESC/qp/blob/master/docs/notebooks/kld.ipynb), written by Alex Malz (CMU) and Phil Marshall (SLAC)._" 1231 | ] 1232 | }, 1233 | { 1234 | "cell_type": "markdown", 1235 | "source": [ 1236 | "The first step is to get both the true posteriors and the approximations evaluated on the same grid of redshifts.\n", 1237 | "Note that some metrics in this category compare approximate and true PDFs as if they are arbitrary functions, whereas others rely on the fact that they are normalized with $p(z | \\vec{d}) \\geq 0$ and $\\int p(z | \\vec{d}) dz = 1$." 1238 | ], 1239 | "metadata": { 1240 | "id": "iQk_p13Fk0cN" 1241 | } 1242 | }, 1243 | { 1244 | "cell_type": "code", 1245 | "execution_count": null, 1246 | "metadata": { 1247 | "id": "-WARGQ6Gh-k_" 1248 | }, 1249 | "outputs": [], 1250 | "source": [ 1251 | "# P = qp.Ensemble(qp.interp, data=dict(xvals=grid.reshape(grid.shape[0]), yvals=posteriors_test))\n", 1252 | "Q = qp.Ensemble(qp.interp, data=dict(xvals=y_grid.reshape(y_grid.shape[0]), yvals=cde_test))\n", 1253 | "Q_bias = qp.Ensemble(qp.interp, data=dict(xvals=y_grid.reshape(y_grid_bias.shape[0]), yvals=cde_test_bias))\n", 1254 | "grid, approx_pdf_on_grid = Q.gridded(grid)\n", 1255 | "grid, approx_pdf_on_grid_bias = Q_bias.gridded(grid)" 1256 | ] 1257 | }, 1258 | { 1259 | "cell_type": "markdown", 1260 | "metadata": { 1261 | "id": "YR96wyRGPerk" 1262 | }, 1263 | "source": [ 1264 | "The root-mean-square-error (RMSE) is a symmetric measure commonly used to compare any 1D functions.\n", 1265 | "Similarly, a lower value corresponds to a more closely approximating posterior PDF." 1266 | ] 1267 | }, 1268 | { 1269 | "cell_type": "code", 1270 | "execution_count": null, 1271 | "metadata": { 1272 | "id": "lrtkIQZXwlMZ" 1273 | }, 1274 | "outputs": [], 1275 | "source": [ 1276 | "RMSEs = np.array([qp.metrics.quick_rmse(p, q, N=granularity) for p, q in zip(posteriors_test, approx_pdf_on_grid)])\n", 1277 | "RMSEs_bias = np.array([qp.metrics.quick_rmse(p, q, N=granularity) for p, q in zip(posteriors_test, approx_pdf_on_grid_bias)])\n", 1278 | "\n", 1279 | "plt.hist(np.log(RMSEs), alpha=0.5, bins=100, label='representative', density=True)\n", 1280 | "plt.hist(np.log(RMSEs_bias), alpha=0.5, bins=100, label='biased', density=True)\n", 1281 | "plt.xlabel('RMSE')\n", 1282 | "plt.legend()" 1283 | ] 1284 | }, 1285 | { 1286 | "cell_type": "markdown", 1287 | "metadata": { 1288 | "id": "ioNxxbaDoDEm" 1289 | }, 1290 | "source": [ 1291 | "The Kullback Leibler Divergence (KLD)\n", 1292 | "\\begin{equation}\n", 1293 | "KLD = \\int_{-\\infty}^{\\infty} p(z | \\vec{d}) \\log\\left[\\frac{p(z | \\vec{d}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)}{p(z | \\vec{d})}\\right] dz\n", 1294 | "\\end{equation}\n", 1295 | "is a directional measure of how much information is lost by using the estimated $p(z | \\vec{d}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)$ instead of the true $p(z | \\vec{d})$.\n", 1296 | "We want the KLD for each galaxy to be low." 1297 | ] 1298 | }, 1299 | { 1300 | "cell_type": "code", 1301 | "execution_count": null, 1302 | "metadata": { 1303 | "id": "J-J7YdTtLKPf" 1304 | }, 1305 | "outputs": [], 1306 | "source": [ 1307 | "KLDs = np.array([qp.metrics.quick_kld(p, q, dx=np.mean(grid[1:] - grid[:-1])) for p, q in zip(posteriors_test, approx_pdf_on_grid)])\n", 1308 | "KLDs_bias = np.array([qp.metrics.quick_kld(p, q, dx=np.mean(grid[1:] - grid[:-1])) for p, q in zip(posteriors_test, approx_pdf_on_grid_bias)])\n", 1309 | "\n", 1310 | "plt.hist(np.log(KLDs), alpha=0.5, bins=100, label='representative', density=True)\n", 1311 | "plt.hist(np.log(KLDs_bias), alpha=0.5, bins=100, label='biased', density=True)\n", 1312 | "plt.xlabel('KLD')\n", 1313 | "plt.legend()\n", 1314 | "plt.semilogy()" 1315 | ] 1316 | }, 1317 | { 1318 | "cell_type": "markdown", 1319 | "source": [ 1320 | "The appendix of [Malz+ (2018)](https://arxiv.org/abs/1806.00014) builds some intuition for the KLD in terms of the more familiar RMSE." 1321 | ], 1322 | "metadata": { 1323 | "id": "TuivxyEMq5jE" 1324 | } 1325 | }, 1326 | { 1327 | "cell_type": "markdown", 1328 | "source": [ 1329 | "### Challenge 3g\n", 1330 | "\n", 1331 | "Try out these metrics on the various estimator outputs on the different data sets, and interpret the results.\n", 1332 | "Why do different situations result in better or worse metric values?\n", 1333 | "Do the metrics have different sensitivity to each type of imperfection?" 1334 | ], 1335 | "metadata": { 1336 | "id": "jgjXqaUSrcE0" 1337 | } 1338 | }, 1339 | { 1340 | "cell_type": "code", 1341 | "source": [], 1342 | "metadata": { 1343 | "id": "nBspqcrPrwZS" 1344 | }, 1345 | "execution_count": null, 1346 | "outputs": [] 1347 | }, 1348 | { 1349 | "cell_type": "markdown", 1350 | "metadata": { 1351 | "id": "DTwhvAxUxVnf" 1352 | }, 1353 | "source": [ 1354 | "### Challenge 3h\n", 1355 | "\n", 1356 | "Apply and visualize the local metrics of [Zhao, Dalmasso, Izbicki & Lee, 2021](https://arxiv.org/abs/2102.10473), or any other metrics not included in this demo; the [cde-diagnostics tutorial](https://github.com/zhao-david/CDE-diagnostics/blob/main/tutorial/tutorial-cde-diagnostics.ipynb), written by David Zhao (CMU), may be a good starting point." 1357 | ] 1358 | }, 1359 | { 1360 | "cell_type": "code", 1361 | "execution_count": null, 1362 | "metadata": { 1363 | "id": "DIwztiqPpgMU" 1364 | }, 1365 | "outputs": [], 1366 | "source": [] 1367 | } 1368 | ], 1369 | "metadata": { 1370 | "colab": { 1371 | "provenance": [], 1372 | "toc_visible": true, 1373 | "include_colab_link": true 1374 | }, 1375 | "kernelspec": { 1376 | "display_name": "DSFP (Python 3)", 1377 | "language": "python", 1378 | "name": "dsfp_3" 1379 | }, 1380 | "language_info": { 1381 | "codemirror_mode": { 1382 | "name": "ipython", 1383 | "version": 3 1384 | }, 1385 | "file_extension": ".py", 1386 | "mimetype": "text/x-python", 1387 | "name": "python", 1388 | "nbconvert_exporter": "python", 1389 | "pygments_lexer": "ipython3", 1390 | "version": "3.10.4" 1391 | } 1392 | }, 1393 | "nbformat": 4, 1394 | "nbformat_minor": 0 1395 | } -------------------------------------------------------------------------------- /week-4/README.md: -------------------------------------------------------------------------------- 1 | # Week 4 Tutorial 2 | 3 | - **(2/8) Photo-z's and uncertainties thereof** [[Open in Colab]](https://colab.research.google.com/github/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-4/Malz_KITPCCA_photo-z_tutorial.ipynb) 4 | -------------------------------------------------------------------------------- /week-4/goldenspike_Colabified.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "view-in-github", 7 | "colab_type": "text" 8 | }, 9 | "source": [ 10 | "\"Open" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "minute-lender", 16 | "metadata": { 17 | "id": "minute-lender" 18 | }, 19 | "source": [ 20 | "# Goldenspike, an example of an end-to-end analysis using RAIL\n", 21 | "\n", 22 | "author: Sam Schmidt, Eric Charles, Alex Malz, John Franklin Crenshaw, others...
\n", 23 | "last run successfully: April 15, 2022\n", 24 | "\n", 25 | "This notebook demonstrates how to use a the various RAIL Modules to draw synthetic samples of fluxes by color, apply physical effects to them, train photo-Z estimators on the samples, test and validate the preformance of those estimators, and to use the RAIL summarization modules to obtain n(z) estimates based on the p(z) estimates.\n", 26 | "\n", 27 | "### Creation \n", 28 | "\n", 29 | "Note that in the parlance of the Creation Module, \"degradation\" is any post-processing that occurs to the \"true\" sample generated by the create Engine. This can include adding photometric errors, applying quality cuts, introducing systematic biases, etc.\n", 30 | "\n", 31 | "In this notebook, we will draw both test and training samples from a RAIL Engine object. Then we will demonstrate how to use RAIL degraders to apply effects to those samples.\n", 32 | "\n", 33 | "### Training and Estimation\n", 34 | "\n", 35 | "The RAIL Informer modules \"train\" or \"inform\" models used to estimate p(z) given band fluxes (and potentially other information).\n", 36 | "\n", 37 | "The RAIL Estimation modules then use those same models to actually apply the model and extract the p(z) estimates.\n", 38 | "\n", 39 | "### p(z) Validation \n", 40 | "\n", 41 | "The RAIL Validator module applies various metrics \n", 42 | "\n", 43 | "### p(z) to n(z) Summarization\n", 44 | "\n", 45 | "The RAIL Summarization modules convert per-galaxy p(z) posteriors to ensemble n(z) estimates. " 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "source": [ 51 | "### Installs (for Colab)" 52 | ], 53 | "metadata": { 54 | "id": "0IppZrEnOJ7T" 55 | }, 56 | "id": "0IppZrEnOJ7T" 57 | }, 58 | { 59 | "cell_type": "code", 60 | "source": [ 61 | "!pip install pz-rail pz-rail-hub\n", 62 | "!pip install git+https://github.com/lee-group-cmu/FlexCode" 63 | ], 64 | "metadata": { 65 | "id": "p3Bvt15Oh5H_" 66 | }, 67 | "id": "p3Bvt15Oh5H_", 68 | "execution_count": null, 69 | "outputs": [] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "id": "banner-migration", 74 | "metadata": { 75 | "id": "banner-migration" 76 | }, 77 | "source": [ 78 | "### Imports" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "id": "supreme-dietary", 85 | "metadata": { 86 | "id": "supreme-dietary" 87 | }, 88 | "outputs": [], 89 | "source": [ 90 | "# Prerquisites: os, numpy, pathlib, pzflow, tables_io\n", 91 | "import os\n", 92 | "import numpy as np\n", 93 | "from pathlib import Path\n", 94 | "from pzflow.examples import get_galaxy_data\n", 95 | "import tables_io" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "id": "material-funeral", 102 | "metadata": { 103 | "id": "material-funeral" 104 | }, 105 | "outputs": [], 106 | "source": [ 107 | "# Various rail modules\n", 108 | "import rail\n", 109 | "from rail.creation.degradation import LSSTErrorModel, InvRedshiftIncompleteness, LineConfusion, QuantityCut\n", 110 | "from rail.creation.engines.flowEngine import FlowModeler, FlowCreator, FlowPosterior\n", 111 | "from rail.core.data import TableHandle\n", 112 | "from rail.core.stage import RailStage\n", 113 | "from rail.core.utilStages import ColumnMapper, TableConverter\n", 114 | "\n", 115 | "from rail.estimation.algos.bpz_lite import Inform_BPZ_lite, BPZ_lite\n", 116 | "from rail.estimation.algos.knnpz import Inform_KNearNeighPDF, KNearNeighPDF\n", 117 | "from rail.estimation.algos.flexzboost import Inform_FZBoost, FZBoost\n", 118 | "\n", 119 | "from rail.estimation.algos.naiveStack import NaiveStack\n", 120 | "from rail.estimation.algos.pointEstimateHist import PointEstimateHist\n", 121 | "\n", 122 | "from rail.evaluation.evaluator import Evaluator\n", 123 | "\n" 124 | ] 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "id": "scheduled-chamber", 129 | "metadata": { 130 | "id": "scheduled-chamber" 131 | }, 132 | "source": [ 133 | "RAIL now uses ceci as a back-end, which takes care of a lot of file I/O decisions to be consistent with other choices in DESC.\n", 134 | "\n", 135 | "This bit effectively overrides a ceci default to prevent overwriting previous results, generally good but not necessary for this demo.\n", 136 | "\n", 137 | "The `DataStore` uses `DataHandle` objects to keep track of the connections between the various stages. When one stage returns a `DataHandle` and then you pass that `DataHandle` to another stage, the underlying code can establish the connections needed to build a reproducilble pipeline. " 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "id": "transparent-worship", 144 | "metadata": { 145 | "id": "transparent-worship" 146 | }, 147 | "outputs": [], 148 | "source": [ 149 | "DS = RailStage.data_store\n", 150 | "DS.__class__.allow_overwrite = True" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "id": "brief-institution", 156 | "metadata": { 157 | "id": "brief-institution" 158 | }, 159 | "source": [ 160 | "Here we need a few configuration parameters to deal with differences in data schema between existing PZ codes." 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "id": "finnish-southeast", 167 | "metadata": { 168 | "id": "finnish-southeast" 169 | }, 170 | "outputs": [], 171 | "source": [ 172 | "from rail.core.utils import RAILDIR\n", 173 | "flow_file = os.path.join(RAILDIR, 'examples/goldenspike/data/pretrained_flow.pkl')\n", 174 | "bands = ['u','g','r','i','z','y']\n", 175 | "band_dict = {band:f'mag_{band}_lsst' for band in bands}\n", 176 | "rename_dict = {f'mag_{band}_lsst_err':f'mag_err_{band}_lsst' for band in bands}" 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "id": "66494399", 182 | "metadata": { 183 | "id": "66494399" 184 | }, 185 | "source": [ 186 | "## Train the Flow Engine\n", 187 | "\n", 188 | "First we need to train the normalizing flow that will serve as the engine for the notebook.\n", 189 | "\n", 190 | "In the cell below, we load the example galaxy catalog from PZFlow and save it so that it can be used to train the flow. We also set the path where we will save the flow" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": null, 196 | "id": "aaa5f61a", 197 | "metadata": { 198 | "id": "aaa5f61a" 199 | }, 200 | "outputs": [], 201 | "source": [ 202 | "DATA_DIR = Path().resolve() / \"data\"\n", 203 | "DATA_DIR.mkdir(exist_ok=True)\n", 204 | "\n", 205 | "catalog_file = DATA_DIR / \"base_catalog.pq\"\n", 206 | "catalog = get_galaxy_data().rename(band_dict, axis=1)\n", 207 | "tables_io.write(catalog, str(catalog_file.with_suffix(\"\")), catalog_file.suffix[1:])\n", 208 | "\n", 209 | "catalog_file = str(catalog_file)\n", 210 | "flow_file = str(DATA_DIR / \"trained_flow.pkl\")" 211 | ] 212 | }, 213 | { 214 | "cell_type": "markdown", 215 | "id": "0cd8b319", 216 | "metadata": { 217 | "id": "0cd8b319" 218 | }, 219 | "source": [ 220 | "Now we set the parameters for the FlowModeler, i.e. the pipeline stage that trains the flow:" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "id": "424f2893", 227 | "metadata": { 228 | "id": "424f2893" 229 | }, 230 | "outputs": [], 231 | "source": [ 232 | "flow_modeler_params = {\n", 233 | " \"name\": \"flow_modeler\",\n", 234 | " \"input\": catalog_file,\n", 235 | " \"model\": flow_file,\n", 236 | " \"seed\": 0,\n", 237 | " \"phys_cols\": {\"redshift\": [0, 3]},\n", 238 | " \"phot_cols\": {\n", 239 | " \"mag_u_lsst\": [17, 35],\n", 240 | " \"mag_g_lsst\": [16, 32],\n", 241 | " \"mag_r_lsst\": [15, 30],\n", 242 | " \"mag_i_lsst\": [15, 30],\n", 243 | " \"mag_z_lsst\": [14, 29],\n", 244 | " \"mag_y_lsst\": [14, 28],\n", 245 | " },\n", 246 | " \"calc_colors\": {\"ref_column_name\": \"mag_i_lsst\"},\n", 247 | "}" 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "id": "2368b6b2", 253 | "metadata": { 254 | "id": "2368b6b2" 255 | }, 256 | "source": [ 257 | "Now we will create the flow and train it" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "id": "9a069fda", 264 | "metadata": { 265 | "id": "9a069fda" 266 | }, 267 | "outputs": [], 268 | "source": [ 269 | "flow_modeler = FlowModeler.make_stage(**flow_modeler_params)" 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": null, 275 | "id": "55d1b8d9", 276 | "metadata": { 277 | "id": "55d1b8d9" 278 | }, 279 | "outputs": [], 280 | "source": [ 281 | "flow_modeler.fit_model()" 282 | ] 283 | }, 284 | { 285 | "cell_type": "markdown", 286 | "id": "nonprofit-interference", 287 | "metadata": { 288 | "id": "nonprofit-interference" 289 | }, 290 | "source": [ 291 | "## Make mock data\n", 292 | "\n", 293 | "Now we will use the trained flow to create training and test data for the photo-z estimators.\n", 294 | "\n", 295 | "For both the training and test data we will:\n", 296 | "\n", 297 | "1. Use the Flow to produce some synthetic data\n", 298 | "2. Use the LSSTErrorModel to add photometric errors\n", 299 | "3. Use the FlowPosterior to estimate the redshift posteriors for the degraded sample\n", 300 | "4. Use the ColumnMapper to rename the error columns so that they match the names in DC2.\n", 301 | "5. Use the TableConverter to convert the data to a numpy dictionary, which will be stored in a hdf5 file with the same schema as the DC2 data\n", 302 | "\n", 303 | "### Training sample\n", 304 | "\n", 305 | "For the training data we are going to apply a couple of extra degradation effects to the data beyond what we do to create test data, as the training data will have some spectroscopic incompleteness. This will allow us to see how the trained models perform with imperfect training data.\n", 306 | "\n", 307 | "More details about the degraders are available in the `rail/examples/creation/degradation_demo.ipynb` notebook.\n" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": null, 313 | "id": "political-member", 314 | "metadata": { 315 | "id": "political-member" 316 | }, 317 | "outputs": [], 318 | "source": [ 319 | "flow_creator_train = FlowCreator.make_stage(\n", 320 | " name='flow_creator_train', \n", 321 | " model=flow_modeler.get_handle(\"model\"), \n", 322 | " n_samples=50,\n", 323 | " seed=1235,\n", 324 | ")\n", 325 | "\n", 326 | "lsst_error_model_train = LSSTErrorModel.make_stage(\n", 327 | " name='lsst_error_model_train',\n", 328 | " bandNames=band_dict, \n", 329 | " seed=29,\n", 330 | ")\n", 331 | "\n", 332 | "inv_redshift = InvRedshiftIncompleteness.make_stage(\n", 333 | " name='inv_redshift',\n", 334 | " pivot_redshift=1.0,\n", 335 | ")\n", 336 | "\n", 337 | "line_confusion = LineConfusion.make_stage(\n", 338 | " name='line_confusion', \n", 339 | " true_wavelen=5007., \n", 340 | " wrong_wavelen=3727.,\n", 341 | " frac_wrong=0.05,\n", 342 | ")\n", 343 | "\n", 344 | "quantity_cut = QuantityCut.make_stage(\n", 345 | " name='quantity_cut', \n", 346 | " cuts={'mag_i_lsst': 25.0},\n", 347 | ")\n", 348 | "\n", 349 | "col_remapper_train = ColumnMapper.make_stage(\n", 350 | " name='col_remapper_train', \n", 351 | " columns=rename_dict,\n", 352 | ")\n", 353 | " \n", 354 | "table_conv_train = TableConverter.make_stage(\n", 355 | " name='table_conv_train', \n", 356 | " output_format='numpyDict',\n", 357 | ")" 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": null, 363 | "id": "simple-bundle", 364 | "metadata": { 365 | "id": "simple-bundle" 366 | }, 367 | "outputs": [], 368 | "source": [ 369 | "train_data_orig = flow_creator_train.sample(150, 1235)\n", 370 | "train_data_errs = lsst_error_model_train(train_data_orig,seed=66)\n", 371 | "train_data_inc = inv_redshift(train_data_errs)\n", 372 | "train_data_conf = line_confusion(train_data_inc)\n", 373 | "train_data_cut = quantity_cut(train_data_conf)\n", 374 | "train_data_pq = col_remapper_train(train_data_cut)\n", 375 | "train_data = table_conv_train(train_data_pq)" 376 | ] 377 | }, 378 | { 379 | "cell_type": "markdown", 380 | "id": "above-portable", 381 | "metadata": { 382 | "id": "above-portable" 383 | }, 384 | "source": [ 385 | "Let's examine the quantities that we've generated, we'll use the handy `tables_io` package to temporarily write to a pandas dataframe for quick writeout of the columns:" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": null, 391 | "id": "functional-dollar", 392 | "metadata": { 393 | "id": "functional-dollar" 394 | }, 395 | "outputs": [], 396 | "source": [ 397 | "train_table = tables_io.convertObj(train_data.data, tables_io.types.PD_DATAFRAME)\n", 398 | "train_table.head()" 399 | ] 400 | }, 401 | { 402 | "cell_type": "markdown", 403 | "id": "clinical-pavilion", 404 | "metadata": { 405 | "id": "clinical-pavilion" 406 | }, 407 | "source": [ 408 | "You see that we've generated redshifts, ugrizy magnitudes, and magnitude errors with names that match those in the cosmoDC2_v1.1.4_image data." 409 | ] 410 | }, 411 | { 412 | "cell_type": "markdown", 413 | "id": "square-breeding", 414 | "metadata": { 415 | "id": "square-breeding" 416 | }, 417 | "source": [ 418 | "### Testing sample\n", 419 | "\n", 420 | "For the test sample we will:\n", 421 | "\n", 422 | "1. Use the Flow to produce some synthetic data\n", 423 | "2. Use the LSSTErrorModel to smear the data\n", 424 | "3. Use the FlowPosterior to estimate the redshift posteriors for the degraded sample\n", 425 | "4. Use ColumnMapper to rename some of the columns to match DC2\n", 426 | "5. Use the TableConverter to convert the data to a numpy dictionary, which will be stored in a hdf5 file with the same schema as the DC2 data" 427 | ] 428 | }, 429 | { 430 | "cell_type": "code", 431 | "execution_count": null, 432 | "id": "breathing-deficit", 433 | "metadata": { 434 | "id": "breathing-deficit" 435 | }, 436 | "outputs": [], 437 | "source": [ 438 | "flow_creator_test = FlowCreator.make_stage(\n", 439 | " name='flow_creator_test',\n", 440 | " model=flow_modeler.get_handle(\"model\"),\n", 441 | " n_samples=50,\n", 442 | ")\n", 443 | " \n", 444 | "lsst_error_model_test = LSSTErrorModel.make_stage(\n", 445 | " name='lsst_error_model_test',\n", 446 | " bandNames=band_dict,\n", 447 | ")\n", 448 | "\n", 449 | "flow_post_test = FlowPosterior.make_stage(\n", 450 | " name='flow_post_test',\n", 451 | " model=flow_modeler.get_handle(\"model\"),\n", 452 | " column='redshift',\n", 453 | " grid=np.linspace(0., 5., 21),\n", 454 | ")\n", 455 | " \n", 456 | "col_remapper_test = ColumnMapper.make_stage(\n", 457 | " name='col_remapper_test',\n", 458 | " columns=rename_dict,\n", 459 | " hdf5_groupname='',\n", 460 | ")\n", 461 | "\n", 462 | "table_conv_test = TableConverter.make_stage(\n", 463 | " name='table_conv_test', \n", 464 | " output_format='numpyDict',\n", 465 | ")\n" 466 | ] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": null, 471 | "id": "educational-windows", 472 | "metadata": { 473 | "id": "educational-windows" 474 | }, 475 | "outputs": [], 476 | "source": [ 477 | "test_data_orig = flow_creator_test.sample(150, 1234)\n", 478 | "test_data_errs = lsst_error_model_test(test_data_orig,seed=58)\n", 479 | "test_data_post = flow_post_test.get_posterior(test_data_errs, err_samples=None)\n", 480 | "test_data_pq = col_remapper_test(test_data_errs)\n", 481 | "test_data = table_conv_test(test_data_pq)" 482 | ] 483 | }, 484 | { 485 | "cell_type": "code", 486 | "execution_count": null, 487 | "id": "inclusive-effect", 488 | "metadata": { 489 | "id": "inclusive-effect" 490 | }, 491 | "outputs": [], 492 | "source": [ 493 | "test_table = tables_io.convertObj(test_data.data, tables_io.types.PD_DATAFRAME)\n", 494 | "test_table.head()" 495 | ] 496 | }, 497 | { 498 | "cell_type": "markdown", 499 | "id": "formal-camping", 500 | "metadata": { 501 | "id": "formal-camping" 502 | }, 503 | "source": [ 504 | "## \"Inform\" some estimators\n", 505 | "\n", 506 | "More details about the process of \"informing\" or \"training\" the models used by the estimators is available in the `rail/examples/estimation/RAIL_estimation_demo.ipynb` notebook.\n", 507 | "\n", 508 | "We use \"inform\" rather than \"train\" to generically refer to the preprocessing of any prior information.\n", 509 | "For a machine learning estimator, that prior information is a training set, but it can also be an SED template library for a template-fitting or hybrid estimator." 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "execution_count": null, 515 | "id": "accredited-circle", 516 | "metadata": { 517 | "id": "accredited-circle" 518 | }, 519 | "outputs": [], 520 | "source": [ 521 | "inform_bpz = Inform_BPZ_lite.make_stage(\n", 522 | " name=\"inform_bpz\",\n", 523 | " model=\"bpz.pkl\",\n", 524 | " hdf5_groupname=\"\",\n", 525 | ")\n", 526 | "\n", 527 | "inform_knn = Inform_KNearNeighPDF.make_stage(\n", 528 | " name='inform_knn', \n", 529 | " nondetect_val=np.nan,\n", 530 | " model='knnpz.pkl', \n", 531 | " hdf5_groupname='',\n", 532 | ")\n", 533 | "\n", 534 | "inform_fzboost = Inform_FZBoost.make_stage(\n", 535 | " name='inform_FZBoost', \n", 536 | " model='fzboost.pkl', \n", 537 | " hdf5_groupname='',\n", 538 | ")" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": null, 544 | "id": "great-verification", 545 | "metadata": { 546 | "id": "great-verification" 547 | }, 548 | "outputs": [], 549 | "source": [ 550 | "inform_bpz.inform(train_data)\n", 551 | "inform_knn.inform(train_data)\n", 552 | "inform_fzboost.inform(train_data)" 553 | ] 554 | }, 555 | { 556 | "cell_type": "markdown", 557 | "id": "colonial-trailer", 558 | "metadata": { 559 | "id": "colonial-trailer" 560 | }, 561 | "source": [ 562 | "## Estimate photo-z posteriors\n", 563 | "\n", 564 | "More details about the estimators is available in the `rail/examples/estimation/RAIL_estimation_demo.ipynb` notebook.\n", 565 | "\n", 566 | "`randomPZ` is a very simple class that does not actually predict a meaningful photo-z, instead it produces a randomly drawn Gaussian for each galaxy.
\n", 567 | "`trainZ` is our \"pathological\" estimator, it makes a PDF from a histogram of the training data and assigns that PDF to every galaxy.
\n", 568 | "`BPZ_lite` is a template-based code that outputs the posterior estimated given a specific template set and Bayesian prior. See Benitez (2000) for more details.
\n" 569 | ] 570 | }, 571 | { 572 | "cell_type": "code", 573 | "execution_count": null, 574 | "id": "electric-minute", 575 | "metadata": { 576 | "id": "electric-minute" 577 | }, 578 | "outputs": [], 579 | "source": [ 580 | "# There's currently a bug in BPZ's path settings so it can't find its template information, so let's skip that for now\n", 581 | "# estimate_bpz = BPZ_lite.make_stage(\n", 582 | "# name='estimate_bpz', \n", 583 | "# hdf5_groupname='', \n", 584 | "# model=inform_bpz.get_handle('model'),\n", 585 | "# )\n", 586 | "\n", 587 | "estimate_knn = KNearNeighPDF.make_stage(\n", 588 | " name='estimate_knn', \n", 589 | " hdf5_groupname='', \n", 590 | " nondetect_val=np.nan, \n", 591 | " model=inform_knn.get_handle('model'),\n", 592 | ")\n", 593 | "\n", 594 | "estimate_fzboost = FZBoost.make_stage(\n", 595 | " name='test_FZBoost', \n", 596 | " nondetect_val=np.nan,\n", 597 | " model=inform_fzboost.get_handle('model'), \n", 598 | " hdf5_groupname='',\n", 599 | " aliases=dict(input='test_data', output='fzboost_estim'),\n", 600 | ")" 601 | ] 602 | }, 603 | { 604 | "cell_type": "code", 605 | "execution_count": null, 606 | "id": "average-rental", 607 | "metadata": { 608 | "id": "average-rental" 609 | }, 610 | "outputs": [], 611 | "source": [ 612 | "knn_estimated = estimate_knn.estimate(test_data)\n", 613 | "fzboost_estimated = estimate_fzboost.estimate(test_data)\n", 614 | "# There's currently a bug in BPZ's path settings so it can't find its template information, so let's skip that for now\n", 615 | "# bpz_estimated = estimate_bpz.estimate(test_data)" 616 | ] 617 | }, 618 | { 619 | "cell_type": "markdown", 620 | "id": "right-mystery", 621 | "metadata": { 622 | "id": "right-mystery" 623 | }, 624 | "source": [ 625 | "## Evaluate the estimates\n", 626 | "\n", 627 | "Now we evaluate metrics on the estimates, separately for each estimator. \n", 628 | "\n", 629 | "Each call to the `Evaluator.evaluate` will create a table with the various performance metrics. \n", 630 | "We will store all of these tables in a dictionary, keyed by the name of the estimator." 631 | ] 632 | }, 633 | { 634 | "cell_type": "code", 635 | "execution_count": null, 636 | "id": "portuguese-graduate", 637 | "metadata": { 638 | "id": "portuguese-graduate" 639 | }, 640 | "outputs": [], 641 | "source": [ 642 | "# There's currently a bug in BPZ's path settings so it can't find its template information, so let's skip that for now\n", 643 | "eval_dict = dict(#bpz=bpz_estimated, \n", 644 | " fzboost=fzboost_estimated, knn=knn_estimated)\n", 645 | "truth = test_data_orig\n", 646 | "\n", 647 | "result_dict = {}\n", 648 | "for key, val in eval_dict.items():\n", 649 | " the_eval = Evaluator.make_stage(name=f'{key}_eval', truth=truth)\n", 650 | " result_dict[key] = the_eval.evaluate(val, truth)" 651 | ] 652 | }, 653 | { 654 | "cell_type": "markdown", 655 | "id": "danish-miller", 656 | "metadata": { 657 | "id": "danish-miller" 658 | }, 659 | "source": [ 660 | "The Pandas DataFrame output format conveniently makes human-readable printouts of the metrics. \n", 661 | "This next cell will convert everything to Pandas." 662 | ] 663 | }, 664 | { 665 | "cell_type": "code", 666 | "execution_count": null, 667 | "id": "constant-peripheral", 668 | "metadata": { 669 | "id": "constant-peripheral" 670 | }, 671 | "outputs": [], 672 | "source": [ 673 | "results_tables = {key:tables_io.convertObj(val.data, tables_io.types.PD_DATAFRAME) for key,val in result_dict.items()}" 674 | ] 675 | }, 676 | { 677 | "cell_type": "code", 678 | "execution_count": null, 679 | "id": "expanded-fellowship", 680 | "metadata": { 681 | "id": "expanded-fellowship" 682 | }, 683 | "outputs": [], 684 | "source": [ 685 | "results_tables['knn']" 686 | ] 687 | }, 688 | { 689 | "cell_type": "code", 690 | "execution_count": null, 691 | "id": "normal-alexandria", 692 | "metadata": { 693 | "id": "normal-alexandria" 694 | }, 695 | "outputs": [], 696 | "source": [ 697 | "results_tables['fzboost']" 698 | ] 699 | }, 700 | { 701 | "cell_type": "code", 702 | "execution_count": null, 703 | "id": "satisfied-intelligence", 704 | "metadata": { 705 | "id": "satisfied-intelligence" 706 | }, 707 | "outputs": [], 708 | "source": [ 709 | "# There's currently a bug in BPZ's path settings so it can't find its template information, so let's skip that for now\n", 710 | "# results_tables['bpz']" 711 | ] 712 | }, 713 | { 714 | "cell_type": "markdown", 715 | "id": "grave-speaking", 716 | "metadata": { 717 | "id": "grave-speaking" 718 | }, 719 | "source": [ 720 | "## Summarize the per-galaxy redshift constraints to make population-level distributions\n", 721 | "\n", 722 | "{introduce the summarizers}\n", 723 | "\n", 724 | "First we make the stages, then execute them, then plot the output." 725 | ] 726 | }, 727 | { 728 | "cell_type": "code", 729 | "execution_count": null, 730 | "id": "white-replacement", 731 | "metadata": { 732 | "id": "white-replacement" 733 | }, 734 | "outputs": [], 735 | "source": [ 736 | "point_estimate_test = PointEstimateHist.make_stage(name='point_estimate_test')\n", 737 | "naive_stack_test = NaiveStack.make_stage(name='naive_stack_test')" 738 | ] 739 | }, 740 | { 741 | "cell_type": "code", 742 | "execution_count": null, 743 | "id": "korean-guess", 744 | "metadata": { 745 | "id": "korean-guess" 746 | }, 747 | "outputs": [], 748 | "source": [ 749 | "point_estimate_ens = point_estimate_test.summarize(eval_dict['fzboost'])\n", 750 | "naive_stack_ens = naive_stack_test.summarize(eval_dict['fzboost'])" 751 | ] 752 | }, 753 | { 754 | "cell_type": "code", 755 | "execution_count": null, 756 | "id": "focused-puppy", 757 | "metadata": { 758 | "id": "focused-puppy" 759 | }, 760 | "outputs": [], 761 | "source": [ 762 | "_ = naive_stack_ens.data.plot_native(xlim=(0,3))" 763 | ] 764 | }, 765 | { 766 | "cell_type": "code", 767 | "execution_count": null, 768 | "id": "worthy-croatia", 769 | "metadata": { 770 | "id": "worthy-croatia" 771 | }, 772 | "outputs": [], 773 | "source": [ 774 | "_ = point_estimate_ens.data.plot_native(xlim=(0,3))" 775 | ] 776 | }, 777 | { 778 | "cell_type": "markdown", 779 | "id": "medical-preview", 780 | "metadata": { 781 | "id": "medical-preview" 782 | }, 783 | "source": [ 784 | "### Convert this to a `ceci` Pipeline\n", 785 | "\n", 786 | "Now that we have all these stages defined and configured, and that we have established the connections between them by passing `DataHandle` objects between them, we can build a `ceci` Pipeline.\n" 787 | ] 788 | }, 789 | { 790 | "cell_type": "code", 791 | "execution_count": null, 792 | "id": "neural-central", 793 | "metadata": { 794 | "id": "neural-central" 795 | }, 796 | "outputs": [], 797 | "source": [ 798 | "import ceci\n", 799 | "pipe = ceci.Pipeline.interactive()\n", 800 | "stages = [\n", 801 | " # train the flow\n", 802 | " flow_modeler,\n", 803 | " # create the training catalog\n", 804 | " flow_creator_train, lsst_error_model_train, inv_redshift,\n", 805 | " line_confusion, quantity_cut, col_remapper_train, table_conv_train,\n", 806 | " # create the test catalog\n", 807 | " flow_creator_test, lsst_error_model_test, col_remapper_test, table_conv_test,\n", 808 | " # inform the estimators\n", 809 | "# There's currently a bug in BPZ's path settings so it can't find its template information, so let's skip that for now\n", 810 | " # inform_bpz, \n", 811 | " inform_knn, inform_fzboost,\n", 812 | " # estimate posteriors\n", 813 | "# There's currently a bug in BPZ's path settings so it can't find its template information, so let's skip that for now\n", 814 | " # estimate_bpz, \n", 815 | " estimate_knn, estimate_fzboost,\n", 816 | " # estimate n(z), aka \"summarize\"\n", 817 | " point_estimate_test, naive_stack_test,\n", 818 | "]\n", 819 | "for stage in stages:\n", 820 | " pipe.add_stage(stage)" 821 | ] 822 | }, 823 | { 824 | "cell_type": "code", 825 | "execution_count": null, 826 | "id": "packed-chosen", 827 | "metadata": { 828 | "id": "packed-chosen" 829 | }, 830 | "outputs": [], 831 | "source": [ 832 | "pipe.initialize(dict(input=catalog_file), dict(output_dir='.', log_dir='.', resume=False), None)" 833 | ] 834 | }, 835 | { 836 | "cell_type": "code", 837 | "execution_count": null, 838 | "id": "academic-romance", 839 | "metadata": { 840 | "id": "academic-romance" 841 | }, 842 | "outputs": [], 843 | "source": [ 844 | "pipe.save('tmp_goldenspike.yml')" 845 | ] 846 | }, 847 | { 848 | "cell_type": "markdown", 849 | "id": "younger-testament", 850 | "metadata": { 851 | "id": "younger-testament" 852 | }, 853 | "source": [ 854 | "### Read back the pipeline and run it" 855 | ] 856 | }, 857 | { 858 | "cell_type": "code", 859 | "execution_count": null, 860 | "id": "israeli-workshop", 861 | "metadata": { 862 | "id": "israeli-workshop" 863 | }, 864 | "outputs": [], 865 | "source": [ 866 | "pr = ceci.Pipeline.read('tmp_goldenspike.yml')" 867 | ] 868 | }, 869 | { 870 | "cell_type": "code", 871 | "execution_count": null, 872 | "id": "danish-homeless", 873 | "metadata": { 874 | "id": "danish-homeless" 875 | }, 876 | "outputs": [], 877 | "source": [ 878 | "pr.run()" 879 | ] 880 | }, 881 | { 882 | "cell_type": "markdown", 883 | "id": "informational-performer", 884 | "metadata": { 885 | "id": "informational-performer" 886 | }, 887 | "source": [ 888 | "# Clean up:\n", 889 | "\n", 890 | "Finally, you'll notice that we've written a large number of temporary files in the course of running this demo, to delete these and clean up the directory just run the `cleanup.sh` script in this directory to delete the data files." 891 | ] 892 | }, 893 | { 894 | "cell_type": "code", 895 | "execution_count": null, 896 | "id": "racial-stocks", 897 | "metadata": { 898 | "id": "racial-stocks" 899 | }, 900 | "outputs": [], 901 | "source": [] 902 | }, 903 | { 904 | "cell_type": "code", 905 | "execution_count": null, 906 | "id": "eaca3af1-0732-4b67-a28a-c86dae19d008", 907 | "metadata": { 908 | "id": "eaca3af1-0732-4b67-a28a-c86dae19d008" 909 | }, 910 | "outputs": [], 911 | "source": [] 912 | } 913 | ], 914 | "metadata": { 915 | "kernelspec": { 916 | "display_name": "mvrail", 917 | "language": "python", 918 | "name": "mvrail" 919 | }, 920 | "language_info": { 921 | "codemirror_mode": { 922 | "name": "ipython", 923 | "version": 3 924 | }, 925 | "file_extension": ".py", 926 | "mimetype": "text/x-python", 927 | "name": "python", 928 | "nbconvert_exporter": "python", 929 | "pygments_lexer": "ipython3", 930 | "version": "3.9.13" 931 | }, 932 | "vscode": { 933 | "interpreter": { 934 | "hash": "3eb7d322b3189fc0d051e46971545e8423a3ccd97a3e6ee97c9e2a28f48eb9d8" 935 | } 936 | }, 937 | "colab": { 938 | "provenance": [], 939 | "include_colab_link": true 940 | } 941 | }, 942 | "nbformat": 4, 943 | "nbformat_minor": 5 944 | } -------------------------------------------------------------------------------- /week-4/teddyAflow.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataDrivenGalaxyEvolution/galevo23-tutorials/487503a8ac3b05cf8c017bab163880b8ff36e498/week-4/teddyAflow.pkl -------------------------------------------------------------------------------- /week-4/teddyBflow.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataDrivenGalaxyEvolution/galevo23-tutorials/487503a8ac3b05cf8c017bab163880b8ff36e498/week-4/teddyBflow.pkl -------------------------------------------------------------------------------- /week-4/teddyCflow.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataDrivenGalaxyEvolution/galevo23-tutorials/487503a8ac3b05cf8c017bab163880b8ff36e498/week-4/teddyCflow.pkl -------------------------------------------------------------------------------- /week-5/README.md: -------------------------------------------------------------------------------- 1 | # Week 5 Tutorial 2 | 3 | - **(2/8) Automatic differentiation and JAX** 4 | * [Slides](https://docs.google.com/presentation/d/1SbYVsBhM2h-zb355LC4RJpF33Ox9K8rP04dYH54t3wE/edit?usp=sharing) 5 | * [Notebook 1: JAX overview](https://github.com/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-5/jax_overview.ipynb) 6 | * [Notebook 2: diffmah demo](https://github.com/DataDrivenGalaxyEvolution/galevo23-tutorials/blob/main/week-5/jax_demo_diffmah.ipynb) 7 | * [diffmah model paper](https://astro.theoj.org/article/26991-a-differentiable-model-of-the-assembly-of-individual-and-populations-of-dark-matter-halos) 8 | -------------------------------------------------------------------------------- /week-6/README.md: -------------------------------------------------------------------------------- 1 | # Week 6 Tutorial 2 | 3 | - **(2/8) Probabilistic U-Nets** [[Open in Colab]](https://colab.research.google.com/github/mhsotoudeh/ProbUNet-Tutorial/blob/main/02%20Rescue%20The%20Randomness.ipynb) 4 | --------------------------------------------------------------------------------