From d5599f0c85de70f6c34a4d5160dc218a531b364b Mon Sep 17 00:00:00 2001 From: Luca Orlandi Date: Thu, 16 Apr 2026 15:52:12 +0200 Subject: [PATCH] Committing first version of the XMCTSGuard python package --- .gitignore | 11 + LICENSE | 674 +++++++++++ README.md | 81 ++ pyproject.toml | 50 + requirements.txt | 174 +++ src/XMCTSGuard/__init__.py | 10 + src/XMCTSGuard/analysis/__init__.py | 0 src/XMCTSGuard/analysis/processors.py | 143 +++ src/XMCTSGuard/engine/__init__.py | 7 + src/XMCTSGuard/engine/callbacks.py | 64 + src/XMCTSGuard/engine/dataset.py | 188 +++ src/XMCTSGuard/engine/model.py | 161 +++ src/XMCTSGuard/engine/optimization.py | 87 ++ src/XMCTSGuard/engine/pulse_dataset.py | 408 +++++++ src/XMCTSGuard/engine/train.py | 264 ++++ src/XMCTSGuard/engine/utils.py | 161 +++ src/XMCTSGuard/gui/__init__.py | 3 + src/XMCTSGuard/gui/helpers.py | 21 + src/XMCTSGuard/gui/main_window.py | 499 ++++++++ src/XMCTSGuard/gui/styles.py | 182 +++ src/XMCTSGuard/gui/widgets.py | 229 ++++ src/XMCTSGuard/gui/workers.py | 36 + src/XMCTSGuard/main.py | 28 + src/XMCTSGuard/utils.py | 250 ++++ src/XMCTSGuard/visualization/__init__.py | 0 src/XMCTSGuard/visualization/gui_plots.py | 0 src/XMCTSGuard/visualization/plots.py | 1330 +++++++++++++++++++++ src/XMCTSGuard/visualization/themes.py | 13 + tests/__init__.py | 0 29 files changed, 5074 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 pyproject.toml create mode 100644 requirements.txt create mode 100644 src/XMCTSGuard/__init__.py create mode 100644 src/XMCTSGuard/analysis/__init__.py create mode 100644 src/XMCTSGuard/analysis/processors.py create mode 100644 src/XMCTSGuard/engine/__init__.py create mode 100644 src/XMCTSGuard/engine/callbacks.py create mode 100644 src/XMCTSGuard/engine/dataset.py create mode 100644 src/XMCTSGuard/engine/model.py create mode 100644 src/XMCTSGuard/engine/optimization.py create mode 100644 src/XMCTSGuard/engine/pulse_dataset.py create mode 100644 src/XMCTSGuard/engine/train.py create mode 100644 src/XMCTSGuard/engine/utils.py create mode 100644 src/XMCTSGuard/gui/__init__.py create mode 100644 src/XMCTSGuard/gui/helpers.py create mode 100644 src/XMCTSGuard/gui/main_window.py create mode 100644 src/XMCTSGuard/gui/styles.py create mode 100644 src/XMCTSGuard/gui/widgets.py create mode 100644 src/XMCTSGuard/gui/workers.py create mode 100644 src/XMCTSGuard/main.py create mode 100644 src/XMCTSGuard/utils.py create mode 100644 src/XMCTSGuard/visualization/__init__.py create mode 100644 src/XMCTSGuard/visualization/gui_plots.py create mode 100644 src/XMCTSGuard/visualization/plots.py create mode 100644 src/XMCTSGuard/visualization/themes.py create mode 100644 tests/__init__.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc408b6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*.npy +*.npz +*.png +*.pdf +*.ckpt +*.yaml +*events* +__pycache__ +images +.ipynb_checkpoints* +*W7-X_QXT* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b18766b --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + This package can be used to detect and correct faults in SXR diagnostics + Copyright (C) 2026 Luca Orlandi + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4306f44 --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# XMCTS data cleaning +This repository contains a project to resolve the faults in the data acquisition of the XMCTS diagnostic of W7-X. + +## Getting started +First of all you should create a python environment to install all of the needed dependencies. +The recommended way is to use venv, one can create a venv by executing the following command: + +`python -m venv path\to\venv\env-name` + +Once the virtual enviroment has been created, one can install the package by moving inside the project main folder and executing the following command: + +`python -m build` + +follwing this, a folder called dist is created and one can then install the package by runnning: + +`python -m pip install dist/xmctsguard-vnum.tar.gz` + +where vnum is the current version of the package, starting from 0.1.0. + +Once this operation is completed all of the required libraries should have been installed and the package can be used. +For instance the gui can be called by executing the command XMCTSGuard-gui. + +## Structure +The project is structured in the following way: + +XMCTSGuard/ +├── src/ +│ └── XMCTSGuard/ +│ ├── __init__.py # Makes this a package +│ ├── main.py # Entry point to launch the GUI +│ │ +│ ├── gui/ # All Things Visual +│ │ ├── __init__.py +│ │ ├── main_window.py # Your Main Class +│ │ ├── widgets.py # Custom buttons, sliders, etc. +│ │ └── helpers.py # GUI-only helper functions +│ │ +│ ├── engine/ # The "Brain" (Neural Network) +│ │ ├── __init__.py +│ │ ├── model.py # The NN class +│ │ ├── trainer.py # Training logic +│ │ ├── database.py # Data loading +│ │ └── callbacks.py # Training monitors +│ │ +│ └── analysis/ # The Bridge +│ ├── __init__.py +│ └── processors.py # Functions that use the NN to analyze data +│ +├── data/ # Local storage for datasets (git-ignored) +├── tests/ # Your test files +├── pyproject.toml # Build config +└── README.md + +## Usage +The project leverages a neural network (NN) based on a AutoEncoder (AE) architecture, contained in engine/model.py to give an ansatz of what the correct brightness "profile" should look like. Subsequently, the correlation between the ansatz and the measured profile is computed, this gives a metric to understand the distance of the measured profile from the usual distribution of profiles in W7-X. Moreover, the ansatz for the profile is also used to compute the distance of each diode from the reconstructed brightness. Via a threshold on the residuals between these two curves, it is possible to highlight the outliers in the measured profile and correct their values knowing the gain ratio between the old pulse and the new pulse. + +Once the analysis is completed one can save (cache) the "new" data, using the same format of the qxtdataaccess gui, so that it is usable for other purposes. + +One can install the package on + +## Neural Network +The NN used in this project, previously introduced, is developed using the `lightning` python library ([lightning docs](https://lightning.ai/docs/overview/getting-started)), which is based on `pytorch`. + +All of the necessary code for the NN is contained in the src/app/engine folder. The model.py file contains the base file with the network structure, trainer.py contains the functions used for the neural network training and database.py has the data loader and dataset classes for file reading and manipulation to make them NN compliant. + +### Training +The training of the NN is done via running the script train.py in the enigine folder. There is a config dictionary with the various parameters it is possible to tweak for each running. Before training a database over which doing the training procedure should be created, this can be done by running the function `consolidate_pulses` contained in src/engine/pulse_dataset.py script The training procedure can be run by calling the `train_autoencoder` function in src/engine/train.py. Refer to this function documentation for more information. + +#### Attention +It may be that the trainig routine, if run locally on IPPs PCs, tries to select the available GPUs, even if it may not be posible to use them. +If this is the case, before running the training procedure, one should run the following command: + +`export CUDA_VISIBLE_DEVICES=''` + +in order to deselect the possibility of using said GPUs. + +### Jupyter Notebooks +This is a useful tool for exploring the code and see hands-on examples on how the various steps work together, however it can be messy inside a .git repository, in order to avoid embedding in the version control a great amount of useless data and plot, the use of the nbstripout package is strongly recommended. This package, a possible implementation can be found [here](https://pypi.org/project/nbstripout/) under the 'Using as a Git filter' section. + +### Notice +For any problems, doubts or error with the code, contact luca.orlandi@igi.cnr.it \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a039d72 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,50 @@ +[build-system] +requires = ["hatchling >= 1.26"] +build-backend = "hatchling.build" + +[project] +name = "XMCTSGuard" +version = "0.1.0" +description = "Anomaly detection and cleaning for XMCTS SXR data" +authors = [ + {name = "Luca Orlandi", email = "luca.orlandi@igi.cnr.it"} +] +readme = "README.md" +requires-python = ">=3.11" +license = {text = "GPL v3"} +license-files = ["LICEN[CS]E*"] + +# List your library dependencies here (what pip install will grab) +dependencies = [ + "numpy", + "scipy", + "matplotlib", + "seaborn", + "torch", + "lightning", + "PyQt6", + "h5py", + "umap-learn" +] + +[project.optional-dependencies] +# Dependencies for development and research notebooks +dev = [ + "pytest", + "jupyterlab", + "ipywidgets", +] + +[project.scripts] +# This creates a terminal command to launch your GUI! +# Format: command_name = "package.module:function" +XMCTSGuard-gui = "XMCTSGuard.main:start_app" + +# Project urls +[project.urls] +Homepage = "https://github.com/pypa/sampleproject" +Issues = "https://github.com/pypa/sampleproject/issues" + +[tool.setuptools.packages.find] +# Tells setuptools where to look for your code +where = ["src"] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..37924f3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,174 @@ +absl-py==2.4.0 +aiohappyeyeballs==2.6.1 +aiohttp==3.13.1 +aiosignal==1.4.0 +anyio==4.12.1 +argon2-cffi==25.1.0 +argon2-cffi-bindings==25.1.0 +arrow==1.4.0 +asttokens==3.0.1 +async-lru==2.1.0 +attrs==25.4.0 +babel==2.18.0 +beautifulsoup4==4.14.3 +bleach==6.3.0 +cbor==1.0.0 +certifi==2026.1.4 +cffi==2.0.0 +charset-normalizer==3.4.4 +comm==0.2.3 +contourpy==1.3.3 +cycler==0.12.1 +debugpy==1.8.20 +decorator==5.2.1 +defusedxml==0.7.1 +executing==2.2.1 +fastjsonschema==2.21.2 +filelock==3.20.0 +fonttools==4.60.1 +fqdn==1.5.1 +frozenlist==1.8.0 +fsspec==2025.9.0 +gevent==25.9.1 +greenlet==3.3.2 +grequests==0.7.0 +grpcio==1.80.0 +h11==0.16.0 +h5py==3.15.1 +httpcore==1.0.9 +httpx==0.28.1 +idna==3.11 +ImageIO==2.37.3 +ipykernel==7.2.0 +ipympl==0.10.0 +ipython==9.10.0 +ipython_pygments_lexers==1.1.1 +ipywidgets==8.1.8 +isoduration==20.11.0 +jedi==0.19.2 +Jinja2==3.1.6 +joblib==1.5.2 +json5==0.13.0 +jsonpointer==3.0.0 +jsonschema==4.26.0 +jsonschema-specifications==2025.9.1 +jupyter==1.1.1 +jupyter-console==6.6.3 +jupyter-events==0.12.0 +jupyter-lsp==2.3.0 +jupyter_client==8.8.0 +jupyter_core==5.9.1 +jupyter_server==2.17.0 +jupyter_server_terminals==0.5.4 +jupyterlab==4.5.4 +jupyterlab_pygments==0.3.0 +jupyterlab_server==2.28.0 +jupyterlab_widgets==3.0.16 +kiwisolver==1.4.9 +lark==1.3.1 +lazy-loader==0.5 +lightning==2.5.5 +lightning-utilities==0.15.2 +Markdown==3.10.2 +MarkupSafe==3.0.3 +matplotlib==3.10.7 +matplotlib-inline==0.2.1 +mistune==3.2.0 +mpmath==1.3.0 +multidict==6.7.0 +nbclient==0.10.4 +nbconvert==7.17.0 +nbformat==5.10.4 +nest-asyncio==1.6.0 +networkx==3.5 +notebook==7.5.3 +notebook_shim==0.2.4 +numpy==2.3.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.10.2.21 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.27.5 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.3.20 +nvidia-nvtx-cu12==12.8.90 +osa==0.2.3 +overrides==7.7.0 +packaging==25.0 +pandas==2.3.3 +pandocfilters==1.5.1 +parso==0.8.6 +pexpect==4.9.0 +pillow==12.0.0 +platformdirs==4.9.2 +prometheus_client==0.24.1 +prompt_toolkit==3.0.52 +propcache==0.4.1 +protobuf==6.33.5 +psutil==7.2.2 +ptyprocess==0.7.0 +pure_eval==0.2.3 +pycparser==3.0 +Pygments==2.19.2 +pyparsing==3.2.5 +PyQt5==5.15.11 +PyQt5-Qt5==5.15.18 +PyQt5_sip==12.18.0 +PyQt6==6.10.2 +PyQt6-Qt6==6.10.2 +PyQt6_sip==13.11.0 +python-dateutil==2.9.0.post0 +python-json-logger==4.0.0 +pytorch-lightning==2.5.5 +pytz==2025.2 +PyYAML==6.0.3 +pyzmq==27.1.0 +referencing==0.37.0 +requests==2.32.5 +rfc3339-validator==0.1.4 +rfc3986-validator==0.1.1 +rfc3987-syntax==1.1.0 +rpds-py==0.30.0 +scikit-image==0.26.0 +scikit-learn==1.7.2 +scipy==1.16.2 +seaborn==0.13.2 +Send2Trash==2.1.0 +six==1.17.0 +soupsieve==2.8.3 +stack-data==0.6.3 +sympy==1.14.0 +tensorboard==2.20.0 +tensorboard-data-server==0.7.2 +tensorboardX==2.6.4 +terminado==0.18.1 +threadpoolctl==3.6.0 +tifffile==2026.3.3 +tinycss2==1.4.0 +torch==2.9.0 +torchmetrics==1.8.2 +tornado==6.5.4 +tqdm==4.67.1 +traitlets==5.14.3 +triton==3.5.0 +typing_extensions==4.15.0 +tzdata==2025.2 +umap-learn==0.5.12 +uri-template==1.3.0 +urllib3==2.6.3 +wcwidth==0.6.0 +webcolors==25.10.0 +webencodings==0.5.1 +websocket-client==1.9.0 +Werkzeug==3.1.8 +widgetsnbextension==4.0.15 +yarl==1.22.0 +zope.event==6.1 +zope.interface==8.2 diff --git a/src/XMCTSGuard/__init__.py b/src/XMCTSGuard/__init__.py new file mode 100644 index 0000000..e2cc60d --- /dev/null +++ b/src/XMCTSGuard/__init__.py @@ -0,0 +1,10 @@ +# Hoisting the main entry points +from .main import start_app +from .engine.model import AutoEncoder + +# Metadata +__version__ = "0.1.0" +__author__ = "Luca Orlandi" + +# Defining what 'from my_app import *' does +__all__ = ["start_app", "AutoEncoder"] \ No newline at end of file diff --git a/src/XMCTSGuard/analysis/__init__.py b/src/XMCTSGuard/analysis/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/XMCTSGuard/analysis/processors.py b/src/XMCTSGuard/analysis/processors.py new file mode 100644 index 0000000..23046b1 --- /dev/null +++ b/src/XMCTSGuard/analysis/processors.py @@ -0,0 +1,143 @@ +import numpy as np +import torch +import gc +from ..engine.utils import reconstruct, pearson, detect_outliers_residual, fill_outlier_gaps, compute_correlation_series, apply_gain, reconstruct_only_batched +from ..engine.model import AutoEncoder + + +# ───────────────────────────────────────────────────────────────────────────── +# Core analysis (orchestration only — heavy lifting delegated to helpers) +# ───────────────────────────────────────────────────────────────────────────── + +def run_analysis(pid, model_path, min_data, max_data, gain_ratio, + z_thresh=0.2, + progress_cb=None): + import gc + import torch + + def _p(msg): + if progress_cb: + progress_cb(msg) + + # ── imports ─────────────────────────────────────────────────────────────── + try: + from ..utils import load_sxr_data + except ImportError as e: + raise ImportError( + f"Could not import project modules: {e}\n" + "Make sure 'model.py' and 'read_h5f.py' are on sys.path." + ) from e + + # ── model ───────────────────────────────────────────────────────────────── + _p("Loading model …") + model = AutoEncoder.load_from_checkpoint(model_path) + model.eval() + + # ── data ────────────────────────────────────────────────────────────────── + _p(f"Loading SXR data for PID {pid} …") + try: + data, fpath, data_dict = load_sxr_data(pid) + except Exception: + _p(f"Data for PID {pid} not found — launching data access GUI …") + try: + import gui_qxt_loader as gqxt + import subprocess + subprocess.run(["python", os.path.abspath(gqxt.__file__)]) + data, fpath, data_dict = load_sxr_data(pid) + except ImportError as e: + raise ImportError( + f"Could not import data access modules: {e}\n" + "Make sure 'gui_qxt_loader.py' is on sys.path." + ) from e + + timedata = data[0, :].astype(np.float32) + signals = data[1:, :].astype(np.float32) + diode_ref = data[152,:].astype(np.float32) + del data + gc.collect() + + diode_keys = [k for k in data_dict.keys() if k != "timedata"] + del data_dict + gc.collect() + + # ── reference time instant (peak emission) ──────────────────────────────── + max_emission = int(np.argmax(diode_ref)) + time_instant = float(timedata[max_emission]) + profile = signals[:, max_emission].copy() + n_diodes = len(profile) + x = np.arange(n_diodes) + + # ── original reconstruction (single profile snapshot) ──────────────────── + _p("Running model on original profile …") + rec_original = reconstruct(model, profile, min_data, max_data) + corr_original = pearson(profile, rec_original) + + # ── model-residuals outlier detection ───────────────────────────────────── + _p(f"Running model-residuals detection (z={z_thresh}) …") + outlier_mask = detect_outliers_residual(profile, rec_original, z_thresh) + outlier_mask = fill_outlier_gaps(outlier_mask, profile, tol=0.1) + mask = ~outlier_mask + _p(f"[Residuals] {int(outlier_mask.sum())} diodes flagged.") + + # ── gain-corrected single profile and its reconstruction ────────────────── + adjusted = apply_gain(profile, outlier_mask, gain_ratio) + rec_adjusted = reconstruct(model, adjusted, min_data, max_data) + corr_adjusted = pearson(adjusted, rec_adjusted) + + gc.collect() + + # ── downsampled time-series indices (for corr plot + spectral) ──────────── + step = max(10, signals.shape[1] // 500) + indices = np.arange(0, signals.shape[1], step) + + # ── correlation time-series (on original signals) ───────────────────────── + _p("Computing correlation time-series …") + correlations = compute_correlation_series( + model, signals, indices, min_data, max_data + ) + gc.collect() + + # ── snapshot for spectral analysis ──────────────────────────────────────── + signals_sampled = signals[:, indices].copy() + + # ── gain-corrected full time series (no model pass) ─────────────────────── + _p("Applying gain correction to full time-series …") + adjusted_full = signals.copy() + if gain_ratio > 1: + adjusted_full[~outlier_mask, :] *= gain_ratio + else: + adjusted_full[outlier_mask, :] *= gain_ratio + + # ── model reconstruction of the gain-corrected full time series ─────────── + _p("Running model on adjusted full time-series …") + rec_adjusted_full = reconstruct_only_batched( + model, adjusted_full, min_data, max_data + ) + gc.collect() + + _p("Done.") + return dict( + pid = pid, + time_instant = time_instant, + x = x, + timedata = timedata[indices], + timedata_full = timedata, + profile = profile, + rec_original = rec_original, + outlier_mask = outlier_mask, + gain_ratio = gain_ratio, + mask = mask, + adjusted = adjusted, + rec_adjusted = rec_adjusted, + adjusted_full = adjusted_full, + rec_adjusted_full = rec_adjusted_full, + corr_original = corr_original, + corr_adjusted = corr_adjusted, + correlations = correlations, + diode_signal = diode_ref[indices], + file_path = fpath, + diode_keys = diode_keys, + method = "residuals", + signals_sampled = signals_sampled, + z_thresh = z_thresh, + ) diff --git a/src/XMCTSGuard/engine/__init__.py b/src/XMCTSGuard/engine/__init__.py new file mode 100644 index 0000000..eda23b8 --- /dev/null +++ b/src/XMCTSGuard/engine/__init__.py @@ -0,0 +1,7 @@ +from .model import AutoEncoder, VariationalAutoEncoder +from .dataset import AEDataset, AEDataModule +from .pulse_dataset import PulseProfileDataset, PulseDataModule +from .train import train_autoencoder + +__all__ = ["AutoEncoder", "VariationalAutoEncoder", "AEDataset", "AEDataModule", + "PulseProfileDataset", "PulseDataModule", "train_autoencoder"] \ No newline at end of file diff --git a/src/XMCTSGuard/engine/callbacks.py b/src/XMCTSGuard/engine/callbacks.py new file mode 100644 index 0000000..ad869a1 --- /dev/null +++ b/src/XMCTSGuard/engine/callbacks.py @@ -0,0 +1,64 @@ +import torch +from lightning import Callback, LightningModule, Trainer +from lightning.pytorch.loggers import TensorBoardLogger +from lightning.pytorch.callbacks import EarlyStopping, LearningRateMonitor + +class SaveBest(Callback): + def __init__(self, monitor: str, logger: TensorBoardLogger) -> None: + super().__init__() + self.monitor = monitor + self.logger = logger + self.best_loss = float('inf') + + def on_validation_end(self, trainer: Trainer, pl_module: LightningModule) -> None: + loss = trainer.callback_metrics[self.monitor] + if loss < self.best_loss: + self.best_loss = loss + trainer.save_checkpoint(f"{self.logger.log_dir}/best_model_.ckpt") + return super().on_validation_end(trainer, pl_module) + + def on_train_end(self, trainer: Trainer, pl_module: LightningModule) -> None: + print(f"Best {self.monitor} loss: {self.best_loss}") + return super().on_train_end(trainer, pl_module) + +class SaveEveryNEpochs(Callback): + def __init__(self, n: int, logger: TensorBoardLogger) -> None: + super().__init__() + self.n = n + self.logger = logger + + def on_train_epoch_end(self, trainer: Trainer, pl_module: LightningModule) -> None: + if (trainer.current_epoch + 1) % self.n == 0: + trainer.save_checkpoint(f"{self.logger.log_dir}/epoch_{trainer.current_epoch + 1}.ckpt") + return super().on_train_epoch_end(trainer, pl_module) + +class PrintLearningRate(Callback): + def on_train_epoch_end(self, trainer: Trainer, pl_module: LightningModule) -> None: + optimizer = trainer.optimizers[0] + lr = optimizer.param_groups[0]['lr'] + print(f"Epoch {trainer.current_epoch + 1}: Learning Rate = {lr}") + return super().on_train_epoch_end(trainer, pl_module) + +class BetaWarmUp(Callback): + def __init__(self, start_epoch: int, initial_beta: float, final_beta: float, warmup_epochs: int) -> None: + super().__init__() + self.start_epoch = start_epoch + self.initial_beta = initial_beta + self.final_beta = final_beta + self.warmup_epochs = warmup_epochs + + def on_train_epoch_start(self, trainer: Trainer, pl_module: LightningModule) -> None: + if self.start_epoch <= trainer.current_epoch < self.start_epoch + self.warmup_epochs: + epoch_in_warmup = trainer.current_epoch - self.start_epoch + beta = self.initial_beta + (self.final_beta - self.initial_beta) * (epoch_in_warmup / self.warmup_epochs) + elif trainer.current_epoch >= self.start_epoch + self.warmup_epochs: + beta = self.final_beta + else: + beta = self.initial_beta + + if hasattr(pl_module, "set_beta"): + pl_module.set_beta(beta) + print(f"Epoch {trainer.current_epoch + 1}: Beta = {beta}") + else: + print("Warning: Model does not have a set_beta method.") + return super().on_train_epoch_start(trainer, pl_module) \ No newline at end of file diff --git a/src/XMCTSGuard/engine/dataset.py b/src/XMCTSGuard/engine/dataset.py new file mode 100644 index 0000000..61734ba --- /dev/null +++ b/src/XMCTSGuard/engine/dataset.py @@ -0,0 +1,188 @@ +import torch +import lightning as L +import numpy as np +from torch.utils.data import random_split, Dataset, DataLoader + +import os + + +class AEDataset(Dataset): + def __init__(self, profiles: torch.Tensor, pids: np.ndarray, times: np.ndarray, + cameras: np.ndarray, mag_confs: np.ndarray, clippings: np.ndarray): + self.profiles = profiles + self.pids = pids + self.times = times + self.cameras = cameras + self.mag_confs = mag_confs + self.clippings = clippings + + def __len__(self): + return len(self.profiles) + + def __getitem__(self, idx: int): + result = {'profile': self.profiles[idx]} + if self.pids is not None: + result['pid'] = self.pids[idx] + if self.times is not None: + result['time'] = self.times[idx] + if self.cameras is not None: + result['camera'] = self.cameras[idx] + if self.mag_confs is not None: + result['mag_conf'] = self.mag_confs[idx] + if self.clippings is not None: + result['clipping'] = self.clippings[idx] + return result + + +class AEDataModule(L.LightningDataModule): + def __init__(self, data_dir: str = '.', file_name: str = 'compressed_profiles.npz', batch_size: int = 32, normalization_strategy: str = 'minmax', nprofiles: int = None): + super().__init__() + self.data_dir = data_dir + self.file_name = file_name + self.batch_size = batch_size + self.normalization_strategy = normalization_strategy + self.nprofiles = nprofiles + self.data = None + + def prepare_data(self): + # Check if the file in data_dir exists otherwise create it calling the create_db method + path = os.path.join(self.data_dir, self.file_name) + if not os.path.exists(path): + print(f"The file {self.file_name} does not exist in path {self.data_dir}") + print("It can be created by calling the right functions in create_db.py.") + print("See the documentation there for more details") + # from create_db import create_database_time_instants, divide_by_camera + # divide_by_camera(data_dir=r"\\share\mp\E5-Praktikanten\Orlandi_Luca\_data\npz_files") + # create_database_time_instants(os.path.join(self.data_dir, self.file_name)) + + def setup(self, stage : str = None): + # Initialize a seed for all the randomic operations + generator = torch.Generator().manual_seed(42) # Seed for reproducibility + + if self.data is None: + # Load the dataset from the specified directory and file + self.data = np.load(f"{self.data_dir}/{self.file_name}") + + if self.nprofiles is None: + # Here the data is loaded in the correct format from the specified file + profiles = torch.tensor(self.data['profiles'], dtype=torch.float32) + pids = self.data['pids'] + times = self.data['times'] + cameras = self.data['cameras'] if 'cameras' in self.data else None + mag_confs = self.data['mag_confs'] if 'mag_confs' in self.data else None + clippings = self.data['clippings'] if 'clippings' in self.data else None + + else: + indices = torch.randperm(len(self.data['profiles']), generator=generator)[:self.nprofiles] + profiles = torch.tensor(self.data['profiles'][indices], dtype=torch.float32) + pids = self.data['pids'][indices] + times = self.data['times'][indices] + cameras = self.data['cameras'][indices] if 'cameras' in self.data else None + mag_confs = self.data['mag_confs'][indices] if 'mag_confs' in self.data else None + clippings = self.data['clippings'][indices] if 'clippings' in self.data else None + + # Normalize the data + profiles = self.normalize(profiles) + + # Initialize the Dataset + dataset = AEDataset(profiles, pids, times, cameras, mag_confs, clippings) + + # Create the dataset train, validation, and test splits + self.train_data, self.val_data, self.test_data = random_split( + dataset, [0.8, 0.1, 0.1], generator=generator,) + + def train_dataloader(self): + return DataLoader(self.train_data, batch_size=self.batch_size, drop_last=True) + + def val_dataloader(self): + return DataLoader(self.val_data, batch_size=self.batch_size, drop_last=True) + + def test_dataloader(self): + return DataLoader(self.test_data, batch_size=self.batch_size, drop_last=True) + + def normalize(self, data: torch.Tensor) -> torch.Tensor: + self.normalization = True + if self.normalization_strategy == 'minmax': + self.min_val = data.min() + self.max_val = data.max() + return (data - self.min_val) / (self.max_val - self.min_val) + elif self.normalization_strategy == 'zscore': + self.mean = data.mean() + self.std = data.std() + return (data - self.mean) / self.std + elif self.normalization_strategy == 'robust': + self.median = data.median() + self.iqr = data.quantile(0.75) - data.quantile(0.25) + return (data - self.median) / self.iqr + elif self.normalization_strategy == 'none': + return data + else: + raise ValueError(f"Unknown normalization strategy: {self.normalization_strategy}, accepted strategies are: minmax, zscore, robust, none") + + def denormalize(self, data: torch.Tensor) -> torch.Tensor: + if not self.normalization: + print("Data was not normalized, returning original data") + return data + if self.normalization_strategy == 'minmax': + return data * (self.max_val - self.min_val) + self.min_val + elif self.normalization_strategy == 'zscore': + return data * self.std + self.mean + elif self.normalization_strategy == 'robust': + return data * self.iqr + self.median + elif self.normalization_strategy == 'none': + return data + else: + raise ValueError(f"Unknown normalization strategy: {self.normalization_strategy}, accepted strategies are: minmax, zscore, robust, none") + + def divide_by_camera(self, camera_list: list = None) -> dict: + """ + Divides the input data by the camera. + + Args: + camera_list (list, optional): The list of cameras to divide the data in. + + Returns: + (dict): The modified data dictionary. + """ + # Load the raw data from the directory and filename + data = np.load(f"{self.data_dir}/{self.file_name}") + + # Create the lists to hold the divided data + profiles = [] + pids = [] + times = [] + camera_ids = [] + + # Define camera ranges + camera_ranges = { + '1A': (0, 17), '1B': (18, 35), '1C': (36, 53), '1D': (54, 71), '1E': (72, 89), + '2A': (90, 107), '2B': (108, 125), '2C': (126, 143), '2D': (144, 161), '2E': (162, 179), + '3A': (180, 197), '3B': (198, 215), '3C': (216, 233), '3D': (234, 251), '3E': (252, 269), + '4A': (270, 287), '4B': (288, 305), '4C': (306, 323), '4D': (324, 341), '4E': (342, 359) + } + + #Redefine the profiles arrangements + if camera_list is None: + camera_list = list(camera_ranges.keys()) + for profile in data["profiles"]: + for camera in camera_list: + if camera not in camera_ranges: # Check if camera is in the defined ranges and skip if not + continue + start, end = camera_ranges[camera] + profiles.append(profile[start:end]) # Append the sliced data for the current camera + pids.append(data["pids"]) + times.append(data["times"]) + camera_ids.append(camera) + + # Combine the lists into a dictionary + self.data = { + 'profiles': np.array(profiles), + 'pids': np.array(pids), + 'times': np.array(times), + 'camera_ids': np.array(camera_ids) + } + + # save the file to an npz + print("Saving divided data by camera to npz file...") + np.savez_compressed(f"{self.data_dir}/db_by_camera.npz", **self.data) + print("Data saved successfully.") \ No newline at end of file diff --git a/src/XMCTSGuard/engine/model.py b/src/XMCTSGuard/engine/model.py new file mode 100644 index 0000000..155f38d --- /dev/null +++ b/src/XMCTSGuard/engine/model.py @@ -0,0 +1,161 @@ +import torch +import torch.nn as nn +import lightning as L + + +class AutoEncoder(L.LightningModule): + def __init__(self, input_dim, geometry, learning_rate=1e-3, activation=torch.nn.ReLU()): + super().__init__() + self.input_dim = input_dim + self.geometry = geometry + self.learning_rate = learning_rate + self.activation = activation + self.save_hyperparameters(ignore=['activation']) + + assert len(geometry) >= 2, "Geometry must have at least two elements: hidden and latent sizes" + + # --- Encoder --- + self.encoder = nn.Sequential() + in_dim = input_dim + for i, out_dim in enumerate(geometry[:-1]): + self.encoder.add_module(f"encoder_layer_{i}", nn.Linear(in_dim, out_dim)) + # self.encoder.add_module(f"encoder_batchnorm_{i}", nn.BatchNorm1d(out_dim)) # serve per l'ampiezza (batch) + # self.encoder.add_module(f"encoder_regularization_{i}", nn.L1Loss()) + # self.encoder.add_module(f"encoder_dropout_{i}", nn.Dropout(0.2)) + self.encoder.add_module(f"encoder_activation_{i}", activation) + in_dim = out_dim + self.encoder.add_module("encoder_output_layer", nn.Linear(in_dim, geometry[-1])) + + # --- Decoder (mirror of encoder) --- + self.decoder = nn.Sequential() + reversed_geometry = list(reversed(geometry)) + in_dim = reversed_geometry[0] + for i, out_dim in enumerate(reversed_geometry[1:]): + self.decoder.add_module(f"decoder_layer_{i}", nn.Linear(in_dim, out_dim)) + self.decoder.add_module(f"decoder_activation_{i}", activation) + in_dim = out_dim + self.decoder.add_module("decoder_output_layer", nn.Linear(in_dim, input_dim)) + + def encode(self, x): + return self.encoder(x) + + def decode(self, z): + return self.decoder(z) + + def forward(self, x): + return self.decode(self.encode(x)) + + def reconstruct(self, x): + return self.forward(x) + + def _common_step(self, batch, step="train"): + x = batch # use batch['profile'] if the datamodule is AEDataModule + reconstructed = self.forward(x) + loss = self.loss_function(reconstructed, x) + self.log_dict({f"{step}/loss": loss,}, batch_size=x.size(0)) + return loss + + def training_step(self, batch, batch_idx): + return self._common_step(batch, step="train") + + def validation_step(self, batch, batch_idx): + return self._common_step(batch, step="val") + + def test_step(self, batch, batch_idx): + return self._common_step(batch, step="test") + + def loss_function(self, reconstructed, original): + return torch.nn.functional.mse_loss(reconstructed, original) + + def configure_optimizers(self): + return torch.optim.Adam(self.parameters(), lr=self.learning_rate) + + +class VariationalAutoEncoder(L.LightningModule): + def __init__(self, input_dim, geometry, beta=4, learning_rate=1e-3, activation=torch.nn.ReLU()): + """ + Args: + geometry (list[int]): List of layer sizes, e.g. [784, 256, 64, 16] + beta (float): Weighting factor for the KL divergence loss + learning_rate (float): Learning rate for the optimizer + activation (nn.Module): Activation function to use between layers + """ + super().__init__() + self.input_dim = input_dim + self.geometry = geometry + self.set_beta(beta) + self.learning_rate = learning_rate + self.activation = activation + self.save_hyperparameters() + + assert len(self.geometry) >= 2, "Geometry must have at least input and latent size" + + # Build encoder + self.encoder = nn.Sequential() + self.encoder.add_module("encoder_input_layer", nn.Linear(self.input_dim, self.geometry[0])) + self.encoder.add_module("encoder_input_activation", self.activation) + for i, (in_dim, out_dim) in enumerate(zip(self.geometry[:-1], self.geometry[1:])): + self.encoder.add_module(f"encoder_layer_{i}", nn.Linear(in_dim, out_dim)) + self.encoder.add_module(f"encoder_activation_{i}", self.activation) + + self.fc_mu = nn.Linear(self.geometry[-1], self.geometry[-1]//2) + self.fc_logvar = nn.Linear(self.geometry[-1], self.geometry[-1]//2) + + # Build decoder (mirror of encoder) + self.decoder_input = nn.Linear(self.geometry[-1]//2, self.geometry[-1]) + self.decoder = nn.Sequential() + for i, (in_dim, out_dim) in enumerate(zip(reversed(self.geometry[1:]), reversed(self.geometry[:-1]))): + self.decoder.add_module(f"decoder_layer_{len(self.geometry) - i - 1}", nn.Linear(in_dim, out_dim)) + self.decoder.add_module(f"decoder_activation_{len(self.geometry) - i - 1}", self.activation) + self.decoder.add_module("decoder_output_layer", nn.Linear(self.geometry[0], self.input_dim)) + + def encode(self, x): + h = self.encoder(x) + mu = self.fc_mu(h) + logvar = self.fc_logvar(h) + return mu, logvar + + def reparametrize(self, mu, logvar): + std = torch.exp(0.5 * logvar) + eps = torch.randn_like(std) + return mu + eps * std + + def decode(self, z): + h = self.decoder_input(z) + return self.decoder(h) + + def forward(self, x): + mu, logvar = self.encode(x) + z = self.reparametrize(mu, logvar) + y = self.decode(z) + return y, mu, logvar + + def set_beta(self, beta): + self.beta = beta + + def _common_step(self, batch, step="train"): + x = batch['profile'] + reconstructed, mu, logvar = self.forward(x) + loss, mse, kl = self.loss_function(reconstructed, x, mu, logvar) + self.log_dict({f"{step}/loss": loss, f"{step}/mse": mse, f"{step}/kl": kl}) + return loss + + def training_step(self, batch, batch_idx): + return self._common_step(batch, step="train") + + def validation_step(self, batch, batch_idx): + return self._common_step(batch, step="val") + + def test_step(self, batch, batch_idx): + return self._common_step(batch, step="test") + + def loss_function(self, reconstructed, original, mu, logvar): + # Reconstruction loss (MSE) + mse = torch.nn.functional.mse_loss(reconstructed, original) + # KL divergence loss + kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) + return mse + self.beta * kl, mse, kl + + def configure_optimizers(self): + return torch.optim.Adam(self.parameters(), lr=self.learning_rate) + diff --git a/src/XMCTSGuard/engine/optimization.py b/src/XMCTSGuard/engine/optimization.py new file mode 100644 index 0000000..db15262 --- /dev/null +++ b/src/XMCTSGuard/engine/optimization.py @@ -0,0 +1,87 @@ +import optuna +import lightning as L +import torch + +# ------------- Seed everything ------------- +L.seed_everything(42) # Lightning helper for deterministic runs +torch.backends.cudnn.deterministic = True +torch.backends.cudnn.benchmark = False + + +from model import AutoEncoder +from dataset import AEDataModule +from lightning.pytorch.loggers import TensorBoardLogger +from lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping +from lightning.pytorch import Trainer + +class Objective: + def __init__(self, data_module: AEDataModule, input_dim: int): + self.data_module = data_module + self.input_dim = input_dim + + def __call__(self, trial): + # Suggest hyperparameters + learning_rate = trial.suggest_float('learning_rate', 1e-5, 1e-2) + hidden_size_0 = trial.suggest_categorical('hidden_size_0', [64, 128, 256, 512, 1024]) + hidden_size_1 = trial.suggest_categorical('hidden_size_1', [64, 128, 256, 512, 1024]) + hidden_size_2 = trial.suggest_categorical('hidden_size_2', [64, 128, 256, 512, 1024]) + hidden_size_3 = trial.suggest_categorical('hidden_size_3', [64, 128, 256, 512, 1024]) + latent_size = trial.suggest_categorical('latent_size', [4, 8, 16, 32, 64, 128, 256]) + geometry = [hidden_size_0, hidden_size_1, hidden_size_2, latent_size] + + # Initialize model + model = AutoEncoder(input_dim=self.input_dim, geometry=geometry, learning_rate=learning_rate) + + # Logger + logger = TensorBoardLogger("OOptuna", name=f"4layers/trial_{trial.number}") + + # Callbacks + checkpoint_callback = ModelCheckpoint( + monitor='val/loss', + dirpath='checkpoints', + filename=f'4layers/trial_{trial.number}' + '-{epoch:02d}-{val/loss:.4f}', + save_top_k=1, + mode='min', + ) + early_stopping_callback = EarlyStopping( + monitor='val/loss', + patience=5, + mode='min' + ) + + # Trainer + trainer = Trainer( + max_epochs=50, + logger=logger, + callbacks=[checkpoint_callback, early_stopping_callback], + accelerator='auto', + devices='auto' + ) + + # Train the model + trainer.fit(model, self.data_module) + + # Return the best validation loss + return checkpoint_callback.best_model_score.item() + +if __name__ == "__main__": + # Data module + data_module = AEDataModule(data_dir='data', file_name='profs_w_magclip.npz', + batch_size=64, normalization_strategy='minmax', nprofiles=100_000) + data_module.prepare_data() + data_module.setup() + + # Input dimension + sample_batch = next(iter(data_module.train_dataloader())) + input_dim = sample_batch['profile'].shape[1] + + # Optuna study + study = optuna.create_study(direction='minimize') + study.optimize(Objective(data_module, input_dim), n_trials=200) + + print("Best trial:") + trial = study.best_trial + print(f" Value: {trial.value}") + print(" Params: ") + for key, value in trial.params.items(): + print(f" {key}: {value}") \ No newline at end of file diff --git a/src/XMCTSGuard/engine/pulse_dataset.py b/src/XMCTSGuard/engine/pulse_dataset.py new file mode 100644 index 0000000..3e57d2e --- /dev/null +++ b/src/XMCTSGuard/engine/pulse_dataset.py @@ -0,0 +1,408 @@ +""" +PulseDataModule — per-frame [360] profile sampling for PyTorch Lightning. + +WORKFLOW +-------- +1. Run consolidate_pulses() ONCE to merge each pulse's 360 .h5f files into + a single memory-mapped [T x 360] float32 .npz file per pulse. + +2. Use PulseDataModule normally in your Lightning Trainer. + Each sample returned is a 1-D tensor of shape [360] — one angular profile + at one timestep. + +WHY CONSOLIDATION? +------------------ +With T > 100 000 timesteps, opening 360 files per __getitem__ call would cost +~360 ms per sample — completely impractical. Memory-mapped .npz files let the +OS page-cache serve random timestep reads at RAM speed after the first epoch +warm-up, with no per-sample file-open overhead. + +DIRECTORY LAYOUT (input) +------------------------ +root/ +├── pulse001/ +│ ├── 000.h5f (degree 0) +│ ├── 001.h5f (degree 1) +│ └── ... (up to 359.h5f) +├── pulse002/ +│ └── ... +└── pulseN/ + +DIRECTORY LAYOUT (after consolidation) +--------------------------------------- +consolidated/ +├── pulse001.npz contains "data" array of shape [T, 361], float32 +├── pulse002.npz +└── pulseN.npz +""" + +from __future__ import annotations + +import random +import time +from pathlib import Path +from typing import Callable, Optional +import re + +import h5py +import numpy as np +import torch +from torch.utils.data import DataLoader, Dataset +import lightning as L + + +# --------------------------------------------------------------------------- +# Step 1 — one-time consolidation +# --------------------------------------------------------------------------- + +def consolidate_pulses( + root: str | Path, + out_dir: str | Path, + data_key: str = "XMCTSdata", + dtype: np.dtype = np.float32, + overwrite: bool = False, + decimation_factor: int = 1, # <--- Added parameter +) -> None: + """ + For each pulse directory, stack its 360 .h5f files into a single + memory-mappable [T x 361] .npz file. + + Files within a pulse are sorted lexicographically, so name them so that + sort order == degree order (e.g. 000.h5f ... 359.h5f). + + Args: + root: root data directory containing pulse sub-directories. + out_dir: where to write the consolidated .npz files. + data_key: HDF5 dataset key inside each file. + dtype: output dtype (float32 recommended; halves storage vs float64). + overwrite: if False, skips pulses whose .npz already exists. + decimation_factor: Keep only every N-th timestep (default 1 means keep all). + """ + root = Path(root) + out_dir = Path(out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + pulse_dirs = sorted(p for p in root.iterdir() if p.is_dir()) + print(f"Consolidating {len(pulse_dirs)} pulses -> {out_dir} with decimation={decimation_factor}") + + pattern = re.compile(r"t(000|090|180|270)$") + + for i, pulse_dir in enumerate(pulse_dirs): + out_path = out_dir / f"{pulse_dir.name}.npz" + print(out_path) + + if out_path.exists() and not overwrite: + print(f" [{i+1}/{len(pulse_dirs)}] {pulse_dir.name} -- skipped (already exists)") + continue + + times = sorted([ + f for f in pulse_dir.glob("*.h5f") + if pattern.search(f.stem) + ]) + h5_files = sorted([ + f for f in pulse_dir.glob("*.h5f") + if not pattern.search(f.stem) + ]) + if not h5_files: + print(f" [{i+1}/{len(pulse_dirs)}] {pulse_dir.name} -- skipped (no .h5f files)") + continue + + t0 = time.perf_counter() + + # Read the first time files to get the original length T + length = np.inf + for h5_path in times: + with h5py.File(h5_path, "r") as f: + # We can load the whole time array to check its length first + tmp_time = np.asarray(f[data_key][str(h5_path)[-7:-4]], dtype=dtype) + if length > tmp_time.shape[0]: + # Apply decimation right away to the stored time array + time_arr = tmp_time[::decimation_factor] + length = tmp_time.shape[0] + + T_original = length + T_decimated = time_arr.shape[0] + + # Allocate output with the new decimated T dimension + matrix = np.empty((T_decimated, 361), dtype=dtype) + matrix[:, 0] = time_arr + + for col, h5_path in enumerate(h5_files): + with h5py.File(h5_path, "r") as f: + # Slice the dataset directly inside HDF5: [:T_original:decimation_factor] + # This only reads the needed values from disk into RAM. + dataset = f[data_key][str(h5_path)[-7:-4]] + decimated_col = np.asarray(dataset[:T_original:decimation_factor], dtype=dtype) + + matrix[:, col + 1] = decimated_col + + np.savez_compressed(out_path, data=matrix) + elapsed = time.perf_counter() - t0 + size_mb = matrix.nbytes / 1024**2 + print( + f" [{i+1}/{len(pulse_dirs)}] {pulse_dir.name}" + f" -> {out_path.name} shape={matrix.shape}" + f" {size_mb:.0f} MB {elapsed:.1f}s" + ) + +# --------------------------------------------------------------------------- +# Step 2 — Dataset +# --------------------------------------------------------------------------- + + +class MinMaxNormalize: + """ + Scales tensor values to the range [0, 1]. + + If global_min and global_max are provided, it performs Global Normalization. + If left as None, it performs Per-Sample Normalization (min and max are + calculated dynamically for every single 360-profile). + """ + def __init__( + self, + global_min: Optional[float] = None, + global_max: Optional[float] = None + ): + self.global_min = global_min + self.global_max = global_max + + def __call__(self, x: torch.Tensor) -> torch.Tensor: + # Use provided globals, otherwise compute local min/max + x_min = self.global_min if self.global_min is not None else x.min() + x_max = self.global_max if self.global_max is not None else x.max() + + denom = x_max - x_min + + # Prevent division by zero if the profile is completely flat + if denom < 1e-8: + return torch.zeros_like(x) + + return (x - x_min) / denom + + +# Module-level mmap cache — each worker process gets its own copy, +# so there is no cross-process sharing or locking needed. +_MMAP_CACHE: dict[str, np.ndarray] = {} + + +def _get_mmap(path: str) -> np.ndarray: + """Return (and cache) a read-only memory-mapped array for *path*.""" + if path not in _MMAP_CACHE: + container = np.load(path, mmap_mode="r") + _MMAP_CACHE[path] = container["data"] + return _MMAP_CACHE[path] + + +class PulseProfileDataset(Dataset): + """ + Flat dataset where each sample is a [360]-length angular profile + at one timestep from one pulse. + + The index is a flat list of (npz_path, t) pairs. + Memory-mapped arrays are opened lazily and cached per worker process, + so the OS page-cache handles repeated access at RAM speed. + + Args: + index: list of (npz_path: str, t: int) tuples. + transform: optional callable applied to the tensor. + """ + + def __init__( + self, + index: list[tuple[str, int]], + transform: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, + ): + self.index = index + self.transform = transform + + def __len__(self) -> int: + return len(self.index) + + def __getitem__(self, idx: int) -> torch.Tensor: + path, t = self.index[idx] + arr = _get_mmap(path) # [T x 361], read-only mmap + profile = arr[t] # shape [361], one page read + x = torch.from_numpy(profile[1:].copy()) # .copy() detaches from mmap buffer + + if self.transform is not None: + x = self.transform(x) + + return x + + +# --------------------------------------------------------------------------- +# Step 3 — Lightning DataModule +# --------------------------------------------------------------------------- + +class PulseDataModule(L.LightningDataModule): + """ + Lightning DataModule for per-frame profile samples. + + Requires that consolidate_pulses() has already been run. + + Splitting is done at the PULSE level to prevent data leakage + (consecutive timesteps within a pulse are strongly correlated). + + Args: + consolidated_dir: directory containing the per-pulse .npz files. + val_frac: fraction of pulses held out for validation. + test_frac: fraction of pulses held out for testing. + batch_size: profiles per batch. + num_workers: DataLoader workers (4-8 is usually optimal). + pin_memory: pin CPU tensors for faster GPU transfer. + seed: RNG seed for reproducible pulse-level splits. + transform: optional per-sample transform. + t_start: first timestep index to include (default 0). + t_end: last timestep index (exclusive); None = all. + """ + + def __init__( + self, + consolidated_dir: str | Path, + val_frac: float = 0.1, + test_frac: float = 0.1, + batch_size: int = 512, + num_workers: int = 4, + pin_memory: bool = False, + seed: int = 42, + transform: Optional[Callable] = None, + t_start: int = 0, + t_end: Optional[int] = None, + ): + super().__init__() + self.consolidated_dir = Path(consolidated_dir) + self.val_frac = val_frac + self.test_frac = test_frac + self.batch_size = batch_size + self.num_workers = num_workers + self.pin_memory = pin_memory + self.seed = seed + self.transform = transform + self.t_start = t_start + self.t_end = t_end + + self._train_index: list[tuple[str, int]] = [] + self._val_index: list[tuple[str, int]] = [] + self._test_index: list[tuple[str, int]] = [] + + # ------------------------------------------------------------------ + def setup(self, stage: Optional[str] = None) -> None: + npz_files = sorted(self.consolidated_dir.glob("*.npz")) + if not npz_files: + raise FileNotFoundError( + f"No .npz files found in {self.consolidated_dir}. " + "Run consolidate_pulses() first." + ) + + rng = random.Random(self.seed) + rng.shuffle(npz_files) + + n = len(npz_files) + n_test = max(1, round(n * self.test_frac)) + n_val = max(1, round(n * self.val_frac)) + n_train = n - n_val - n_test + + splits = { + "train": npz_files[:n_train], + "val": npz_files[n_train: n_train + n_val], + "test": npz_files[n_train + n_val:], + } + + for split, files in splits.items(): + index = self._build_flat_index(files) + setattr(self, f"_{split}_index", index) + + self._print_summary(splits) + + def _build_flat_index(self, npz_files: list[Path]) -> list[tuple[str, int]]: + """Return a flat list of (path, t) pairs for all timesteps in all pulses.""" + index = [] + for path in npz_files: + with np.load(str(path), mmap_mode="r") as container: + T = container["data"].shape[0] + + t_end = min(self.t_end, T) if self.t_end is not None else T + index.extend((str(path), t) for t in range(self.t_start, t_end)) + return index + + def _print_summary(self, splits: dict) -> None: + for split, files in splits.items(): + idx = getattr(self, f"_{split}_index") + print( + f"[PulseDataModule] {split:5s}: " + f"{len(files):3d} pulses | {len(idx):>10,} timestep samples" + ) + + # ------------------------------------------------------------------ + def _make_loader(self, index: list[tuple[str, int]], shuffle: bool) -> DataLoader: + if shuffle: + index = index.copy() + random.shuffle(index) + + return DataLoader( + PulseProfileDataset(index, transform=self.transform), + batch_size=self.batch_size, + shuffle=False, # already shuffled above + num_workers=self.num_workers, + pin_memory=self.pin_memory, + persistent_workers=self.num_workers > 0, + ) + + def train_dataloader(self) -> DataLoader: + return self._make_loader(self._train_index, shuffle=True) + + def val_dataloader(self) -> DataLoader: + return self._make_loader(self._val_index, shuffle=False) + + def test_dataloader(self) -> DataLoader: + return self._make_loader(self._test_index, shuffle=False) + + # ------------------------------------------------------------------ + @property + def n_angles(self) -> int: + with np.load(str(self._train_index[0][0]), mmap_mode="r") as container: + return container["data"].shape[1] + + @property + def n_train_samples(self) -> int: + return len(self._train_index) + + +# --------------------------------------------------------------------------- +# Usage +# --------------------------------------------------------------------------- + +if __name__ == "__main__": + # ---- Run ONCE to consolidate ---------------------------------------- + root_dir = input(f"Select folder where .h5 files are cached") + out_dir = input(f"Select folder to write the database files, should be ./data") + consolidate_pulses( + root=root_dir, + out_dir="/home/IPP-HGW/orluca/devel/XMCTSGuard/data/consolidated/", + data_key="XMCTSdata", # adjust to your HDF5 key + dtype=np.float32, + overwrite=False, # set True to re-consolidate + decimation_factor=1_000, + ) + + # ---- Then use normally in Lightning --------------------------------- + scaler = MinMaxNormalize(global_min=0.0, global_max=10.0) + + dm = PulseDataModule( + consolidated_dir="data/consolidated/", + val_frac=0.1, + test_frac=0.1, + batch_size=512, + num_workers=4, + seed=42, + transform=scaler + # t_start=1000, # optional: trim transient at start of pulse + # t_end=90_000, # optional: trim tail + ) + + dm.setup() + + for batch in dm.train_dataloader(): + print(f"Batch shape : {batch.shape}") # Will be [512, 361] because of the time array in col 0 + print(f"Dtype : {batch.dtype}") + break \ No newline at end of file diff --git a/src/XMCTSGuard/engine/train.py b/src/XMCTSGuard/engine/train.py new file mode 100644 index 0000000..284ce90 --- /dev/null +++ b/src/XMCTSGuard/engine/train.py @@ -0,0 +1,264 @@ +import torch +import lightning as L +from lightning.pytorch.callbacks import EarlyStopping +from lightning.pytorch.loggers import TensorBoardLogger + +from .pulse_dataset import PulseDataModule, MinMaxNormalize +from .dataset import AEDataModule +from .model import AutoEncoder, VariationalAutoEncoder +from .callbacks import SaveBest, SaveEveryNEpochs, BetaWarmUp +from ..visualization.plots import GAIN_PIDS as gain_list + +def train_autoencoder(data_dir, file_name=None, input_dim=360, geometry=[64, 32, 16, 8], + beta=1, gamma=1, batch_size=32, max_epochs=100, + normalization_strategy='minmax', learning_rate=3e-4, + activation=torch.nn.ReLU(), nprofiles=None, model_kind='AE', + sel_device=None): + """ + Trains an Autoencoder (AE) or Variational Autoencoder (VAE) on pulse profile data + from the Wendelstein 7-X (W7-X) stellarator experiment, using PyTorch Lightning + for training orchestration and TensorBoard for logging. + + The function handles the full training pipeline end-to-end: + 1. Data loading and normalization via a PulseDataModule. + 2. Model instantiation (AE or VAE) with the specified architecture. + 3. Training with automatic hardware acceleration and configurable callbacks. + 4. Validation and testing after training. + + Parameters + ---------- + data_dir : str or Path + Path to the consolidated directory containing the pulse profile dataset. + This is passed directly to PulseDataModule as `consolidated_dir`. + + file_name : str or None, optional + Name of a specific data file to load from `data_dir`. If None, the data + module is expected to discover files automatically. Currently unused in + the active code path (legacy parameter). Default is None. + + input_dim : int, optional + Dimensionality of each input sample (i.e., the number of features per + pulse profile). Must match the actual feature size of the loaded data. + Default is 360. + + geometry : list of int, optional + Defines the encoder's layer sizes from input to the bottleneck. Each + integer specifies the number of neurons in that hidden layer. The decoder + is constructed as the mirror image of the encoder. + Example: [64, 32, 16, 8] produces the architecture: + Encoder: input_dim → 64 → 32 → 16 → 8 (bottleneck) + Decoder: 8 → 16 → 32 → 64 → input_dim + Default is [64, 32, 16, 8]. + + beta : float or int, optional + Weight applied to the KL-divergence term in the VAE loss function. + Only relevant when model_kind='VAE'. A value of 1 corresponds to a + standard VAE; values > 1 produce a β-VAE, which encourages greater + disentanglement of latent representations. Ignored for AE. Default is 1. + + gamma : float or int, optional + Additional loss scaling factor for the VAE objective. Only relevant when + model_kind='VAE'. Interpretation depends on the VariationalAutoEncoder + implementation (e.g., may weight reconstruction loss separately). + Ignored for AE. Default is 1. + + batch_size : int, optional + Number of samples per training batch. Note: this parameter is accepted + for interface compatibility but the active code path hardcodes + batch_size=64 inside PulseDataModule. Default is 32. + + max_epochs : int, optional + Maximum number of training epochs. Training may stop earlier if an + EarlyStopping callback is enabled (currently commented out). + Default is 100. + + normalization_strategy : str, optional + Normalization strategy label. Currently unused in the active code path + (legacy parameter); normalization is handled by MinMaxNormalize with + fixed global_min=0.0 and global_max=10.0. Default is 'minmax'. + + learning_rate : float, optional + Initial learning rate passed to the model's optimizer (Adam or similar, + depending on the model implementation). Default is 3e-4. + + activation : torch.nn.Module, optional + Activation function applied between hidden layers in both encoder and + decoder. Any torch.nn activation module is valid (e.g., torch.nn.ReLU(), + torch.nn.Tanh(), torch.nn.LeakyReLU()). Default is torch.nn.ReLU(). + + nprofiles : int or None, optional + Maximum number of profiles to load from the dataset. If None, all + available profiles are used. Currently unused in the active code path + (legacy parameter). Default is None. + + model_kind : {'AE', 'VAE'}, optional + Selects the model architecture to train: + - 'AE' : Standard deterministic AutoEncoder (AutoEncoder class). + - 'VAE' : Variational AutoEncoder (VariationalAutoEncoder class), + which learns a probabilistic latent space using the + reparameterization trick and a KL-divergence regularization term. + Default is 'AE'. + + sel_device : str or None, optional + Target compute device (e.g., 'cpu', 'cuda', 'mps'). Currently unused; + device selection is handled automatically by PyTorch Lightning via + accelerator='auto'. Default is None. + + Returns + ------- + model : AutoEncoder or VariationalAutoEncoder + The trained model instance after fitting. The model's weights correspond + to the final training epoch (not necessarily the best validation checkpoint, + unless SaveBest restores them — check the SaveBest callback implementation). + + Side Effects + ------------ + - Writes TensorBoard logs to: ./W7-X_QXT// + where logger_name is 'AE{input_dim}' or 'VAE{input_dim}'. + - Saves model checkpoints via SaveBest (monitors val/loss) and + SaveEveryNEpochs (every 100 epochs) callbacks. Checkpoint paths are + determined by the logger configuration. + - Runs trainer.validate() and trainer.test() after training, logging + results to TensorBoard. + + Raises + ------ + ValueError + Raised implicitly if model_kind is not 'AE' or 'VAE', as the model + variable will be undefined when passed to the trainer. + + Notes + ----- + **Hardcoded data module settings:** + The PulseDataModule is initialized with val_frac=0.0, test_frac=0.0, + num_workers=4, and seed=42, regardless of the values passed to + normalization_strategy, or nprofiles. These parameters are currently kept + in the signature for backward compatibility but have no effect on behavior. + + **Normalization:** + MinMaxNormalize is applied with global_min=0.0 and global_max=10.0. + These bounds should be verified against the actual data range to avoid + clipping or poor normalization. + + **Validation and test splits:** + Since val_frac=0.0 and test_frac=0.0, trainer.validate() and + trainer.test() will run on the training set. Consider adjusting + val_frac and test_frac for proper generalization evaluation. + + **Callbacks (active):** + - SaveBest: Saves the checkpoint with the lowest val/loss. + - SaveEveryNEpochs(100): Saves a checkpoint every 100 epochs. + + **Callbacks (disabled):** + - EarlyStopping: Would halt training if val/loss does not improve for + 10 consecutive epochs. + - BetaWarmUp: Would gradually increase the β term from 0 to 0.1 over + 50 epochs starting at epoch 10 (useful for VAE training stability). + + Examples + -------- + Train a standard AE on pulse data: + + >>> model = train_autoencoder( + ... data_dir='/data/w7x/pulses', + ... input_dim=360, + ... geometry=[128, 64, 32, 16], + ... model_kind='AE', + ... max_epochs=200, + ... learning_rate=1e-3, + ... ) + + Train a β-VAE with a stronger KL penalty: + + >>> model = train_autoencoder( + ... data_dir='/data/w7x/pulses', + ... input_dim=360, + ... geometry=[64, 32, 16], + ... model_kind='VAE', + ... beta=1e-5, + ... gamma=1, + ... max_epochs=300, + ... activation=torch.nn.LeakyReLU(), + ... ) + + See Also + -------- + AutoEncoder : Standard deterministic autoencoder model class. + VariationalAutoEncoder : VAE model class with KL-divergence regularization. + PulseDataModule : Lightning DataModule for loading and batching pulse profiles. + MinMaxNormalize : Transform class for min-max feature scaling. + SaveBest : Callback that saves the best model checkpoint by monitored metric. + SaveEveryNEpochs : Callback that saves checkpoints at fixed epoch intervals. + """ + + # TODO: implement better device selection practice + # # Initialize the data module + # data_module = AEDataModule(data_dir, file_name, batch_size, normalization_strategy, nprofiles=nprofiles) + # data_module.prepare_data() + # data_module.setup() + # data_module.exclude_pids(gain_list) + scaler = MinMaxNormalize(global_min=0.0, global_max=10.0) + data_module = PulseDataModule(consolidated_dir=data_dir, + val_frac=0.1, test_frac=0.1, batch_size=batch_size, num_workers=4, seed=42, + transform=scaler, + ) + data_module.setup() + + # Initialize the model + if model_kind == 'AE': + model = AutoEncoder(input_dim=input_dim, geometry=geometry, learning_rate=learning_rate, activation=activation) + logger_name = f"AE{input_dim}" + elif model_kind == 'VAE': + model = VariationalAutoEncoder(input_dim=input_dim, geometry=geometry, beta=beta, gamma=gamma, learning_rate=learning_rate, activation=activation) + logger_name = f"VAE{input_dim}" + + # Initialize a logger + logger = TensorBoardLogger("W7-X_QXT", name=logger_name) + + # Initialize the trainer + trainer = L.Trainer( + logger=logger, + max_epochs=max_epochs, + accelerator='auto', + callbacks=[ + SaveBest(monitor="val/loss", logger=logger), + SaveEveryNEpochs(100, logger=logger), + # EarlyStopping(monitor="val/loss", patience=10, mode="min"), + # BetaWarmUp(start_epoch=10, initial_beta=0, final_beta=0.1, warmup_epochs=50), + ], + devices='auto',) + + + # Train the model + trainer.fit(model, data_module) + trainer.validate(model, data_module) + trainer.test(model, data_module) + + # # Evaluate the model on the validation set + # if data_module.val_data is not None: + # trainer.validate(model, datamodule=data_module) + # # Evaluate the model on the test set + # if data_module.test_data is not None: + # trainer.test(model, datamodule=data_module) + + return model + +if __name__ == "__main__": + data_dir = "../data" + file_name = "20251028_all_data.npz" + input_dim = 360 + geometry = [64, 32, 32] + beta = 1e-7 + gamma = 1e-4 + batch_size = 32 + max_epochs = 3000 + normalization_strategy = 'minmax' # Options: 'minmax', 'zscore', 'robust', 'none' + learning_rate = 5e-5 + nprofiles = 10000 + activation = torch.nn.ReLU() + model_kind = 'AE' + + # Train the autoencoder + train_autoencoder(data_dir, file_name, input_dim, geometry, beta, gamma, batch_size, + max_epochs, normalization_strategy, learning_rate, activation, + nprofiles, model_kind=model_kind) diff --git a/src/XMCTSGuard/engine/utils.py b/src/XMCTSGuard/engine/utils.py new file mode 100644 index 0000000..2614ea2 --- /dev/null +++ b/src/XMCTSGuard/engine/utils.py @@ -0,0 +1,161 @@ +# ───────────────────────────────────────────────────────────────────────────── +# Pure computation helpers (stateless, importable, testable) +# ───────────────────────────────────────────────────────────────────────────── +import numpy as np + + +def normalize(arr: np.ndarray, min_data: float, max_data: float) -> np.ndarray: + """Min-max normalise to [0, 1], returned as float32.""" + return ((arr - min_data) / (max_data - min_data)).astype(np.float32) + + +def denormalize(arr: np.ndarray, min_data: float, max_data: float) -> np.ndarray: + """Invert min-max normalisation.""" + return arr * (max_data - min_data) + min_data + + +def model_forward_single(model, profile_norm: np.ndarray) -> np.ndarray: + """Run the autoencoder on one normalised 1-D profile (float32 numpy array).""" + import torch + with torch.no_grad(): + return model(torch.from_numpy(profile_norm).unsqueeze(0)).squeeze(0).numpy() + + +def model_forward_batch(model, batch_norm: np.ndarray) -> np.ndarray: + """ + Run the autoencoder on a batch shaped (n_samples, n_diodes). + Returns (n_samples, n_diodes) float32. + """ + import torch + with torch.no_grad(): + return model(torch.from_numpy(batch_norm)).numpy() + + +def reconstruct(model, profile: np.ndarray, + min_data: float, max_data: float) -> np.ndarray: + """Normalise → model → denormalise for a single 1-D profile.""" + rec_norm = model_forward_single(model, normalize(profile, min_data, max_data)) + return denormalize(rec_norm, min_data, max_data) + + +def pearson(a: np.ndarray, b: np.ndarray) -> float: + """Pearson correlation coefficient between two 1-D arrays.""" + return float(np.corrcoef(a, b)[0, 1]) + + +def apply_gain(profile: np.ndarray, + outlier_mask: np.ndarray, + gain_ratio: float) -> np.ndarray: + """ + Return a gain-corrected copy of *profile*. + + gain_ratio = old_gain / new_gain. + + When gain_ratio > 1 the majority of channels recorded with the higher + old gain and look inflated — they are the ones to scale; the spatial + outliers are the channels that did NOT change gain. + When gain_ratio < 1 the detected outlier channels are the ones that + changed gain and need to be rescaled. + """ + adjusted = profile.copy() + if gain_ratio > 1: + adjusted[~outlier_mask] *= gain_ratio # majority-changed channels + else: + adjusted[outlier_mask] *= gain_ratio # outlier channels changed gain + return adjusted + + +def fill_outlier_gaps(outlier_mask: np.ndarray, + profile: np.ndarray, + tol: float = 0.10) -> np.ndarray: + """ + For each pair of consecutive flagged diodes (i, j) that are at most + 8 positions apart, check whether every diode m between them is within + *tol* (relative) of the average of profile[i] and profile[j]. If so, + flag m as well — this closes small intra-camera gaps in the outlier region. + """ + filled = outlier_mask.copy() + outlier_indices = np.where(outlier_mask)[0] + + for k in range(len(outlier_indices) - 1): + i = outlier_indices[k] + j = outlier_indices[k + 1] + + if j - i > 8: # only close gaps within the same camera + continue + + ref = (profile[i] + profile[j]) / 2.0 + for m in range(i + 1, j): + if abs(profile[m] - ref) / (abs(ref) + 1e-10) <= tol: + filled[m] = True + + return filled + + +# ── Single-pass model-residuals outlier detection ──────────────────────────── + +def detect_outliers_residual(profile: np.ndarray, + reconstruction: np.ndarray, + z_thresh: float) -> np.ndarray: + """ + Flag diodes where (profile − reconstruction) > mean + z_thresh · std. + + Only positive residuals are caught: diodes whose signal sits well above + what the autoencoder expects given the rest of the spatial profile. + """ + residuals = profile - reconstruction + threshold = np.mean(residuals) + z_thresh * np.std(residuals) + return residuals > threshold + + +# ── Batched helpers ─────────────────────────────────────────────────────────── + +def compute_correlation_series(model, signals: np.ndarray, + indices: np.ndarray, + min_data: float, max_data: float, + batch_size: int = 256) -> np.ndarray: + """ + Compute per-time-step Pearson ρ(signal, AE(signal)) for the given column + indices of *signals* (shape: n_diodes × n_time), in batches. + + Returns a float32 array of length len(indices). + """ + correlations = np.empty(len(indices), dtype=np.float32) + col = 0 + + for start in range(0, len(indices), batch_size): + idx_batch = indices[start : start + batch_size] + batch_sig = signals[:, idx_batch] # (n_diodes, b) + batch_norm = normalize(batch_sig.T, min_data, max_data) # (b, n_diodes) + rec_norm = model_forward_batch(model, batch_norm) # (b, n_diodes) + rec_dn = denormalize(rec_norm, min_data, max_data) + for j in range(len(idx_batch)): + correlations[col] = pearson(batch_sig[:, j], rec_dn[j, :]) + col += 1 + del batch_sig, batch_norm, rec_norm, rec_dn + + return correlations + + +def reconstruct_only_batched(model, signals: np.ndarray, + min_data: float, max_data: float, + batch_size: int = 256) -> np.ndarray: + """ + Pass every time step of *signals* (n_diodes × n_time) through the + autoencoder in batches. No gain correction is applied here — the caller + is responsible for providing already-corrected data. + + Returns rec shaped (n_diodes, n_time). *signals* is NOT mutated. + """ + n_time = signals.shape[1] + rec = np.empty_like(signals) + + for start in range(0, n_time, batch_size): + end = min(start + batch_size, n_time) + batch = normalize(signals[:, start:end].T, + min_data, max_data) # (b, n_diodes) + out = model_forward_batch(model, batch) # (b, n_diodes) + rec[:, start:end] = denormalize(out.T, min_data, max_data) + del batch, out + + return rec \ No newline at end of file diff --git a/src/XMCTSGuard/gui/__init__.py b/src/XMCTSGuard/gui/__init__.py new file mode 100644 index 0000000..d42f715 --- /dev/null +++ b/src/XMCTSGuard/gui/__init__.py @@ -0,0 +1,3 @@ +from .main_window import WorkflowGUI + +__all__ = ["WorkflowGUI"] \ No newline at end of file diff --git a/src/XMCTSGuard/gui/helpers.py b/src/XMCTSGuard/gui/helpers.py new file mode 100644 index 0000000..19b782c --- /dev/null +++ b/src/XMCTSGuard/gui/helpers.py @@ -0,0 +1,21 @@ +# ───────────────────────────────────────────────────────────────────────────── +# Small UI helpers +# ───────────────────────────────────────────────────────────────────────────── + +from PyQt6.QtWidgets import QLabel, QLineEdit, QFrame + +def lbl_h(text, obj_name="dim"): + w = QLabel(text) + w.setObjectName(obj_name) + return w + + +def divider_h(): + f = QFrame() + f.setObjectName("divider") + f.setFrameShape(QFrame.Shape.HLine) + return f + + +def entry_h(default=""): + return QLineEdit(default) diff --git a/src/XMCTSGuard/gui/main_window.py b/src/XMCTSGuard/gui/main_window.py new file mode 100644 index 0000000..8a321c5 --- /dev/null +++ b/src/XMCTSGuard/gui/main_window.py @@ -0,0 +1,499 @@ +# ───────────────────────────────────────────────────────────────────────────── +# Main window +# ───────────────────────────────────────────────────────────────────────────── + +from PyQt6.QtWidgets import ( + QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, + QFileDialog, QMessageBox, QFrame, QSizePolicy, QGridLayout, +) +from matplotlib.figure import Figure +import matplotlib.gridspec as gridspec +from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg, NavigationToolbar2QT +from PyQt6.QtCore import Qt, QThread + +import os +import numpy as np + +from .helpers import * +from .styles import * +from .workers import AnalysisWorker +from .widgets import SpectralAnalysisDialog +from ..engine.utils import * +from ..utils import * + +class WorkflowGUI(QMainWindow): + def __init__(self): + super().__init__() + self.setWindowTitle("SXR Profile Anomaly Detector") + self.resize(1480, 860) + self.setMinimumSize(1100, 700) + self.setStyleSheet(STYLESHEET) + + self._thread = None + self._worker = None + self._results = None + self._build_ui() + + # ── layout ──────────────────────────────────────────────────────────────── + + def _build_ui(self): + root = QWidget() + self.setCentralWidget(root) + root_v = QVBoxLayout(root) + root_v.setContentsMargins(0, 0, 0, 0) + root_v.setSpacing(0) + + topbar = QFrame() + topbar.setObjectName("topbar") + topbar.setFixedHeight(52) + tb_h = QHBoxLayout(topbar) + tb_h.setContentsMargins(20, 0, 20, 0) + tb_h.addWidget(lbl_h("⚡ SXR Anomaly Detector", "title")) + tb_h.addStretch() + self._status_lbl = lbl_h("Ready", "status") + tb_h.addWidget(self._status_lbl) + root_v.addWidget(topbar) + + body = QWidget() + body_h = QHBoxLayout(body) + body_h.setContentsMargins(12, 12, 12, 12) + body_h.setSpacing(10) + root_v.addWidget(body, stretch=1) + + sidebar = QFrame() + sidebar.setObjectName("sidebar") + sidebar.setFixedWidth(264) + sidebar.setSizePolicy(QSizePolicy.Policy.Fixed, + QSizePolicy.Policy.Expanding) + self._build_sidebar(sidebar) + body_h.addWidget(sidebar) + + plot_w = QWidget() + self._build_plots(plot_w) + body_h.addWidget(plot_w, stretch=1) + + def _build_sidebar(self, parent): + lay = QVBoxLayout(parent) + lay.setContentsMargins(14, 10, 14, 14) + lay.setSpacing(4) + + def section(text): + lay.addSpacing(10) + lay.addWidget(lbl_h(text, "section")) + lay.addWidget(divider_h()) + + def field(label, default): + lay.addWidget(lbl_h(label)) + e = entry_h(default) + lay.addWidget(e) + return e + + section("SHOT") + self._pid_edit = field("PID", "20250401.49") + + section("MODEL") + lay.addWidget(lbl_h("Checkpoint path")) + path_row = QWidget() + path_h = QHBoxLayout(path_row) + path_h.setContentsMargins(0, 0, 0, 0) + path_h.setSpacing(4) + self._model_edit = entry_h( + "path/to/ckpt/file/best_model_.ckpt" + ) + browse_btn = QPushButton("…") + browse_btn.setObjectName("browse") + browse_btn.setFixedWidth(28) + browse_btn.clicked.connect(self._browse_model) + path_h.addWidget(self._model_edit) + path_h.addWidget(browse_btn) + lay.addWidget(path_row) + + section("NORMALISATION") + self._min_edit = field("min_data", "-0.2294265627861023") + self._max_edit = field("max_data", "8.772955894470215") + + section("GAIN RATIO") + gain_row = QWidget() + gain_h = QHBoxLayout(gain_row) + gain_h.setContentsMargins(0, 0, 0, 0) + gain_h.setSpacing(6) + for label, val, attr in [("Old gain", "5", "_old_gain"), + ("New gain", "2", "_new_gain")]: + gain_h.addWidget(lbl_h(label)) + e = entry_h(val) + e.setFixedWidth(46) + setattr(self, attr, e) + gain_h.addWidget(e) + lay.addWidget(gain_row) + + section("OUTLIER DETECTION") + + # ── single greyed-out method indicator ──────────────────────────────── + self._method_btn = QPushButton("Model Residuals") + self._method_btn.setObjectName("method_btn") + self._method_btn.setCheckable(True) + self._method_btn.setChecked(True) + self._method_btn.setEnabled(False) # purely decorative + lay.addWidget(self._method_btn) + + # ── z-threshold ─────────────────────────────────────────────────────── + lay.addSpacing(4) + lay.addWidget(lbl_h("Z-threshold")) + self._z_edit = entry_h("0.2") + lay.addWidget(self._z_edit) + + # ── action buttons ──────────────────────────────────────────────────── + lay.addStretch() + + self._run_btn = QPushButton("▶ RUN ANALYSIS") + self._run_btn.setObjectName("run") + self._run_btn.clicked.connect(self._run) + lay.addWidget(self._run_btn) + + self._save_btn = QPushButton("💾 SAVE ADJUSTED DATA") + self._save_btn.setObjectName("run") + self._save_btn.setEnabled(False) + self._save_btn.clicked.connect(self._save_adjusted_data) + lay.addWidget(self._save_btn) + + self._save_rec_btn = QPushButton("💾 SAVE MODEL RECONSTRUCTION") + self._save_rec_btn.setObjectName("run") + self._save_rec_btn.setEnabled(False) + self._save_rec_btn.clicked.connect(self._save_reconstruction_data) + lay.addWidget(self._save_rec_btn) + + self._spectral_btn = QPushButton("📊 SPECTRAL ANALYSIS") + self._spectral_btn.setObjectName("spectral") + self._spectral_btn.setEnabled(False) + self._spectral_btn.setToolTip( + "Per-diode PSD heatmap, total power, and spectral entropy") + self._spectral_btn.clicked.connect(self._open_spectral_analysis) + lay.addWidget(self._spectral_btn) + + # ── correlation readout ─────────────────────────────────────────────── + lay.addSpacing(6) + self._corr_widget = QWidget() + self._corr_layout = QGridLayout(self._corr_widget) + self._corr_layout.setContentsMargins(0, 0, 0, 0) + self._corr_layout.setSpacing(3) + lay.addWidget(self._corr_widget) + + def _build_plots(self, parent): + lay = QVBoxLayout(parent) + lay.setContentsMargins(0, 0, 0, 0) + lay.setSpacing(0) + + self._fig = Figure(figsize=(10, 7), dpi=100, facecolor=BG) + gs = gridspec.GridSpec(2, 2, figure=self._fig, + hspace=0.42, wspace=0.20, + left=0.07, right=0.93, + top=0.93, bottom=0.08) + self._ax_orig = self._fig.add_subplot(gs[0, 0]) + self._ax_adj = self._fig.add_subplot(gs[0, 1]) + self._ax_rec = self._fig.add_subplot(gs[1, 0]) + self._ax_corr = self._fig.add_subplot(gs[1, 1]) + self.twin_ax_corr = self._ax_corr.twinx() + + for ax, title in [ + (self._ax_orig, "Original profile vs Reconstruction"), + (self._ax_adj, "Adjusted profile (outliers in red)"), + (self._ax_rec, "Adjusted profile vs AE reconstruction"), + (self._ax_corr, "Correlation over time"), + ]: + ax.grid(True) + ax.set_facecolor(PANEL) + ax.set_title(title, color=FG, pad=8) + + canvas = FigureCanvasQTAgg(self._fig) + canvas.setSizePolicy(QSizePolicy.Policy.Expanding, + QSizePolicy.Policy.Expanding) + lay.addWidget(canvas, stretch=1) + + tb_container = QWidget() + tb_container.setStyleSheet(f"background:{PANEL};") + tb_h = QHBoxLayout(tb_container) + tb_h.setContentsMargins(4, 0, 4, 0) + toolbar = NavigationToolbar2QT(canvas, tb_container) + toolbar.setStyleSheet(f"background:{PANEL}; color:{FG};") + tb_h.addWidget(toolbar) + lay.addWidget(tb_container) + + self._canvas = canvas + + # ── handlers ────────────────────────────────────────────────────────────── + + def _browse_model(self): + path, _ = QFileDialog.getOpenFileName( + self, "Select model checkpoint", "", + "Checkpoint (*.ckpt);;All files (*.*)" + ) + if path: + self._model_edit.setText(path) + + def _run(self): + try: + pid = self._pid_edit.text().strip() + model_path = self._model_edit.text().strip() + min_data = float(self._min_edit.text()) + max_data = float(self._max_edit.text()) + gain_ratio = float(self._old_gain.text()) / float(self._new_gain.text()) + except ValueError as e: + QMessageBox.critical(self, "Parameter error", str(e)) + return + + try: + z_thresh = float(self._z_edit.text()) + except ValueError: + z_thresh = 0.2 + + import gc + self._results = None + self._save_btn.setEnabled(False) + self._save_rec_btn.setEnabled(False) + self._spectral_btn.setEnabled(False) + gc.collect() + + self._run_btn.setEnabled(False) + self._run_btn.setText("⏳ Running …") + self._status_lbl.setText("Starting …") + + self._thread = QThread() + self._worker = AnalysisWorker( + pid, model_path, min_data, max_data, gain_ratio, + z_thresh = z_thresh, + ) + self._worker.moveToThread(self._thread) + self._thread.started.connect(self._worker.run) + self._worker.progress.connect(self._status_lbl.setText) + self._worker.finished.connect(self._on_results) + self._worker.error.connect(self._on_error) + self._worker.finished.connect(self._thread.quit) + self._worker.error.connect(self._thread.quit) + self._thread.start() + + def _on_error(self, msg): + self._run_btn.setEnabled(True) + self._run_btn.setText("▶ RUN ANALYSIS") + self._status_lbl.setText("Error — see dialog") + QMessageBox.critical(self, "Analysis failed", msg) + + def _on_results(self, r): + self._results = r + self._run_btn.setEnabled(True) + self._run_btn.setText("▶ RUN ANALYSIS") + self._save_btn.setEnabled(True) + self._save_rec_btn.setEnabled(True) + self._spectral_btn.setEnabled(True) + + self._status_lbl.setText( + f"PID {r['pid']} | t = {r['time_instant']:.2f} ms" + f" | ρ_orig = {r['corr_original']:.4f}" + f" | ρ_adj = {r['corr_adjusted']:.4f}" + ) + self._plot_results(r) + self._update_corr_readout(r) + + # ── spectral analysis ───────────────────────────────────────────────────── + + def _open_spectral_analysis(self): + if self._results is None: + return + dlg = SpectralAnalysisDialog(self._results, parent=self) + dlg.show() + + # ── plotting ────────────────────────────────────────────────────────────── + + def _plot_results(self, r): + for ax in (self._ax_orig, self._ax_adj, + self._ax_rec, self._ax_corr): + ax.cla() + ax.grid(True) + ax.set_facecolor(PANEL) + self.twin_ax_corr.cla() + self.twin_ax_corr.yaxis.set_label_position("right") + self.twin_ax_corr.yaxis.tick_right() + + x, ti, pid = r["x"], r["time_instant"], r["pid"] + + # ── panel 1: original vs AE ─────────────────────────────────────────── + ax = self._ax_orig + ax.plot(x, r["profile"], color=ACCENT, lw=1.8, label="Original") + ax.plot(x, r["rec_original"], color=ACCENT2, lw=1.8, ls="--", + label=f"AE recon (ρ = {r['corr_original']:.4f})") + ax.set_title("Original vs AE Reconstruction", color=FG, pad=8) + ax.set_xlabel("Diode index") + ax.set_ylabel("Signal [V]") + ax.legend(fontsize=8) + + # ── panel 2: adjusted profile with outliers ─────────────────────────── + ax = self._ax_adj + out = r["outlier_mask"] + ax.plot(x, r["profile"], color=FG_DIM, lw=1.2, ls="--", + alpha=0.6, label="Original") + ax.plot(x, r["adjusted"], color=ACCENT3, lw=1.8, label="Adjusted") + ax.plot(x, r["rec_original"], color=ACCENT2, lw=1.2, ls=":", + alpha=0.7, label="AE reconstruction") + if out.any(): + ax.scatter(x[out], r["profile"][out], + color=ACCENT4, marker="x", s=80, lw=1.8, + label=f"Outliers ({out.sum()})", zorder=5) + ax.set_title( + f"Adjusted Profile [Model Residuals z={r.get('z_thresh', '?')}]", + color=FG, pad=8) + ax.set_xlabel("Diode index") + ax.set_ylabel("Signal [V]") + ax.legend(fontsize=8) + + # ── panel 3: adjusted + AE reconstruction ──────────────────────────── + ax = self._ax_rec + ax.plot(x, r["profile"], color=FG_DIM, lw=1.2, ls="--", + alpha=0.6, label="Original") + ax.plot(x, r["adjusted"], color=ACCENT3, lw=1.8, label="Adjusted") + ax.plot(x, r["rec_adjusted"], color=ACCENT2, lw=1.8, ls="--", + label=f"AE recon (adj) (ρ = {r['corr_adjusted']:.4f})") + ax.set_title("Adjusted vs AE Reconstruction", color=FG, pad=8) + ax.set_xlabel("Diode index") + ax.set_ylabel("Signal [V]") + ax.legend(fontsize=8) + + # ── panel 4: correlation time-series ────────────────────────────────── + ax = self._ax_corr + t = r["timedata"] + cor = r["correlations"] + c = np.where(cor < 0.9, ACCENT4, ACCENT) + ax.scatter(t, cor, c=c, s=6, zorder=3) + ax.plot(t, cor, color=ACCENT, lw=1.0, alpha=0.4, zorder=2) + ax.axhline(0.9, color=WARNING, lw=1.2, ls="--", label="Threshold 0.9") + ax.axvline(ti, color=ACCENT2, lw=1.2, ls=":", + label=f"t = {ti:.1f} ms") + self.twin_ax_corr.plot(t, r["diode_signal"], color=ACCENT2, + lw=1.0, alpha=0.45, label="Diode #151") + self.twin_ax_corr.set_ylabel("Diode #151 [V]", color=ACCENT2, fontsize=8) + self.twin_ax_corr.tick_params(axis="y", labelcolor=ACCENT2, labelsize=7) + self.twin_ax_corr.set_facecolor(PANEL) + ax.set_title("Correlation over Time", color=FG, pad=8) + ax.set_xlabel("Time [ms]") + ax.set_ylabel("Pearson ρ", color=ACCENT) + ax.tick_params(axis="y", labelcolor=ACCENT) + ax.set_ylim(-0.1, 1.05) + l1, lb1 = ax.get_legend_handles_labels() + l2, lb2 = self.twin_ax_corr.get_legend_handles_labels() + ax.legend(l1 + l2, lb1 + lb2, fontsize=7, loc="lower left") + + self._fig.suptitle( + f"PID: {pid} | t_max = {ti:.2f} ms", + color=FG, fontsize=11, y=0.99, + ) + self._canvas.draw_idle() + + def _update_corr_readout(self, r): + # clear previous widgets + while self._corr_layout.count(): + item = self._corr_layout.takeAt(0) + if item.widget(): + item.widget().deleteLater() + + row = 0 + + # ── correlation summary ─────────────────────────────────────────────── + for label, value in [("ρ original :", r["corr_original"]), + ("ρ adjusted :", r["corr_adjusted"])]: + name = "corr_ok" if value >= 0.9 else "corr_bad" + lbl = lbl_h(label) + val = QLabel(f"{value:.4f}") + val.setObjectName(name) + val.setAlignment(Qt.AlignmentFlag.AlignRight) + self._corr_layout.addWidget(lbl, row, 0) + self._corr_layout.addWidget(val, row, 1) + row += 1 + + verdict = "▸ NORMAL" if r["corr_original"] >= 0.9 else "▸ ANOMALY" + obj = "verdict_ok" if r["corr_original"] >= 0.9 else "verdict_bad" + v_lbl = QLabel(verdict) + v_lbl.setObjectName(obj) + v_lbl.setAlignment(Qt.AlignmentFlag.AlignRight) + self._corr_layout.addWidget(v_lbl, row, 0, 1, 2) + row += 1 + + # ── residuals detection summary ─────────────────────────────────────── + row += 1 + self._corr_layout.addWidget(divider_h(), row, 0, 1, 2) + row += 1 + hdr = QLabel("── Residuals detection ──") + hdr.setObjectName("diode_corr_header") + hdr.setAlignment(Qt.AlignmentFlag.AlignCenter) + self._corr_layout.addWidget(hdr, row, 0, 1, 2) + row += 1 + n_out = int(r["outlier_mask"].sum()) + for lbl_txt, val_txt in [ + ("z-threshold", f"{r.get('z_thresh', '?')}"), + ("n flagged", f"{n_out}"), + ]: + lbl_w = QLabel(lbl_txt + " :") + lbl_w.setObjectName("diode_corr_row") + val_w = QLabel(val_txt) + val_w.setObjectName("diode_corr_row") + val_w.setAlignment(Qt.AlignmentFlag.AlignRight) + self._corr_layout.addWidget(lbl_w, row, 0) + self._corr_layout.addWidget(val_w, row, 1) + row += 1 + + # ── save ────────────────────────────────────────────────────────────────── + + def _save_adjusted_data(self): + if self._results is None: + QMessageBox.warning(self, "No data", "Run the analysis first.") + return + + r = self._results + h5py_path = r["file_path"] + pid = r["pid"] + adjusted_full = r["adjusted_full"] # gain-corrected, no model pass + timedata = r["timedata_full"] + diode_keys = r["diode_keys"] + + save_dir = os.path.join(os.path.dirname(h5py_path)) + os.makedirs(save_dir, exist_ok=True) + + try: + # Save the t000, t090, t180 and t270 files with adjusted keyword + save_tfiles(h5py_path) + # Save the x000, ..., x360 files with the adjusted data + save_xfiles(h5py_path, adjusted_full) + + except Exception as e: + QMessageBox.critical(self, "Save failed", str(e)) + + def _save_reconstruction_data(self): + if self._results is None: + QMessageBox.warning(self, "No data", "Run the analysis first.") + return + + import h5py + + r = self._results + h5py_path = r["file_path"] + pid = r["pid"] + rec_adjusted_full = r["rec_adjusted_full"] # model reconstruction of gain-corrected data + timedata = r["timedata_full"] + diode_keys = r["diode_keys"] + + save_dir = os.path.join(os.path.dirname(h5py_path)) + os.makedirs(save_dir, exist_ok=True) + + try: + for i, key in enumerate(diode_keys): + dst_path = os.path.join( + save_dir, + f"xmcts{format_pid(pid)}reconstructed_x{key}.h5f" + ) + with h5py.File(dst_path, "w") as f: + grp = f.create_group("XMCTSdata") + grp.create_dataset("timedata", data=timedata) + grp.create_dataset(key, data=rec_adjusted_full[i, :]) + self._status_lbl.setText( + f"Saved {len(diode_keys)} reconstruction files → {save_dir}") + except Exception as e: + QMessageBox.critical(self, "Save failed", str(e)) + + diff --git a/src/XMCTSGuard/gui/styles.py b/src/XMCTSGuard/gui/styles.py new file mode 100644 index 0000000..90881f6 --- /dev/null +++ b/src/XMCTSGuard/gui/styles.py @@ -0,0 +1,182 @@ +import matplotlib.pyplot as plt + + +# ── colour palette ──────────────────────────────────────────────────────────── +BG = "#0f1117" +PANEL = "#1a1d27" +ACCENT = "#4f8ef7" +ACCENT2 = "#f7a24f" +ACCENT3 = "#4ff7a2" +ACCENT4 = "#f74f4f" +FG = "#e8eaf0" +FG_DIM = "#6b7280" +BORDER = "#2a2d3a" +SUCCESS = "#22c55e" +WARNING = "#f59e0b" +DANGER = "#ef4444" + +# ── matplotlib style ────────────────────────────────────────────────────────── +plt.rcParams.update({ + "figure.facecolor": BG, + "axes.facecolor": PANEL, + "axes.edgecolor": BORDER, + "axes.labelcolor": FG, + "axes.titlecolor": FG, + "xtick.color": FG_DIM, + "ytick.color": FG_DIM, + "grid.color": BORDER, + "grid.linestyle": "--", + "grid.alpha": 0.5, + "legend.facecolor": PANEL, + "legend.edgecolor": BORDER, + "legend.labelcolor": FG, + "text.color": FG, + "font.family": "monospace", + "font.size": 9, +}) + +# ── global stylesheet ───────────────────────────────────────────────────────── +STYLESHEET = f""" +QWidget {{ + background-color: {BG}; + color: {FG}; + font-family: "Courier New", monospace; + font-size: 10px; +}} +QFrame#sidebar {{ + background-color: {PANEL}; + border-right: 1px solid {BORDER}; +}} +QFrame#topbar {{ + background-color: {PANEL}; + border-bottom: 1px solid {BORDER}; +}} +QLabel#title {{ + color: {ACCENT}; + font-size: 14px; + font-weight: bold; +}} +QLabel#section {{ + color: {ACCENT}; + font-size: 9px; + font-weight: bold; +}} +QLabel#dim {{ + color: {FG_DIM}; + font-size: 9px; +}} +QLineEdit {{ + background-color: #252836; + color: {FG}; + border: 1px solid {BORDER}; + border-radius: 3px; + padding: 4px 6px; + font-size: 9px; +}} +QLineEdit:focus {{ + border: 1px solid {ACCENT}; +}} +QLineEdit:disabled {{ + background-color: #1a1d27; + color: {FG_DIM}; + border: 1px solid {BORDER}; +}} +QPushButton#run {{ + background-color: {ACCENT}; + color: #0f1117; + font-weight: bold; + font-size: 11px; + border: none; + border-radius: 4px; + padding: 9px; +}} +QPushButton#run:hover {{ + background-color: #7aabff; +}} +QPushButton#run:disabled {{ + background-color: #2a3550; + color: {FG_DIM}; +}} +QPushButton#browse {{ + background-color: {BORDER}; + color: {FG}; + border: none; + border-radius: 3px; + padding: 4px 8px; + font-size: 10px; +}} +QPushButton#browse:hover {{ + background-color: #3a3d4a; +}} +QFrame#divider {{ + background-color: {BORDER}; + max-height: 1px; +}} +QLabel#corr_ok {{ color: {SUCCESS}; font-weight: bold; }} +QLabel#corr_bad {{ color: {DANGER}; font-weight: bold; }} +QLabel#verdict_ok {{ color: {SUCCESS}; font-size: 12px; font-weight: bold; }} +QLabel#verdict_bad {{ color: {DANGER}; font-size: 12px; font-weight: bold; }} +QLabel#status {{ color: {FG_DIM}; font-size: 9px; }} +QPushButton#method_btn {{ + background-color: {BORDER}; + color: {FG_DIM}; + border: 1px solid {BORDER}; + border-radius: 3px; + padding: 4px 6px; + font-size: 9px; +}} +QPushButton#method_btn:checked {{ + background-color: #1e3a5f; + color: {ACCENT}; + border: 1px solid {ACCENT}; +}} +QPushButton#method_btn:disabled {{ + background-color: #1e3a5f; + color: {ACCENT}; + border: 1px solid {ACCENT}; + opacity: 0.7; +}} +QPushButton#spectral {{ + background-color: #1a2e1a; + color: {ACCENT3}; + font-weight: bold; + font-size: 11px; + border: 1px solid {ACCENT3}; + border-radius: 4px; + padding: 9px; +}} +QPushButton#spectral:hover {{ + background-color: #253525; +}} +QPushButton#spectral:disabled {{ + background-color: {PANEL}; + color: {FG_DIM}; + border: 1px solid {BORDER}; +}} +QComboBox {{ + background-color: #252836; + color: {FG}; + border: 1px solid {BORDER}; + border-radius: 3px; + padding: 2px 4px; +}} +QComboBox:disabled {{ + background-color: #1a1d27; + color: {FG_DIM}; +}} +QComboBox QAbstractItemView {{ + background-color: #252836; + color: {FG}; + selection-background-color: {ACCENT}; +}} +QLabel#diode_corr_header {{ + color: {ACCENT3}; + font-size: 9px; + font-weight: bold; +}} +QLabel#diode_corr_row {{ + color: {FG_DIM}; + font-size: 8px; + font-family: monospace; +}} +""" diff --git a/src/XMCTSGuard/gui/widgets.py b/src/XMCTSGuard/gui/widgets.py new file mode 100644 index 0000000..58614fe --- /dev/null +++ b/src/XMCTSGuard/gui/widgets.py @@ -0,0 +1,229 @@ +from PyQt6 import QtWidgets +from PyQt6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QSizePolicy, QDialog, QComboBox, +) +from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg, NavigationToolbar2QT +from matplotlib.figure import Figure +import matplotlib.gridspec as gridspec + + + +import numpy as np +from scipy.signal import welch +from scipy.stats import entropy as scipy_entropy + +from .styles import * +from .helpers import * + + +# ───────────────────────────────────────────────────────────────────────────── +# Spectral Analysis Dialog +# ───────────────────────────────────────────────────────────────────────────── + +class SpectralAnalysisDialog(QDialog): + """ + Stand-alone spectral analysis window. + + Three panels (all sharing the same diode-index x-axis): + • Top — 2-D PSD heatmap (diode × frequency, log₁₀ scale) + • Middle — total spectral power per diode + • Bottom — spectral entropy per diode + + Outlier diodes from the parent analysis are highlighted with red bands + in all three panels. + """ + + def __init__(self, results: dict, parent=None): + super().__init__(parent) + self.setWindowTitle(f"Spectral Analysis — PID {results['pid']}") + self.resize(1240, 860) + self.setMinimumSize(900, 600) + self.setStyleSheet(STYLESHEET) + self._r = results + self._build_ui() + self._compute_and_plot() + + def _build_ui(self): + root = QVBoxLayout(self) + root.setContentsMargins(10, 10, 10, 10) + root.setSpacing(6) + + ctrl = QWidget() + ctrl.setStyleSheet(f"background:{PANEL}; border-radius:4px;" + f" border:1px solid {BORDER}; padding:2px;") + ctrl_h = QHBoxLayout(ctrl) + ctrl_h.setContentsMargins(12, 6, 12, 6) + ctrl_h.setSpacing(14) + + def _combo(items, width=90, default_idx=0): + c = QComboBox() + c.addItems(items) + c.setCurrentIndex(default_idx) + c.setFixedWidth(width) + c.currentIndexChanged.connect(self._replot) + return c + + ctrl_h.addWidget(lbl_h("Window:", "dim")) + self._win_combo = _combo(["hann", "hamming", "blackman", "boxcar"]) + ctrl_h.addWidget(self._win_combo) + + ctrl_h.addWidget(lbl_h("nperseg:", "dim")) + self._nperseg_combo = _combo(["64", "128", "256", "512"], 70, 2) + ctrl_h.addWidget(self._nperseg_combo) + + ctrl_h.addWidget(lbl_h("f-max (Hz):", "dim")) + self._fmax_combo = _combo( + ["All", "50", "100", "200", "500", "1000", "2000", "5000"], 80) + ctrl_h.addWidget(self._fmax_combo) + + ctrl_h.addWidget(lbl_h("Colormap:", "dim")) + self._cmap_combo = _combo( + ["inferno", "magma", "plasma", "viridis", "cividis", "hot"], 80) + ctrl_h.addWidget(self._cmap_combo) + + ctrl_h.addStretch() + self._info_lbl = lbl_h("", "dim") + ctrl_h.addWidget(self._info_lbl) + root.addWidget(ctrl) + + self._fig = Figure(figsize=(11, 8), dpi=100, facecolor=BG) + canvas = FigureCanvasQTAgg(self._fig) + canvas.setSizePolicy(QSizePolicy.Policy.Expanding, + QSizePolicy.Policy.Expanding) + root.addWidget(canvas, stretch=1) + + tb_w = QWidget() + tb_w.setStyleSheet(f"background:{PANEL};") + tb_h = QHBoxLayout(tb_w) + tb_h.setContentsMargins(4, 0, 4, 0) + toolbar = NavigationToolbar2QT(canvas, tb_w) + toolbar.setStyleSheet(f"background:{PANEL}; color:{FG};") + tb_h.addWidget(toolbar) + root.addWidget(tb_w) + + self._canvas = canvas + + def _compute_psd_matrix(self, nperseg: int, window: str): + sigs = self._r["signals_sampled"] + timedata = self._r["timedata"] + dt_ms = float(np.median(np.diff(timedata))) + fs_est = 1.0 / (dt_ms * 1e-3) + + n_diodes = sigs.shape[0] + freqs, _ = welch(sigs[0], fs=fs_est, nperseg=nperseg, window=window) + psd_mat = np.empty((n_diodes, len(freqs)), dtype=np.float32) + for i in range(n_diodes): + _, p = welch(sigs[i].astype(np.float64), + fs=fs_est, nperseg=nperseg, window=window) + psd_mat[i] = p.astype(np.float32) + + return freqs, psd_mat, fs_est + + def _compute_and_plot(self): + nperseg = int(self._nperseg_combo.currentText()) + window = self._win_combo.currentText() + self._freqs, self._psd, self._fs = self._compute_psd_matrix(nperseg, window) + self._draw() + + def _replot(self): + self._compute_and_plot() + + def _draw(self): + r = self._r + freqs = self._freqs + psd = self._psd + outlier_mask = r["outlier_mask"] + n_diodes = psd.shape[0] + x = np.arange(n_diodes) + cmap = self._cmap_combo.currentText() + + fmax_txt = self._fmax_combo.currentText().replace(" ", "") + freq_mask = np.ones(len(freqs), dtype=bool) if fmax_txt == "All" \ + else freqs <= float(fmax_txt) + freqs_plt = freqs[freq_mask] + psd_plt = psd[:, freq_mask] + + total_power = psd_plt.sum(axis=1) + spec_entropy = np.array([ + float(scipy_entropy(psd_plt[i] / (psd_plt[i].sum() + 1e-30))) + for i in range(n_diodes) + ], dtype=np.float32) + dom_freq = freqs_plt[np.argmax(psd_plt, axis=1)] + + self._fig.clf() + gs = gridspec.GridSpec(3, 2, figure=self._fig, + height_ratios=[3, 1, 1], width_ratios=[30, 1], + hspace=0.52, wspace=0.03, + left=0.07, right=0.95, top=0.93, bottom=0.07) + ax_heat = self._fig.add_subplot(gs[0, 0]) + ax_cbar = self._fig.add_subplot(gs[0, 1]) + ax_power = self._fig.add_subplot(gs[1, 0]) + ax_entr = self._fig.add_subplot(gs[2, 0]) + + for ax in (ax_heat, ax_power, ax_entr): + ax.set_facecolor(PANEL) + ax.grid(True, alpha=0.35) + + self._fig.suptitle( + f"Spectral Analysis — PID: {r['pid']} | " + f"window={self._win_combo.currentText()} " + f"nperseg={self._nperseg_combo.currentText()} " + f"fs≈{self._fs:.0f} Hz", + color=FG, fontsize=10, y=0.985, + ) + + im = ax_heat.imshow( + np.log10(psd_plt.T + 1e-30), aspect="auto", origin="lower", + extent=[-0.5, n_diodes - 0.5, freqs_plt[0], freqs_plt[-1]], + cmap=cmap, interpolation="nearest", + ) + ax_heat.plot(x, dom_freq, color=ACCENT3, lw=1.2, ls="--", + alpha=0.8, label="Dominant freq / diode") + ax_heat.set_ylabel("Frequency (Hz)", color=FG) + ax_heat.set_title( + "Power Spectral Density [log₁₀(V²/Hz)] — each column is one diode", + color=FG, pad=6, fontsize=9) + ax_heat.tick_params(labelbottom=False) + ax_heat.legend(fontsize=7, loc="upper right") + + cb = self._fig.colorbar(im, cax=ax_cbar) + cb.set_label("log₁₀ PSD", color=FG, fontsize=8) + cb.ax.yaxis.set_tick_params(color=FG_DIM, labelsize=7) + plt.setp(cb.ax.yaxis.get_ticklabels(), color=FG_DIM) + + ax_power.fill_between(x, total_power, alpha=0.20, color=ACCENT) + ax_power.plot(x, total_power, color=ACCENT, lw=1.5, + label="Total spectral power") + ax_power.set_ylabel("Total power\n(V²/Hz)", color=FG, fontsize=8) + ax_power.tick_params(labelbottom=False) + + ax_entr.fill_between(x, spec_entropy, alpha=0.20, color=ACCENT2) + ax_entr.plot(x, spec_entropy, color=ACCENT2, lw=1.5, + label="Spectral entropy") + ax_entr.set_ylabel("Entropy\n(nats)", color=FG, fontsize=8) + ax_entr.set_xlabel("Diode index", color=FG) + + if outlier_mask.any(): + out_idx = np.where(outlier_mask)[0] + for ax in (ax_heat, ax_power, ax_entr): + for idx in out_idx: + ax.axvspan(idx - 0.5, idx + 0.5, + color=ACCENT4, alpha=0.22, linewidth=0, zorder=0) + ax_power.scatter(out_idx, total_power[out_idx], + color=ACCENT4, s=50, zorder=6, + label=f"Outliers ({len(out_idx)})") + ax_entr.scatter(out_idx, spec_entropy[out_idx], + color=ACCENT4, s=50, zorder=6, + label=f"Outliers ({len(out_idx)})") + + for ax in (ax_power, ax_entr): + ax.legend(fontsize=7, loc="upper right") + for ax in (ax_heat, ax_power, ax_entr): + ax.set_xlim(-0.5, n_diodes - 0.5) + + n_out = int(outlier_mask.sum()) + self._info_lbl.setText( + f"{n_diodes} diodes | {n_out} flagged | " + f"{len(freqs_plt)} freq bins | fs ≈ {self._fs:.0f} Hz" + ) + self._canvas.draw_idle() diff --git a/src/XMCTSGuard/gui/workers.py b/src/XMCTSGuard/gui/workers.py new file mode 100644 index 0000000..7353596 --- /dev/null +++ b/src/XMCTSGuard/gui/workers.py @@ -0,0 +1,36 @@ +# ───────────────────────────────────────────────────────────────────────────── +# Background worker +# ───────────────────────────────────────────────────────────────────────────── + +from PyQt6.QtCore import QObject, pyqtSignal +from ..analysis.processors import run_analysis + +class AnalysisWorker(QObject): + progress = pyqtSignal(str) + finished = pyqtSignal(dict) + error = pyqtSignal(str) + + def __init__(self, pid, model_path, min_data, max_data, gain_ratio, + z_thresh=0.2): + super().__init__() + self.pid = pid + self.model_path = model_path + self.min_data = min_data + self.max_data = max_data + self.gain_ratio = gain_ratio + self.z_thresh = z_thresh + + def run(self): + try: + results = run_analysis( + self.pid, self.model_path, + self.min_data, self.max_data, self.gain_ratio, + z_thresh = self.z_thresh, + progress_cb = self.progress.emit, + ) + self.finished.emit(results) + except Exception: + import traceback + self.error.emit(traceback.format_exc()) + + diff --git a/src/XMCTSGuard/main.py b/src/XMCTSGuard/main.py new file mode 100644 index 0000000..69c3f93 --- /dev/null +++ b/src/XMCTSGuard/main.py @@ -0,0 +1,28 @@ +# src/my_app/main.py +import sys +from .gui.main_window import WorkflowGUI +from .engine.model import AutoEncoder # Optional: if you want to pre-load + +def start_app(): + """ + The entry point function that initializes everything. + """ + # 1. Initialize the GUI Application object + # (Example using PyQt/PySide logic) + from PyQt6.QtWidgets import QApplication + app = QApplication(sys.argv) + + # # 2. Optional: Initialize the Engine or Analysis logic + # # You can pass these into the GUI class so the GUI "owns" the engine. + # model = AutoEncoder() + + # 3. Create the Main Window + # We pass the model to the window so it can call inference later + window = WorkflowGUI() + window.show() + + # 4. Start the event loop + sys.exit(app.exec()) + +if __name__ == "__main__": + start_app() \ No newline at end of file diff --git a/src/XMCTSGuard/utils.py b/src/XMCTSGuard/utils.py new file mode 100644 index 0000000..299c774 --- /dev/null +++ b/src/XMCTSGuard/utils.py @@ -0,0 +1,250 @@ +import os +import h5py +import numpy as np + + +def format_pid(pid: str) -> str: + """ + Format a program ID (e.g. '20250305.50') into a zero-padded directory name + (e.g. '20250305_050'). + """ + head, sep, tail = pid.strip().rpartition('.') + if sep: + frac = tail + if frac.isdigit() and len(frac) < 3: + frac = frac.zfill(3) + return f"{head}_{frac}" + return pid.replace('.', '_') + + +def read_h5f_directory(h5py_path: str, decimate: int = 100) -> dict: + """ + Read all .h5f files in the given directory and return a dictionary of datasets. + + - Files ending in _t000, _t090, _t180, _t270 are treated as reference files: + only the time base (dataset ending in '0') is extracted from them. + - All other .h5f files have their full XMCTSdata content loaded (excluding 'timedata'). + + Parameters + ---------- + h5py_path : str + Path to the directory containing the .h5f files. + decimate : int + Takes data every n = decimate entries + + Returns + ------- + dict + Dictionary mapping dataset names to numpy arrays. + Includes a 'timedata' key from the reference files. + """ + REFERENCE_SUFFIXES = ("_t000.h5f", "_t090.h5f", "_t180.h5f", "_t270.h5f") + data_dict = {} + length = np.inf + + # Check if the data has consistent length, otherwise cut it to the smallest length + for f in os.listdir(h5py_path): + # if there is adjusted in the name skip it + if f.__contains__('adjusted'): continue + h5f_file = os.path.join(h5py_path, f) + if f.endswith(".h5f"): + with h5py.File(h5f_file, "r") as h5f: + if "XMCTSdata" in h5f: + for dataset in h5f["XMCTSdata"].keys(): + if dataset != "timedata": + length_tmp = h5f["XMCTSdata"][dataset][:].shape[0] + if length_tmp < length: + length = length_tmp + + for f in sorted(os.listdir(h5py_path)): + h5f_file = os.path.join(h5py_path, f) + # if there is adjusted in the name skip it + if f.__contains__('adjusted'): continue + + # Reference files: extract time base only + if any(f.endswith(s) for s in REFERENCE_SUFFIXES): + with h5py.File(h5f_file, "r") as h5f: + if "XMCTSdata" in h5f: + for dataset in h5f["XMCTSdata"].keys(): + if dataset.endswith("000"): + data_dict["timedata"] = h5f["XMCTSdata"][dataset][:length:decimate] + continue + + # Data files: extract all datasets except 'timedata' + if f.endswith(".h5f"): + with h5py.File(h5f_file, "r") as h5f: + if "XMCTSdata" in h5f: + for dataset in h5f["XMCTSdata"].keys(): + if dataset != "timedata": + data_dict[dataset] = h5f["XMCTSdata"][dataset][:length:decimate] + + return data_dict + + +def save_tfiles(h5py_path: str, keyword: str = 'adjusted'): + """ + Duplicate specific HDF5 files in a directory with a modified naming convention. + + Iterates through a directory to find files ending in specific suffixes + (0, 90, 180, 270). For each match, it creates a copy where the middle + section of the filename is replaced by the provided keyword. + + Parameters + ---------- + h5py_path : str + The system path to the directory containing the .h5f files. + keyword : str, optional + The string to insert into the new filename (default is 'adjusted'). + This replaces the variable middle segment of the original filename. + + Returns + ------- + None + Copies are created directly on the filesystem. + """ + import shutil + import os + + REFERENCE_SUFFIXES = ("_t000.h5f", "_t090.h5f", "_t180.h5f", "_t270.h5f") + for f in sorted(os.listdir(h5py_path)): + if f.endswith(REFERENCE_SUFFIXES): + h5f_file = os.path.join(h5py_path, f) + + # Split and rebuild filename logic + parts = f.split('_') + exp_num = parts[1][:3] + new_f = f"{parts[0]}_{exp_num}{keyword}_{parts[-1]}" + + new_h5f_file = os.path.join(h5py_path, new_f) + shutil.copy2(h5f_file, new_h5f_file) + + +def save_xfiles(h5py_path: str, adjusted_data: np.ndarray, keyword: str = 'adjusted'): + """ + Duplicate HDF5 files and update specific internal datasets with adjusted data. + + This function iterates through a directory, skipping specific reference + orientation files. For all other files, it creates a copy with a modified + filename containing a keyword. Inside each copy, it replaces the dataset + corresponding to a specific diode index (000-360) within the 'XMCTSdata' + group using the provided array. + + Parameters + ---------- + h5py_path : str + The system path to the directory containing the .h5f files. + adjusted_data : np.ndarray + The numerical array to be written into the 'XMCTSdata' dataset. + keyword : str, optional + The string to insert into the new filename (default is 'adjusted'). + This is appended to the 3-digit experiment ID extracted from the + original filename. + + Returns + ------- + None + New files are created and modified on the filesystem. + """ + import shutil + + REFERENCE_SUFFIXES = ("_t000.h5f", "_t090.h5f", "_t180.h5f", "_t270.h5f") + diodes = [f"{i:03}" for i in range(361)] + count = 0 + + for f in sorted(os.listdir(h5py_path)): + # Process only files that are NOT the reference suffixes + if not f.endswith(REFERENCE_SUFFIXES): + print(f) + h5f_file = os.path.join(h5py_path, f) + + # Filename logic: + parts = f.split('_') + exp_num = parts[1][:3] + new_f = f"{parts[0]}_{exp_num}{keyword}_{parts[-1]}" + + new_h5f_file = os.path.join(h5py_path, new_f) + shutil.copy2(h5f_file, new_h5f_file) + + with h5py.File(new_h5f_file, 'r+') as nf: + # Replaces data in the dataset corresponding to the current count + # Example: nf['XMCTSdata']['000'] = adjusted_data + nf['XMCTSdata'][diodes[count]][...] = adjusted_data[count, :] + + count += 1 + + +def build_data_array(data_dict: dict) -> np.ndarray: + """ + Stack all arrays in the data dictionary into a 2D numpy array. + + The resulting shape is (n_channels, n_timepoints), where the first row + corresponds to 'timedata' and the remaining rows are the diode channels. + + Parameters + ---------- + data_dict : dict + Dictionary as returned by read_h5f_directory(). + + Returns + ------- + np.ndarray + 2D array of shape (n_channels, n_timepoints). + """ + return np.array(list(data_dict.values())) + + +def sort_sxr_data(data: np.ndarray) -> np.ndarray: + """ + Organize the stacked arrays so that the time base is sorted. + + Parameters + ---------- + data : np.ndarray + array returned by build_data_array() + + Returns + ------- + np.ndarray + Sorted 2D array of shape (n_channels, n_timepoints). + """ + sorted_indices = np.argsort(data[:, 0]) + return data[sorted_indices, :] + + +def get_sxr_data(): + raise NotImplementedError + + +def load_sxr_data(pid: str, base_path: str = "/home/IPP-HGW/orluca/devel/data/HDF/_data/OP2", + decimate: int = 1) -> np.ndarray: + """ + Full pipeline: given a program ID, load all SXR diode data and return + a 2D numpy array of shape (n_channels, n_timepoints). + + Parameters + ---------- + pid : str + Program ID, e.g. '20250305.50'. + base_path : str + Root directory where the HDF data folders are stored. + + Returns + ------- + np.ndarray + 2D array of shape (n_channels, n_timepoints). + """ + pid_formatted = format_pid(pid) + h5py_path = os.path.join(base_path, pid_formatted, "") + data_dict = read_h5f_directory(h5py_path, decimate) + data = build_data_array(data_dict) + return data, h5py_path, data_dict + + +if __name__ == "__main__": + pid = "20221019.25" + data, h5py_path, data_dict = load_sxr_data(pid) + print(f"Loaded data array with shape: {data.shape}") + print(f"H5F path: {h5py_path}") + print("First time instant across all channels:") + for d in data[:, 0]: + print(d) diff --git a/src/XMCTSGuard/visualization/__init__.py b/src/XMCTSGuard/visualization/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/XMCTSGuard/visualization/gui_plots.py b/src/XMCTSGuard/visualization/gui_plots.py new file mode 100644 index 0000000..e69de29 diff --git a/src/XMCTSGuard/visualization/plots.py b/src/XMCTSGuard/visualization/plots.py new file mode 100644 index 0000000..e3ae485 --- /dev/null +++ b/src/XMCTSGuard/visualization/plots.py @@ -0,0 +1,1330 @@ +import os +import torch +import numpy as np +import pandas as pd + +import os +from pyexpat import model + +import numpy as np +import pandas as pd +import torch +import umap + +# These imports are for the latent space clustering +from sklearn.cluster import KMeans, DBSCAN +from sklearn.mixture import GaussianMixture +from sklearn.decomposition import PCA +from sklearn.manifold import TSNE +from sklearn.metrics import silhouette_score, adjusted_rand_score + +# These imports are for visualization +import seaborn as sns +import matplotlib.pyplot as plt +from matplotlib.patches import Patch + + +# Global Variables +GAIN_PIDS = ["20250416.44", "20250416.30", "20250416.24", "20250410.45", "20250410.8", "20250408.46", + "20250408.43", "20250403.26", "20250403.25", "20250403.23", "20250403.20", "20250403.17", + "20250403.13", "20250402.46", "20250402.18", "20250402.16", "20250402.14", "20250402.13", + "20250401.78", "20250401.77", "20250401.70", "20250401.60", "20250401.53", "20250401.49", + "20241128.69", "20241128.70"] + +DETECTED_FAULTS = ['20250305.40' '20250305.50' '20250312.107' '20250312.114' '20250312.116' + '20250312.119' '20250312.91' '20250312.93' '20250319.62' '20250319.65' + '20250319.69' '20250319.75' '20250319.76' '20250319.78' '20250319.89' + '20250325.104' '20250325.88' '20250326.102' '20250326.105' '20250401.49' + '20250401.53' '20250401.70' '20250401.77' '20250401.78' '20250402.13' + '20250402.14' '20250402.16' '20250402.18' '20250402.46' '20250402.62' + '20250402.79' '20250402.8' '20250402.82' '20250403.13' '20250403.17' + '20250403.20' '20250403.23' '20250403.26' '20250403.54' '20250409.21' + '20250409.22' '20250409.47' '20250410.5' '20250415.49' '20250415.50' '20250415.76'] + + +def plot_latent_space(encoder, data_loader, device, save_path=None): + """ + Plots the 2D latent space of the encoder. + + Args: + encoder (torch.nn.Module): The encoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + save_path (str, optional): Path to save the plot. If None, the plot is shown instead. + + Returns: + None + """ + encoder.eval() + latents = [] + labels = [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = encoder(profiles) + latents.append(z.cpu().numpy()) + labels.append(np.zeros(z.size(0))) # Dummy labels, modify as needed + + latents = np.concatenate(latents, axis=0) + labels = np.concatenate(labels, axis=0) + + plt.figure(figsize=(8, 6)) + scatter = plt.scatter(latents[:, 0], latents[:, 1], c=labels, cmap='viridis', alpha=0.7) + plt.colorbar(scatter) + plt.title('2D Latent Space') + plt.xlabel('Latent Dimension 1') + plt.ylabel('Latent Dimension 2') + + if save_path: + plt.savefig(save_path) + print(f"Latent space plot saved to {save_path}") + else: + plt.show() + +def plot_latent_reconstruction(encoder, decoder, data_loader, device, num_samples=5, save_path=None): + """ + Plots original and reconstructed samples from the autoencoder. + + Args: + encoder (torch.nn.Module): The encoder model. + decoder (torch.nn.Module): The decoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + num_samples (int): Number of samples to plot. + save_path (str, optional): Path to save the plot. If None, the plot is shown instead. + + Returns: + None + """ + encoder.eval() + decoder.eval() + + with torch.no_grad(): + for i, batch in enumerate(data_loader): + batch = batch.to(device) + z = encoder(batch) + reconstructed = decoder(z) + + if i == 0: + originals = batch.cpu().numpy() + reconstructions = reconstructed.cpu().numpy() + else: + originals = np.concatenate((originals, batch.cpu().numpy()), axis=0) + reconstructions = np.concatenate((reconstructions, reconstructed.cpu().numpy()), axis=0) + + if originals.shape[0] >= num_samples: + break + + # Plotting + fig, axes = plt.subplots(num_samples, 2, figsize=(10, 2 * num_samples)) + for i in range(num_samples): + axes[i, 0].imshow(originals[i].transpose(1, 2, 0)) + axes[i, 0].set_title("Original") + axes[i, 0].axis("off") + + axes[i, 1].imshow(reconstructions[i].transpose(1, 2, 0)) + axes[i, 1].set_title("Reconstructed") + axes[i, 1].axis("off") + + if save_path: + plt.savefig(save_path) + print(f"Latent space plot saved to {save_path}") + else: + plt.show() + +def interactive_latent_space(model, data_loader, device): + """ + Creates an interactive plot for the latent space of the encoder. + + Args: + encoder (torch.nn.Module): The encoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + + Returns: + None + """ + model.encoder.eval() + latents = [] + originals = [] + pids = [] + times = [] + # cameras = [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = model.encoder(profiles) + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + # try: + # cameras.append(batch['camera']) + # except KeyError: + # cameras.append(None) + + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + pids = np.concatenate(pids, axis=0) + times = np.concatenate(times, axis=0) + # if cameras is not None: + # cameras = np.concatenate(cameras, axis=0) + + fig, ax = plt.subplots(figsize=(8, 6)) + scatter = ax.scatter(latents[:, 0], latents[:, 1], c='blue', alpha=0.7) + ax.set_title("Interactive Latent Space") + ax.set_xlabel("Latent Dimension 1") + ax.set_ylabel("Latent Dimension 2") + + def onpick(event): + ind = event.ind[0] + z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + model.decoder.eval() + with torch.no_grad(): + recon = model.decoder(z).cpu().numpy()[0] + orig = originals[ind] + fig2 = plt.figure(figsize=(8, 4)) + plt.plot(np.arange(len(orig)), orig, marker='o', label="Original") + plt.plot(np.arange(len(recon)), recon, marker='x', label="Reconstructed") + + plt.title(f"PID: {pids[ind]} @ t = {times[ind]} s") + + fig.canvas.mpl_connect('pick_event', onpick) + scatter.set_picker(True) + plt.show() + +def interactive_latent_space_wflags(model, data_loader, device): + """ + Creates an interactive plot for the latent space of the encoder and adds a legend + based on the 'clipping' flag in each batch. + + Args: + model (torch.nn.Module): The model with encoder/decoder. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + + Returns: + None + """ + + model.encoder.eval() + latents = [] + originals = [] + pids = [] + times = [] + cameras = [] + clippings = [] + + model.eval() + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = model.encode(profiles) + if isinstance(z, tuple): + # If the output is a tuple, take the first element (the mean of the VAE) + z = z[0] + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + # cameras.append(batch['camera']) + clippings.append(batch['clipping']) + + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + pids = np.concatenate(pids, axis=0) + times = np.concatenate(times, axis=0) + # cameras = np.concatenate(cameras, axis=0) + clippings = np.concatenate(clippings, axis=0) + + # If clipping has extra dimensions (e.g., per-channel), reduce to per-sample boolean + if clippings.ndim > 1: + try: + clippings = np.any(clippings, axis=1) + except Exception: + # fallback: flatten if shapes don't align + print("Clipping shape mismatch, flattening.") + clippings = clippings.reshape((clippings.shape[0], -1)) + clippings = np.any(clippings, axis=1) + + # Map clipping boolean to colors and legend + gain_list = ["20250416.44", "20250416.30", "20250416.24", "20250410.45", "20250410.8", "20250408.46", + "20250408.43", "20250403.26", "20250403.25", "20250403.23", "20250403.20", "20250403.17", + "20250403.13", "20250402.46", "20250402.18", "20250402.16", "20250402.14", "20250402.13", + "20250401.78", "20250401.77", "20250401.70", "20250401.60", "20250401.53", "20250401.49",] + + colors = np.where(np.isin(pids, gain_list), 'green', np.where(clippings, 'red', 'blue')) # gains override clipping/color + + fig, ax = plt.subplots(figsize=(8, 6)) + print("Latent space dimensions:", latents.shape[1]) + scatter = ax.scatter(latents[:, 0], latents[:, 2], c=colors, alpha=0.7) # here one can decide which dimensions to plot on a 2D plane + ax.set_title("Interactive Latent Space (colored by clipping)") + ax.set_xlabel("Latent Dimension 1") + ax.set_ylabel("Latent Dimension 2") + + # Legend patches + handles = [ + Patch(color='red', label='Clipped'), + Patch(color='blue', label='Not clipped'), + Patch(color='green', label='Gain') + ] + ax.legend(handles=handles, title="Clipping") + + def onpick(event): + # event.ind can be a list of indices; pick the first + inds = getattr(event, "ind", None) + if not inds: + return + ind = inds[0] + z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + model.eval() + with torch.no_grad(): + recon = model.decode(z).cpu().numpy()[0] + orig = originals[ind] + plt.figure(figsize=(8, 4)) + plt.plot(np.arange(len(orig)), orig, marker='o', label="Original") + plt.plot(np.arange(len(recon)), recon, marker='x', label="Reconstructed") + plt.title(f"PID: {pids[ind]} @ t = {times[ind]} s | Clipped: {bool(clippings[ind])}") + plt.legend() + plt.show() + + fig.canvas.mpl_connect('pick_event', onpick) + scatter.set_picker(True) + plt.show() + + +def violin_plot(model, data_loader, device): + """ + Plots the distribution of latent spaces with dim > 2 by class. + + Args: + model (torch.nn.Module): The autoencoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + + Returns: + None + """ + model.encoder.eval() + latents = [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = model.encoder(profiles) + latents.append(z.cpu().numpy()) + + latents = np.concatenate(latents, axis=0) + print(latents.shape) + + # Make a dataframe from the latents for seaborn + df = pd.DataFrame(latents, columns=[f"Dim {i}" for i in range(latents.shape[1])]) + + # Create the violin plots + plt.figure(figsize=(12, 6)) + sns.violinplot(data=df, inner="quartile") + plt.title("Latent Space Distribution") + plt.xlabel(f"Latent Dimensions") + plt.ylabel("Density") + plt.show() + +def PairwiseScatterMatrix(model, data_loader, device): + model.eval() + latents, originals = [], [] + pids, times, cameras, mag_confs, clippings = [], [], [], [], [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = model.encoder(profiles) + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + cameras.append(batch['camera']) + mag_confs.append(batch['mag_conf']) + clippings.append(batch['clipping']) + + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + + meta = { + "camera": np.concatenate(cameras, axis=0), + "mag_conf": np.concatenate(mag_confs, axis=0), + "clipping": np.any(np.concatenate(clippings, axis=0), axis=1) + } + + df = pd.DataFrame(latents, columns=[f"Dim {i}" for i in range(latents.shape[1])]) + for k, v in meta.items(): + df[k] = v + + # Only use latent dimensions for the axes + latent_cols = [c for c in df.columns if c.startswith("Dim ")] + + # --- Create all pairplots at once --- + for key in meta.keys(): + print(f"Generating pairplot colored by: {key}") + grid = sns.pairplot( + df[latent_cols + [key]], + hue=key, + corner=True, + palette="tab10", + plot_kws={'alpha': 0.6, 's': 20} + ) + grid.figure.suptitle(f"Pairwise Scatter Matrix Colored by '{key}'", y=1.02) + grid.figure.tight_layout() + plt.savefig(f"pairplot_{key}.png") + plt.show(block=False) + +def PairwiseScatterMatrix(model, data_loader, device): + model.eval() + latents = [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = model.encoder(profiles) + latents.append(z.cpu().numpy()) + + latents = np.concatenate(latents, axis=0) + + # DataFrame with only latent dimensions + df = pd.DataFrame(latents, columns=[f"Dim {i}" for i in range(latents.shape[1])]) + + # Simple pairwise scatter matrix without any labeling + grid = sns.pairplot(df, corner=True, plot_kws={'alpha': 0.6, 's': 20}) + grid.figure.suptitle("Pairwise Scatter Matrix of Latent Dimensions", y=1.02) + grid.figure.tight_layout() + plt.show() + +def LabeledPairwiseScatterMatrix(model, data_loader, device): + model.eval() + latents, originals = [], [] + pids, times, cameras, mag_confs, clippings = [], [], [], [], [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = model.encoder(profiles) + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + cameras.append(batch['camera']) + mag_confs.append(batch['mag_conf']) + clippings.append(batch['clipping']) + + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + + meta = { + "camera": np.concatenate(cameras, axis=0), + "mag_conf": np.concatenate(mag_confs, axis=0), + "clipping": np.any(np.concatenate(clippings, axis=0), axis=1) + } + + df = pd.DataFrame(latents, columns=[f"Dim {i}" for i in range(latents.shape[1])]) + for k, v in meta.items(): + df[k] = v + + # Only use latent dimensions for the axes + latent_cols = [c for c in df.columns if c.startswith("Dim ")] + + # --- Create all pairplots at once --- + for key in meta.keys(): + print(f"Generating pairplot colored by: {key}") + grid = sns.pairplot( + df[latent_cols + [key]], + hue=key, + corner=True, + palette="tab10", + plot_kws={'alpha': 0.6, 's': 20} + ) + grid.figure.suptitle(f"Pairwise Scatter Matrix Colored by '{key}'", y=1.02) + grid.figure.tight_layout() + plt.savefig(f"pairplot_{key}.png") + plt.show(block=False) + +def UMAP_latent_space(model, data_loader, device, n_neighbors=15, min_dist=0.1, n_components=2, metric='euclidean', save_path=None): + """ + Applies UMAP to the latent space and plots the result. + + Args: + model (torch.nn.Module): The autoencoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + n_neighbors (int): Number of neighbors for UMAP. + min_dist (float): Minimum distance for UMAP. + n_components (int): Number of dimensions for UMAP. + metric (str): Metric for UMAP. + save_path (str, optional): Path to save the plot. If None, the plot is shown instead. + + Returns: + None + """ + model.encoder.eval() + latents = [] + + # Collect originals and metadata for interaction + populate latent space + originals = [] + pids = [] + times = [] + cameras = [] + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + z = model.encoder(profiles) + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + cameras.append(batch['camera']) + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + pids = np.concatenate(pids, axis=0) + times = np.concatenate(times, axis=0) + cameras = np.concatenate(cameras, axis=0) + reducer = umap.UMAP(n_neighbors=n_neighbors, min_dist=min_dist, n_components=n_components, metric=metric) + embedding = reducer.fit_transform(latents) + + # Interactive UMAP embedding plot + if n_components == 2: + fig, ax = plt.subplots(figsize=(8, 6)) + scatter = ax.scatter(embedding[:, 0], embedding[:, 1], c='blue', alpha=0.7) + ax.set_title("UMAP Projection of Latent Space") + ax.set_xlabel("UMAP Dimension 1") + ax.set_ylabel("UMAP Dimension 2") + + def onpick(event): + ind = event.ind[0] + z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + model.decoder.eval() + with torch.no_grad(): + recon = model.decoder(z).cpu().numpy()[0] + orig = originals[ind] + fig2 = plt.figure(figsize=(8, 4)) + plt.plot(np.arange(len(orig)), orig, marker='o', label="Original") + plt.plot(np.arange(len(recon)), recon, marker='x', label="Reconstructed") + plt.title(f"PID: {pids[ind]} @ t = {times[ind]} s | Camera: {cameras[ind]}") + plt.legend() + plt.show() + + fig.canvas.mpl_connect('pick_event', onpick) + scatter.set_picker(True) + if save_path: + plt.savefig(save_path) + else: + plt.show() + + elif n_components == 3: + """ + 3D UMAP projection, understand why it is not working + """ + from mpl_toolkits.mplot3d import Axes3D + fig = plt.figure() + ax = Axes3D(fig) + ax.scatter(embedding[:, 0], embedding[:, 1], embedding[:, 2]) + # scatter = ax.scatter(embedding[:, 0], embedding[:, 1], embedding[:, 2]) + ax.set_title("UMAP Projection of Latent Space") + ax.set_xlabel("UMAP Dimension 1") + ax.set_ylabel("UMAP Dimension 2") + ax.set_zlabel("UMAP Dimension 3") + + # def onpick(event): + # ind = event.ind[0] + # z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + # model.decoder.eval() + # with torch.no_grad(): + # recon = model.decoder(z).cpu().numpy()[0] + # orig = originals[ind] + # fig2 = plt.figure(figsize=(8, 4)) + # plt.plot(np.arange(len(orig)), orig, marker='o', label="Original") + # plt.plot(np.arange(len(recon)), recon, marker='x', label="Reconstructed") + # plt.title(f"PID: {pids[ind]} @ t = {times[ind]} s | Camera: {cameras[ind]}") + # plt.legend() + # plt.show() + + # fig.canvas.mpl_connect('pick_event', onpick) + # scatter.set_picker(True) + if save_path: + plt.savefig(save_path) + else: + plt.show() + + else: + print("Number of components not implemented") + +def VAEviolin_plot(model, data_loader, device): + """ + Plots the distribution of latent spaces with dim > 2 by class. + + Args: + model (torch.nn.Module): The autoencoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + + Returns: + None + """ + model.eval() + latents = [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + mu, logvar = model.encoder(profiles) + z = model.reparametrize(mu, logvar) + latents.append(z.cpu().numpy()) + + latents = np.concatenate(latents, axis=0) + print(latents.shape) + + # Make a dataframe from the latents for seaborn + df = pd.DataFrame(latents, columns=[f"Dim {i}" for i in range(latents.shape[1])]) + + # Create the violin plots + plt.figure(figsize=(12, 6)) + sns.violinplot(data=df, inner="quartile") + plt.title("Latent Space Distribution") + plt.xlabel(f"Latent Dimensions") + plt.ylabel("Density") + plt.show() + +def VAEPairwiseScatterMatrix(model, data_loader, device): + """ + Plots the pairwise scatter matrix of the latent space dimensions. + + Args: + model (torch.nn.Module): The autoencoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + + Returns: + None + """ + model.eval() + latents = [] + originals = [] + pids = [] + times = [] + cameras = [] + mag_confs = [] + clippings = [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + mu, logvar = model.encode(profiles) + z = model.reparametrize(mu, logvar) + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + cameras.append(batch['camera']) + mag_confs.append(batch['mag_conf']) + clippings.append(batch['clipping']) + + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + pids = np.concatenate(pids, axis=0) + times = np.concatenate(times, axis=0) + cameras = np.concatenate(cameras, axis=0) + mag_confs = np.concatenate(mag_confs, axis=0) + clippings = np.concatenate(clippings, axis=0) + + df = pd.DataFrame(latents, columns=[f"Dim {i}" for i in range(latents.shape[1])]) + + # Plot pairwise scatter matrix and make it interactive + axes = sns.pairplot(df) + plt.suptitle("Pairwise Scatter Matrix of Latent Dimensions", y=1.02) + plt.tight_layout() + + # Attach pick event to all scatter axes + def onpick(event): + ind = event.ind[0] + z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + with torch.no_grad(): + recon = model.decode(z).cpu().numpy()[0] + orig = originals[ind] + fig2 = plt.figure(figsize=(8, 4)) + plt.plot(np.arange(len(orig)), orig, marker='o', label="Original") + plt.plot(np.arange(len(recon)), recon, marker='x', label="Reconstructed") + plt.title(f"PID: {pids[ind]} @ t = {times[ind]} s | Camera: {cameras[ind]}") + plt.legend() + plt.show() + + # Find all scatter plots in the pairplot and set picker + for ax in axes.axes.flatten(): + for coll in ax.collections: + coll.set_picker(True) + + axes.fig.canvas.mpl_connect('pick_event', onpick) + plt.show() + +def VAEUMAP_latent_space(model, data_loader, device, n_neighbors=15, min_dist=0.1, n_components=2, metric='euclidean', save_path=None): + """ + Applies UMAP to the latent space and plots the result. + + Args: + model (torch.nn.Module): The autoencoder model. + data_loader (torch.utils.data.DataLoader): DataLoader for the dataset. + device (torch.device): Device to run the model on. + n_neighbors (int): Number of neighbors for UMAP. + min_dist (float): Minimum distance for UMAP. + n_components (int): Number of dimensions for UMAP. + metric (str): Metric for UMAP. + save_path (str, optional): Path to save the plot. If None, the plot is shown instead. + + Returns: + None + """ + model.eval() + latents = [] + + # Collect originals and metadata for interaction + populate latent space + originals = [] + pids = [] + times = [] + cameras = [] + with torch.no_grad(): + for batch in data_loader: + profiles = batch['profile'].to(device) + mu, logvar = model.encode(profiles) + z = model.reparametrize(mu, logvar) + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + cameras.append(batch['camera']) + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + pids = np.concatenate(pids, axis=0) + times = np.concatenate(times, axis=0) + cameras = np.concatenate(cameras, axis=0) + reducer = umap.UMAP(n_neighbors=n_neighbors, min_dist=min_dist, n_components=n_components, metric=metric) + embedding = reducer.fit_transform(latents) + + # Interactive UMAP embedding plot + if n_components == 2: + fig, ax = plt.subplots(figsize=(8, 6)) + scatter = ax.scatter(embedding[:, 0], embedding[:, 1], c='blue', alpha=0.7) + ax.set_title("UMAP Projection of Latent Space") + ax.set_xlabel("UMAP Dimension 1") + ax.set_ylabel("UMAP Dimension 2") + + def onpick(event): + ind = event.ind[0] + z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + with torch.no_grad(): + recon = model.decode(z).cpu().numpy()[0] + orig = originals[ind] + fig2 = plt.figure(figsize=(8, 4)) + plt.plot(np.arange(len(orig)), orig, marker='o', label="Original") + plt.plot(np.arange(len(recon)), recon, marker='x', label="Reconstructed") + plt.title(f"PID: {pids[ind]} @ t = {times[ind]} s | Camera: {cameras[ind]}") + plt.legend() + plt.show() + + fig.canvas.mpl_connect('pick_event', onpick) + scatter.set_picker(True) + if save_path: + plt.savefig(save_path) + else: + plt.show() + + elif n_components == 3: + """ + 3D UMAP projection, understand why it is not working + """ + from mpl_toolkits.mplot3d import Axes3D + fig = plt.figure() + ax = Axes3D(fig) + ax.scatter(embedding[:, 0], embedding[:, 1], embedding[:, 2]) + # scatter = ax.scatter(embedding[:, 0], embedding[:, 1], embedding[:, 2]) + ax.set_title("UMAP Projection of Latent Space") + ax.set_xlabel("UMAP Dimension 1") + ax.set_ylabel("UMAP Dimension 2") + ax.set_zlabel("UMAP Dimension 3") + + # def onpick(event): + # ind = event.ind[0] + # z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + # with torch.no_grad(): + # recon = model.decode(z).cpu().numpy()[0] + # orig = originals[ind] + # fig2 = plt.figure(figsize=(8, 4)) + # plt.plot(np.arange(len(orig)), orig, marker='o', label="Original") + # plt.plot(np.arange(len(recon)), recon, marker='x', label="Reconstructed") + # plt.title(f"PID: {pids[ind]} @ t = {times[ind]} s | Camera: {cameras[ind]}") + # plt.legend() + # plt.show() + + # fig.canvas.mpl_connect('pick_event', onpick) + # scatter.set_picker(True) + if save_path: + plt.savefig(save_path) + else: + plt.show() + + else: + print("Number of components not implemented") + + +def plot_tensorboard_csv(directory, train_file: str ="train.csv", val_file: str ="val.csv", metric="Value", step_col="Step"): + """ + Searches for train.csv and val.csv in a directory and plots them together. + + Args: + directory (str): Path to the folder containing CSV files. + metric (str): Column name for the metric to plot (e.g., 'Value'). + step_col (str): Column name for the x-axis (usually 'Step'). + + Example: + plot_tensorboard_csvs("./logs") + """ + # Define expected filenames + csv_files = { + "Train": os.path.join(directory, train_file), + "Validation": os.path.join(directory, val_file) + } + + plt.figure(figsize=(8, 5)) + + found_any = False + + for label, file_path in csv_files.items(): + if os.path.exists(file_path): + df = pd.read_csv(file_path) + if step_col in df.columns and metric in df.columns: + plt.plot(df[step_col], df[metric], label=label) + found_any = True + else: + print(f"Skipping {file_path}: missing '{step_col}' or '{metric}' column.") + else: + print(f"{file_path} not found.") + + if found_any: + plt.title(f"{metric} vs {step_col}") + plt.xlabel(step_col) + plt.ylabel(metric) + plt.legend() + plt.grid(True, linestyle="--", alpha=0.6) + plt.tight_layout() + plt.show() + else: + print("No valid CSV files found to plot.") + +def compute_distance_embedding(model, dataloader, device): + """ + Computes pairwise distances between embeddings. + + Params: + model: The model used to encode the input data. + dataloader: The dataloader providing the input data. + device: The device to perform computations on (CPU or GPU). + + Returns: + A tensor containing the pairwise distances between embeddings. + """ + + # collect embeddings then compute full pairwise distances + embeds = [] + model.eval() + with torch.no_grad(): + for batch in dataloader: + x = batch['profile'].to(device) + z = model.encode(x) + embeds.append(z) # keep on device for cdist efficiency + zs = torch.cat(embeds, dim=0) # shape (N, D) + dists = torch.cdist(zs, zs, p=2) # shape (N, N), on device + return dists.cpu() + +def compute_distance_measure_reconstruction(model, dataloader, device): + """ + Computes the distance between original and reconstructed embeddings. + + Params: + model: The model used to encode the input data. + dataloader: The dataloader providing the input data. + device: The device to perform computations on (CPU or GPU). + + Returns: + A tensor containing the distances between original and reconstructed embeddings. + """ + # collect original and reconstructed embeddings + model.eval() + original = [] + reconstructed = [] + pids = [] + with torch.no_grad(): + for batch in dataloader: + x = batch['profile'].to(device) + recon = model(x) + reconstructed.append(recon) + original.append(x) + pids.append(batch['pid']) + dists = torch.norm(torch.stack(original) - torch.stack(reconstructed), dim=-1) # shape (N,), on device + pids = np.array(pids) + # Unravel both dists and pids + dists = dists.flatten() + pids = pids.flatten() + # save the data in a npz file + np.savez_compressed("reconstruction_distances.npz", dists=dists, pids=pids) + return dists.cpu(), pids + +def clustering_LatentSpace(model, dataloader, device): + # Assuming you have a trained autoencoder model and an encoder submodule + # Example for PyTorch: + # latent_vectors = encoder(torch.tensor(X).float()).detach().numpy() + + # Example for TensorFlow: + # latent_vectors = encoder.predict(X) + + # Step 1: Get latent features + model.eval() + with torch.no_grad(): + xs = [] + for batch in dataloader: + profiles = batch['profile'].to(device) + z = model.encode(profiles) + xs.append(z.cpu().numpy()) + xs = np.concatenate(xs, axis=0) + + # Step 2: (Optional) Dimensionality reduction for visualization or denoising + pca = PCA(n_components=min(20, xs.shape[1])) + latent_pca = pca.fit_transform(xs) + + # Step 3: Apply clustering + kmeans = KMeans(n_clusters=5, random_state=42) + cluster_labels = kmeans.fit_predict(latent_pca) + + # Optionally, try DBSCAN or GMM + # db = DBSCAN(eps=0.5, min_samples=5).fit(latent_pca) + # gmm = GaussianMixture(n_components=5).fit(latent_pca) + # cluster_labels = gmm.predict(latent_pca) + + # Step 4: Evaluate clustering performance + sil_score = silhouette_score(latent_pca, cluster_labels) + print(f"Silhouette Score: {sil_score:.3f}") + + # If ground-truth fault labels are known: + if 'y_true' in locals(): + ari = adjusted_rand_score(y_true, cluster_labels) + print(f"Adjusted Rand Index (vs true faults): {ari:.3f}") + + # Step 5: Visualize in 2D using t-SNE + tsne = TSNE(n_components=2, random_state=42) + latent_2d = tsne.fit_transform(latent_pca) + + plt.figure(figsize=(8,6)) + plt.scatter(latent_2d[:,0], latent_2d[:,1], c=cluster_labels, cmap='tab10', s=15) + plt.title("t-SNE of Encoded Data with Clusters") + plt.colorbar(label='Cluster') + plt.show() + + # Optional: visualize with true fault labels if available + if 'y_true' in locals(): + plt.figure(figsize=(8,6)) + plt.scatter(latent_2d[:,0], latent_2d[:,1], c=y_true, cmap='tab10', s=15) + plt.title("t-SNE of Encoded Data Colored by True Fault Labels") + plt.colorbar(label='True Fault Category') + plt.show() + +def interactive_latent_space_clusters( + model, + data_loader, + device, + n_clusters=5, + gain_pid='20250403.17' +): + model.encoder.eval() + latents, originals, pids, times, clippings = [], [], [], [], [] + + with torch.no_grad(): + for batch in data_loader: + profiles = batch["profile"].to(device) + z = model.encoder(profiles) + latents.append(z.cpu().numpy()) + originals.append(batch["profile"].cpu().numpy()) + pids.append(batch["pid"]) + times.append(batch["time"]) + clippings.append(batch["clipping"]) + + # Concatenate everything + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + pids = np.concatenate(pids, axis=0) + times = np.concatenate(times, axis=0) + clippings = np.concatenate(clippings, axis=0) + + if clippings.ndim > 1: + clippings = np.any(clippings, axis=1) + + # PCA + clustering + pca = PCA(n_components=min(20, latents.shape[1])) + latent_pca = pca.fit_transform(latents) + kmeans = KMeans(n_clusters=n_clusters, random_state=42) + cluster_labels = kmeans.fit_predict(latent_pca) + + # 2D visualization + tsne = TSNE(n_components=2, random_state=42, perplexity=30) + latent_2d = tsne.fit_transform(latent_pca) + + cmap = plt.get_cmap("tab10") + colors = np.array([cmap(i % 10) for i in cluster_labels]) + is_gain = (pids == gain_pid) + + fig, ax = plt.subplots(figsize=(9, 7)) + + # Plot 4 combinations efficiently + mask_normal = ~clippings & ~is_gain + mask_gain = ~clippings & is_gain + mask_clip = clippings & ~is_gain + mask_clip_gain = clippings & is_gain + + ax.scatter(latent_2d[mask_normal, 0], latent_2d[mask_normal, 1], + c=colors[mask_normal], marker='o', s=60, alpha=0.7, edgecolors='none', label='Normal') + ax.scatter(latent_2d[mask_gain, 0], latent_2d[mask_gain, 1], + c=colors[mask_gain], marker='o', s=60, alpha=0.7, edgecolors='green', linewidths=1.5, label='Gain') + ax.scatter(latent_2d[mask_clip, 0], latent_2d[mask_clip, 1], + c=colors[mask_clip], marker='x', s=60, alpha=0.7, label='Clipped') + ax.scatter(latent_2d[mask_clip_gain, 0], latent_2d[mask_clip_gain, 1], + c=colors[mask_clip_gain], marker='x', s=60, alpha=0.7, edgecolors='green', linewidths=1.5, label='Clipped + Gain') + + ax.set_title("Latent Space Clusters (Color=Cluster, Marker=Clipping, Edge=Gain)") + ax.set_xlabel("t-SNE Dim 1") + ax.set_ylabel("t-SNE Dim 2") + + # Legend + cluster_handles = [Patch(color=cmap(i % 10), label=f"Cluster {i}") for i in range(n_clusters)] + extra_handles = [ + Patch(facecolor='gray', label='Normal (o)'), + Patch(facecolor='gray', label='Clipped (x)'), + Patch(edgecolor='green', facecolor='none', label='Gain') + ] + ax.legend(handles=cluster_handles + extra_handles, title="Legend", bbox_to_anchor=(1.05, 1), loc='upper left') + + # Prepare scatter for interactive picking + scatter = ax.scatter(latent_2d[:, 0], latent_2d[:, 1], c='none', alpha=0) + scatter.set_picker(True) + + def onpick(event): + inds = getattr(event, "ind", None) + if not inds: + return + ind = inds[0] + z = torch.tensor(latents[ind:ind+1], dtype=torch.float32).to(device) + model.decoder.eval() + with torch.no_grad(): + recon = model.decoder(z).cpu().numpy()[0] + orig = originals[ind] + plt.figure(figsize=(8, 4)) + plt.plot(orig, label="Original", marker="o") + plt.plot(recon, label="Reconstructed", marker="x") + plt.title( + f"PID: {pids[ind]} | Time: {times[ind]} | " + f"Cluster: {cluster_labels[ind]} | Clipped: {bool(clippings[ind])} | Gain: {is_gain[ind]}" + ) + plt.legend() + plt.show() + + fig.canvas.mpl_connect("pick_event", onpick) + plt.tight_layout() + plt.show() + + return cluster_labels, latent_2d, latents + +def plot_profiles(model, dataloader, device, num_samples=5): + model.eval() + latents, originals = [], [] + pids, times = [], [] + + with torch.no_grad(): + for batch in dataloader: + x = batch['profile'].to(device) + z = model.encoder(x) + latents.append(z.cpu().numpy()) + originals.append(batch['profile'].cpu().numpy()) + pids.append(batch['pid']) + times.append(batch['time']) + + latents = np.concatenate(latents, axis=0) + originals = np.concatenate(originals, axis=0) + pids = np.concatenate(pids, axis=0) + times = np.concatenate(times, axis=0) + + for i in range(num_samples): + plt.figure(figsize=(8, 4)) + plt.plot(originals[i], label="Original", marker="o") + recon = model.decoder(torch.tensor(latents[i:i+1], dtype=torch.float32).to(device)).detach().cpu().numpy()[0] + plt.plot(recon, label="Reconstructed", marker="x") + plt.title(f"PID: {pids[i]} | Time: {times[i]}") + plt.legend() + plt.savefig(f"images/profile_{i}.png") + plt.close() + +def plot_profiles_byPID(model, dataloader, device, target_pid, num_samples=5): + ''' + Plot profiles for a specific PID. + ''' + model.eval() + with torch.no_grad(): + for batch in dataloader: + if target_pid in batch['pid']: + x = batch['profile'].to(device) + z = model.encoder(x) + recon = model.decoder(z).cpu().numpy() + pids = batch['pid'] + times = batch['time'] + count = 0 + for i, pid in enumerate(pids): + if pid == target_pid: + orig = x[i].cpu().numpy() + y_min = min(orig.min(), recon[i].min()) + y_max = max(orig.max(), recon[i].max()) + residuals = orig - recon[i] + + fig, axes = plt.subplots(3, 1, figsize=(14, 8)) + axes[0].plot(orig, label="Original", marker="*") + axes[0].set_title(f"Original Profile - PID: {pid} | Time: {times[i]}") + axes[0].set_ylim(y_min, y_max) + axes[0].legend() + axes[0].grid(True, alpha=0.3) + + axes[1].plot(recon[i], label="Reconstructed", marker="x") + axes[1].set_title(f"Reconstructed Profile - PID: {pid} | Time: {times[i]}") + axes[1].set_ylim(y_min, y_max) + axes[1].legend() + axes[1].grid(True, alpha=0.3) + + axes[2].plot(residuals, label="Residuals (Original - Reconstructed)", marker="o", color="red") + axes[2].set_title("Residuals") + axes[2].axhline(y=0, color='k', linestyle='--', alpha=0.3) + axes[2].legend() + axes[2].grid(True, alpha=0.3) + + plt.tight_layout() + plt.show() + count += 1 + if count >= num_samples: + break + +def plot_profiles_PID_and_time(data, pid, time, nprof=5): + ''' + Plot profiles for a specific PID and time. + + Params: + data: The dataset containing profiles, pids, and times. + pid: The PID to filter by. + time: The time to filter by. + nprof: The number of profiles to plot (default is 5). + ''' + + data = data[data.pids == pid] + print(f"Found {len(data)} profiles for PID: {pid}") + print(f"Available times for PID {pid}: {data['time']}") + time_index = np.isclose(data['time'], time, atol=1e-2) + time = data['time'][time_index] + if len(time) > 0: + profiles = data['profile'][time_index, :] # Assuming profile is stored as a 2D array (num_profiles, profile_length) + for i in range(min(len(profiles), nprof)): # Plot up to nprof profiles + plt.figure(figsize=(14, 8)) + plt.plot(profiles[i], label=f"PID: {pid} | Time: {time[i]}", marker="o") + plt.title(f"Profile - PID: {pid} | Time: {time[i]}") + plt.legend() + plt.grid(True, alpha=0.3) + plt.tight_layout() + plt.show() + else: + print(f"No profiles found for PID: {pid} at Time: {time}") + +def plot_profiles_PID_and_time_model(model, dataloader, device, target_pid, target_time, nprof=5): + ''' + Plot profiles for a specific PID and time, along with model reconstructions. + + Params: + model: The autoencoder model. + dataloader: The dataloader providing the dataset. + device: The device to perform computations on (CPU or GPU). + target_pid: The PID to filter by. + target_time: The time to filter by. + nprof: The number of profiles to plot (default is 5). + ''' + model.eval() + count = 0 + + with torch.no_grad(): + for batch in dataloader: + # Filter by target PID + pid_mask = np.array([pid == target_pid for pid in batch['pid']]) + if not np.any(pid_mask): + continue + + # Filter by target time + times = np.array(batch['time']) + time_mask = np.isclose(times, target_time, atol=1e-2) + mask = pid_mask & time_mask + + if not np.any(mask): + continue + + # Extract matching profiles + x = batch['profile'][mask].to(device) + recon = model(x).cpu().numpy() + originals = x.cpu().numpy() + matched_times = times[mask] + + if len(matched_times) == 0: + print(f"No profiles found for PID: {target_pid} at Time: {target_time}") + continue + + # Plot up to nprof profiles + for i in range(min(np.sum(mask), nprof)): + fig = plt.figure(figsize=(14, 8)) + plt.plot(recon[i], label="Reconstructed", marker="x", color="orange") + plt.title(f"Reconstructed Profile - PID: {target_pid} | Time: {matched_times[i]:.2f}") + plt.legend() + plt.grid(True, alpha=0.3) + plt.tight_layout() + plt.show() + + +def compute_std_dev_latent(model, dataloader, device): + ''' + Compute the standard deviation of the latent space representations. + Then plot them on a graph where the x is the latent dimension and the y the + associated standard deviation. + ''' + model.eval() + with torch.no_grad(): + latents = [] + for batch in dataloader: + x = batch['profile'].to(device) + z = model.encoder(x) + latents.append(z.cpu().numpy()) + latents = np.concatenate(latents, axis=0) + + # Plot the standard deviation of the latent space representations + std_dev = np.std(latents, axis=0) + plt.figure(figsize=(8, 4)) + plt.plot(std_dev, label="Standard Deviation", marker="o") + plt.title("Latent Space Standard Deviation") + plt.xlabel("Latent Dimension") + plt.ylabel("Standard Deviation") + plt.legend() + # plt.show() + plt.savefig("latent_std_dev.png") + + return std_dev + +def testAE(): + # For some old versions it may be necessary to specify the input_dim and geometry + # RAVEN + # model = AutoEncoder.load_from_checkpoint(r"\\share\mp\E5-Praktikanten\Orlandi_Luca\NNsrc\W7-X_QXT\Raven\AE17\version_8\best_model_.ckpt") + # LOCALE + # # In dim 17 + # model = AutoEncoder.load_from_checkpoint(r"\\share\mp\E5-Praktikanten\Orlandi_Luca\NNsrc\W7-X_QXT\AE17\version_14\best_model_.ckpt") + # # In dim 360 + model = AutoEncoder.load_from_checkpoint("/home/IPP-HGW/orluca/devel/classificator/W7-X_QXT/AE360/version_0/best_model_.ckpt") + # model = AutoEncoder.load_from_checkpoint(r"\\share\mp\E5-Praktikanten\Orlandi_Luca\NNsrc\W7-X_QXT\Raven\AE360\version_1\best_model_.ckpt") + + + # # Divided by camera + # dm = AEDataModule(data_dir="data", file_name='db_by_camera.npz', nprofiles=10000) + # All profile + dm = AEDataModule(data_dir="../data", file_name='20251028_all_data.npz', nprofiles=None, normalization_strategy='minmax') + dm.setup() + dm.get_pids(GAIN_PIDS) + # print(f"maximum value used for normalization: {dm.max_val}") + # print(f"minimum value used for normalization: {dm.min_val}") + + # # This is to find particular cases, this routine is not working properly!! + # train_loader = dm.train_dataloader() + # # see if in train_loader are cases with pid == '20250312.83' + # for batch in train_loader: + # if (batch['pid'] == '20250312.83'): + # print("Found matching PID in train_loader") + # else: + # print("Did not find matching PID in train_loader") + # assert False + + # test_loader = dm.test_dataloader() + test_loader = dm.full_dataloader() # i am using the full dataloader because these are profiles never seen by the model + + device = "cpu" + # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + # # print the model and do one iteration over the test set + # print(model) + # for batch in test_loader: + # x = batch['profile'].to(device) + # with torch.no_grad(): + # reconstructed = model(x) + # break + + # # # ------------------ Distance computations ------------------ # # # + # # check if a file for distances exists otherwise compute them + # if os.path.exists("reconstruction_distances.npz"): + # data = np.load("reconstruction_distances.npz") + # dists = data["dists"] + # pids = data["pids"] + # else: + # # First of all compute the distances + # print("Computing distances...") + # dists, pids = compute_distance_measure_reconstruction(model, test_loader, device) + + # # Once we have the distances and PIDs, we can use them for further analysis + # # See which PID has the largest distance besides "20250312.83" + # # print(np.where(pids == '20250312.83', False, True)) + # max_dist_idx = np.argmax(dists[np.where(pids == '20250312.83', False, True)]) + # print(f"PID with largest distance: {pids[max_dist_idx]}, Distance: {dists[max_dist_idx]}") + + # # Try with flags + # interactive_latent_space_wflags(model, test_loader, device) + + # # w/o + # interactive_latent_space(model, test_loader, device) + # violin_plot(model, test_loader, device) + # PairwiseScatterMatrix(model, test_loader, device) + # UMAP_latent_space(model, test_loader, device, n_components=2) + + # # Try clustering + # clustering_LatentSpace(model, test_loader, device) + # cluster_labels, latent_2d, latents = interactive_latent_space_clusters(model, test_loader, device) + + # # Compute std_dev + # compute_std_dev_latent(model, test_loader, device) + + # plot some profiles + plot_profiles(model, test_loader, device, num_samples=10) + +def testVAE(): + from model import VariationalAutoEncoder + # model = VariationalAutoEncoder.load_from_checkpoint(r"\\share\mp\E5-Praktikanten\Orlandi_Luca\NNsrc\W7-X_QXT\Raven\VAE360\version_9\best_model_.ckpt") + model = VariationalAutoEncoder.load_from_checkpoint(r"\\share\mp\E5-Praktikanten\Orlandi_Luca\QXT_NN\NNsrc\W7-X_QXT\Raven\VAE360\version_9\best_model_.ckpt") + + dm = AEDataModule(data_dir="data", file_name='20251028_all_data.npz', nprofiles=None) + dm.setup() + test_loader = dm.test_dataloader() + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + + # VAEviolin_plot(model, test_loader, device) + # VAEPairwiseScatterMatrix(model, test_loader, device) + # VAEUMAP_latent_space(model, test_loader, device, n_components=2) + + # Interactive latent space: + interactive_latent_space_wflags(model, test_loader, device) + + +if __name__ == "__main__": + + # # Use these functions to understand how the latent space looks like + testAE() + # testVAE() + + # # Use this function to plot losses + # plot_tensorboard_csv(r'\\share\mp\E5-Praktikanten\Orlandi_Luca\NNsrc\W7-X_QXT\Raven\AE17\version_2') diff --git a/src/XMCTSGuard/visualization/themes.py b/src/XMCTSGuard/visualization/themes.py new file mode 100644 index 0000000..ece16d2 --- /dev/null +++ b/src/XMCTSGuard/visualization/themes.py @@ -0,0 +1,13 @@ +import seaborn as sns +import matplotlib.pyplot as plt + +def apply_style(): + """ + Sets a global aesthetic for the entire library + """ + sns.set_theme( + context="notebook", + style="whitegrid", + palette="muted", + font_scale=1.2, + ) \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29