From d3f56e1382bfd574a7fc223e51138ba13b382d87 Mon Sep 17 00:00:00 2001 From: MaxRonce Date: Thu, 13 Jun 2024 15:10:01 +0200 Subject: [PATCH 01/16] add LICENSE --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /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. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From 2e01b82701280ce75b57f3651c79768efc720857 Mon Sep 17 00:00:00 2001 From: MaxRonce Date: Thu, 13 Jun 2024 15:11:46 +0200 Subject: [PATCH 02/16] Add files via upload --- ressources/CC-BY-NC-SA-4.0 | 437 +++++++++++++++++++++++++++++++++++++ 1 file changed, 437 insertions(+) create mode 100644 ressources/CC-BY-NC-SA-4.0 diff --git a/ressources/CC-BY-NC-SA-4.0 b/ressources/CC-BY-NC-SA-4.0 new file mode 100644 index 0000000..d60efe4 --- /dev/null +++ b/ressources/CC-BY-NC-SA-4.0 @@ -0,0 +1,437 @@ +Attribution-NonCommercial-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International +Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial-ShareAlike 4.0 International Public License +("Public License"). To the extent this Public License may be +interpreted as a contract, You are granted the Licensed Rights in +consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the +Licensor receives from making the Licensed Material available under +these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-NC-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution, NonCommercial, and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + l. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + m. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + n. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. From 5819911dda434c873e77d5f43143ae61dec98b37 Mon Sep 17 00:00:00 2001 From: mroncera Date: Mon, 13 May 2024 14:34:48 +0200 Subject: [PATCH 03/16] REFACTOR - move the optimisation tab to a separate module, add optimisation_tab.py --- src/view/gui.py | 3 ++- src/view/optimisation_tab.py | 41 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/view/optimisation_tab.py diff --git a/src/view/gui.py b/src/view/gui.py index ac45bbf..8f4be61 100644 --- a/src/view/gui.py +++ b/src/view/gui.py @@ -32,6 +32,7 @@ from src.controler.controller import CalculationController, STRATEGY_MAP from src.model.visualisation.create_tree import create_tree, add_title_description +from view.optimisation_tab import OptimisationTab ureg: UnitRegistry = UnitRegistry() @@ -843,7 +844,7 @@ def init_ui(self): self.param_tab = QWidget() # QWidget that will contain the parameters layout as a tab self.strategy_tab = QWidget() # QWidget that will contain the strategy selection layout as a tab self.spice_tab = QWidget() # QWidget that will contain the spice layout as a tab - self.optimisation_tab = QWidget() # QWidget that will contain the optimisation layout as a tab + self.optimisation_tab = OptimisationTab() # QWidget that will contain the optimisation layout as a tab self.EMC_tab = QWidget() # QWidget that will contain the EMC layout as a tab self.params_layout = QVBoxLayout(self.param_tab) diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py new file mode 100644 index 0000000..696f608 --- /dev/null +++ b/src/view/optimisation_tab.py @@ -0,0 +1,41 @@ +from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton, QMessageBox + + +class OptimisationTab(QWidget): + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + + def setup_ui(self): + self.layout = QVBoxLayout(self) + + self.label = QLabel("Welcome to the optimisation Tab !") + self.layout.addWidget(self.label) + + self.optimise_button = QPushButton("Optimise") + self.optimise_button.clicked.connect(self.on_optimise_clicked) + self.layout.addWidget(self.optimise_button) + + def on_optimise_clicked(self): + """Popup message box to confirm the optimisation.""" + + #show a message box inside a popup + msg = QMessageBox() + msg.setIcon(QMessageBox.Icon.Information) + msg.setText("Do you really want to start the optimisation process, it can take few minutes ?") + msg.setWindowTitle("Confirm") + msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) + msg.setDefaultButton(QMessageBox.StandardButton.No) + msg.buttonClicked.connect(self.on_message_box_clicked) + msg.exec() + + def on_message_box_clicked(self, button): + """Handle the message box button clicked event.""" + if button.text() == "&Yes": + print("Optimisation started !") + else: + print("Optimisation canceled !") + + + + From c2b254f03928bdb7420f31e46c345370d9d13a8a Mon Sep 17 00:00:00 2001 From: mroncera Date: Tue, 14 May 2024 10:54:18 +0200 Subject: [PATCH 04/16] Feature - add target on optimisation tab and add genetic optimisation --- src/controler/controller.py | 16 +- .../optimisation/genetic_optimisation.py | 151 ++++++++++++++++++ src/view/optimisation_tab.py | 144 +++++++++++++++-- 3 files changed, 299 insertions(+), 12 deletions(-) create mode 100644 src/model/optimisation/genetic_optimisation.py diff --git a/src/controler/controller.py b/src/controler/controller.py index 0229283..348ea7a 100644 --- a/src/controler/controller.py +++ b/src/controler/controller.py @@ -192,16 +192,30 @@ def __init__(self, params_dict=None, backups_count=3): input parameters of the engine. """ self.engine = CalculationEngine(backups_count=backups_count) + self.backup_count = backups_count self.is_data_ready = False self.params = None + self.STRATEGY_MAP = STRATEGY_MAP - for node_name, info in STRATEGY_MAP.items(): + for node_name, info in self.STRATEGY_MAP.items(): default_strategy = info["default"]() self.engine.add_or_update_node(node_name, default_strategy) if params_dict: self.update_parameters(params_dict) + def swap_strategy_map(self, strategy_map): + self.engine = CalculationEngine(backups_count=self.backup_count) + self.STRATEGY_MAP = strategy_map + + for node_name, info in self.STRATEGY_MAP.items(): + default_strategy = info["default"]() + self.engine.add_or_update_node(node_name, default_strategy) + + if self.params: + self.update_parameters(self.params) + + def delete_spice_nodes(self, spice_nodes : list): for node_name in spice_nodes: self.engine.delete_node(node_name) diff --git a/src/model/optimisation/genetic_optimisation.py b/src/model/optimisation/genetic_optimisation.py new file mode 100644 index 0000000..b8036fa --- /dev/null +++ b/src/model/optimisation/genetic_optimisation.py @@ -0,0 +1,151 @@ +import random + +import numpy as np +from PyQt6.QtCore import pyqtSignal, QThread +from deap import creator, base, tools, algorithms + +from model.optimisation.impedance_strategy_map import IMPEDANCE_STRATEGY_MAP +from src.controler.controller import CalculationController + +parameters_dict = { + # Initialize all required parameters + 'f_start': 1, + 'f_stop': 1000000, + 'nb_points_per_decade': 1000, + # Add other necessary parameters + 'mu_insulator': 1, + 'kapthon_thick': 30e-6, + 'insulator_thick': 10e-6, + 'diam_out_mandrel': 3.2e-3, + 'len_core': 20e-2, + 'diam_core': 3.2e-3, + 'mu_r': 100000, + 'rho_whire': 1.6, + 'coeff_expansion': 1, + 'stage_1_cutting_freq': 20000, + 'stage_2_cutting_freq': 20000, + 'gain_1_linear': 1, + 'gain_2_linear': 1, + 'mutual_inductance': 0.1, + 'feedback_resistance': 1000, + 'temperature': 300, + 'spice_resistance_test': 1000, + 'Para_A': 1, + 'Para_B': 1, + 'e_en': 1, + 'e_in': 1, + 'Alpha': 1, + "ray_spire": 5e-3, + "capa_tuning": 1e-12, + "capa_triwire": 10e-12 + } +class GeneticOptimisation(QThread): + update_signal = pyqtSignal(int, float, float) # generation, fitness average, best fitness + finished_signal = pyqtSignal(dict, float) # best parameters, resonance frequency + def __init__(self, population_size, generations, mutation_rate, parameters_dict, target_resonance_freq=2430): + super().__init__() + self.population_size = population_size + self.generations = generations + self.mutation_rate = mutation_rate + self.target_resonance_freq = target_resonance_freq + self.toolbox = None + + self.controller = CalculationController() + + # TODO : change this line + self.controller.swap_strategy_map(IMPEDANCE_STRATEGY_MAP) + + self.parameters_dict = parameters_dict + + self.init_creator() + + def update_target_resonance_freq(self, target_resonance_freq): + self.target_resonance_freq = target_resonance_freq + def determine_resonance_freq(self, freq_vector, impedance_vector): + index = impedance_vector.argmax() + return freq_vector[index] + + def evaluate(self, individual): + len_coil, diam_wire, nb_spire, capa_tuning, capa_triwire = individual + + params = parameters_dict.copy() + params.update({ + 'len_coil': len_coil, + 'diam_wire': diam_wire, + 'nb_spire': int(nb_spire), + 'capa_tuning': capa_tuning, + 'capa_triwire': capa_triwire + }) + + try: + self.controller.update_parameters(params) + results = self.controller.get_current_results() + impedance = results['impedance']["data"] + resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + target_resonance_freq = self.target_resonance_freq + return abs(resonance_freq - target_resonance_freq), + except Exception as e: + return 1e6, + + def init_creator(self): + creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) + creator.create("Individual", list, fitness=creator.FitnessMin) + + toolbox = base.Toolbox() + toolbox.register("attr_len_coil", random.uniform, 1e-3, 200e-3) + toolbox.register("attr_diam_wire", random.uniform, 10e-6, 300e-6) + toolbox.register("attr_nb_spire", random.uniform, 1000, 20000) + toolbox.register("attr_capa_tuning", random.uniform, 1e-12, 1000e-12) + toolbox.register("attr_capa_triwire", random.uniform, 10e-12, 1000e-12) + toolbox.register("individual", tools.initCycle, creator.Individual, + (toolbox.attr_len_coil, toolbox.attr_diam_wire, toolbox.attr_nb_spire, + toolbox.attr_capa_tuning, toolbox.attr_capa_triwire), + n=1) + toolbox.register("population", tools.initRepeat, list, toolbox.individual) + toolbox.register("evaluate", self.evaluate) + toolbox.register("mate", tools.cxTwoPoint) + toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.3) + toolbox.register("select", tools.selTournament, tournsize=5) + + self.toolbox = toolbox + + def run_optimisation(self): + population = self.toolbox.population(n=self.population_size) + hof = tools.HallOfFame(5) # Keep the top 5 individuals + stats = tools.Statistics(lambda ind: ind.fitness.values) + stats.register("min", min) + stats.register("avg", np.mean) + + for gen in range(self.generations): + population, logbook = algorithms.eaSimple(population, self.toolbox, cxpb=0.7, mutpb=self.mutation_rate, + ngen=1, stats=stats, halloffame=hof, verbose=False) + + avg_fitness = logbook.select("avg")[0] + best_fitness = logbook.select("min")[0][0] + print(best_fitness) + self.update_signal.emit(gen, avg_fitness, best_fitness) + + best_params = hof[0] + print("Best Parameters:", best_params) + print("Best Fitness:", self.evaluate(best_params)[0]) + + # Update parameters for the final evaluation + final_params = {'len_coil': best_params[0], 'diam_wire': best_params[1], 'nb_spire': int(best_params[2]), + 'capa_tuning': best_params[3], 'capa_triwire': best_params[4]} + self.controller.update_parameters(final_params) + final_results = self.controller.get_current_results() + impedance = final_results['impedance']["data"] + final_resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + print("Final Resonance Frequency:", final_resonance_freq) + print("Final parameters:", final_params) + self.finished_signal.emit(final_params, final_resonance_freq) + return final_resonance_freq, final_params + + def run(self): + self.run_optimisation() + + +if __name__ == "__main__": + + optimisation = GeneticOptimisation(100, 20, 0.3, parameters_dict, target_resonance_freq=24430) + optimisation.run_optimisation() \ No newline at end of file diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index 696f608..ac0718b 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -1,4 +1,11 @@ -from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton, QMessageBox +from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton, QMessageBox, QProgressDialog, QGroupBox, \ + QComboBox, QLineEdit +from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas +from matplotlib.figure import Figure + +from src.model.optimisation.simulated_annealing import SimulatedAnnealing +from src.model.optimisation.genetic_optimisation import GeneticOptimisation, parameters_dict +from src.model.optimisation.particle_swarm_optimisation import ParticleSwarmOptimization class OptimisationTab(QWidget): @@ -6,28 +13,140 @@ def __init__(self, parent=None): super().__init__(parent) self.setup_ui() + self.optimisation = GeneticOptimisation(100, 20, 0.3, parameters_dict, target_resonance_freq=24430) + self.pso_optimisation = ParticleSwarmOptimization(parameters_dict) + self.sa_optimisation = SimulatedAnnealing(parameters_dict, target_resonance_freq=3255, n_iterations=1000, initial_temperature=1000, cooling_rate=0.99) + + self.optimisation.update_signal.connect(self.update_progress) + self.optimisation.finished_signal.connect(self.display_final_results) + + self.pso_optimisation.update_signal.connect(self.update_progress) + self.pso_optimisation.finished_signal.connect(self.display_final_results) + + self.sa_optimisation.update_signal.connect(self.update_progress) + self.sa_optimisation.finished_signal.connect(self.display_final_results) + def setup_ui(self): self.layout = QVBoxLayout(self) - self.label = QLabel("Welcome to the optimisation Tab !") + # Combobox for method selection + self.method_combobox = QComboBox() + self.method_combobox.addItem("Genetic Optimization") + self.method_combobox.addItem("Particle Swarm Optimization") + self.method_combobox.addItem("Simulated Annealing") + self.layout.addWidget(self.method_combobox) + + # Scroll area for target selection + self.target_group_box = QGroupBox("Target") + self.target_layout = QVBoxLayout() + + self.target_combobox = QComboBox() + self.target_combobox.addItem("Impedance") + self.target_layout.addWidget(self.target_combobox) + + self.target_value_input = QLineEdit() + self.target_value_input.setPlaceholderText("Enter target impedance value") + self.target_layout.addWidget(self.target_value_input) + + self.target_group_box.setLayout(self.target_layout) + self.layout.addWidget(self.target_group_box) + + # Add other controls + self.label = QLabel("Welcome to the optimisation Tab!") self.layout.addWidget(self.label) self.optimise_button = QPushButton("Optimise") self.optimise_button.clicked.connect(self.on_optimise_clicked) self.layout.addWidget(self.optimise_button) + self.figure = Figure() + self.canvas = FigureCanvas(self.figure) + self.layout.addWidget(self.canvas) + self.ax = self.figure.add_subplot(111) + self.ax.set_title('Average Fitness over Generations') + self.ax.grid() + self.ax.semilogy() + self.ax.set_xlabel('Generation') + self.ax.set_ylabel('Average Fitness') + + + def on_optimise_clicked(self): """Popup message box to confirm the optimisation.""" + try: + target_value = float(self.target_value_input.text()) + # Update target resonance frequency based on the selected method + if self.method_combobox.currentText() == "Genetic Optimization": + self.optimisation.update_target_resonance_freq(target_value) + elif self.method_combobox.currentText() == "Particle Swarm Optimization": + self.pso_optimisation.update_target_resonance_freq(target_value) + elif self.method_combobox.currentText() == "Simulated Annealing": + self.sa_optimisation.update_target_resonance_freq(target_value) + msg = QMessageBox() + msg.setIcon(QMessageBox.Icon.Information) + msg.setText("Do you really want to start the optimisation process, it can take few minutes ?") + msg.setWindowTitle("Confirm") + msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) + msg.setDefaultButton(QMessageBox.StandardButton.No) + msg.buttonClicked.connect(self.start_optimisation) + msg.exec() + except ValueError: + QMessageBox.warning(self, "Invalid Input", "Please enter a valid number for the target impedance.") - #show a message box inside a popup - msg = QMessageBox() - msg.setIcon(QMessageBox.Icon.Information) - msg.setText("Do you really want to start the optimisation process, it can take few minutes ?") - msg.setWindowTitle("Confirm") - msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) - msg.setDefaultButton(QMessageBox.StandardButton.No) - msg.buttonClicked.connect(self.on_message_box_clicked) - msg.exec() + + def start_optimisation(self, button): + if button.text() == "&Yes": + # Clear the plot + self.ax.clear() + self.ax.set_title('Average Fitness over Generations') + self.ax.grid() + self.ax.semilogy() + self.ax.set_xlabel('Generation') + self.ax.set_ylabel('Average Fitness') + + if self.method_combobox.currentText() == "Genetic Optimization": + total_iterations = self.optimisation.generations + elif self.method_combobox.currentText() == "Particle Swarm Optimization": + total_iterations = self.pso_optimisation.n_iterations + elif self.method_combobox.currentText() == "Simulated Annealing": + total_iterations = self.sa_optimisation.n_iterations + + self.progress_dialog = QProgressDialog("Optimizing...", "Abort", 0, total_iterations, self) # Update with correct total iterations + self.progress_dialog.setModal(True) + self.progress_dialog.show() + + if self.method_combobox.currentText() == "Genetic Optimization": + self.optimisation.start() + elif self.method_combobox.currentText() == "Particle Swarm Optimization": + self.pso_optimisation.start() + elif self.method_combobox.currentText() == "Simulated Annealing": + self.sa_optimisation.start() + else: + print("Optimization canceled!") + + def update_progress(self, generation, avg_fitness, best_fitness): + if self.progress_dialog: + self.progress_dialog.setValue(generation) + self.ax.plot(generation, best_fitness, 'ro-') # Plot each point as it comes in + self.canvas.draw() # Update the canvas + if self.method_combobox.currentText() == "Genetic Optimization": + total_generations = self.optimisation.generations + elif self.method_combobox.currentText() == "Particle Swarm Optimization": + total_generations = self.pso_optimisation.n_iterations + elif self.method_combobox.currentText() == "Simulated Annealing": + total_generations = self.sa_optimisation.n_iterations + + if generation == total_generations - 1: + self.progress_dialog.setValue(total_generations) + self.progress_dialog.close() + + def display_final_results(self, final_params, final_resonance_freq): + if self.progress_dialog: + self.progress_dialog.close() + message = (f"Optimization Completed!\n\n" + f"Final Resonance Frequency: {final_resonance_freq:.2f}\n" + f"Final Parameters:\n{final_params}") + QMessageBox.information(self, "Optimisation Results", message) def on_message_box_clicked(self, button): """Handle the message box button clicked event.""" @@ -39,3 +158,6 @@ def on_message_box_clicked(self, button): + + + From 80f2a0cdbd6a4c95679d390fbbfdc93f95568204 Mon Sep 17 00:00:00 2001 From: mroncera Date: Tue, 14 May 2024 13:53:40 +0200 Subject: [PATCH 05/16] FEAT - Add many files and differents optimisation methods --- .../optimisation/impedance_strategy_map.py | 45 +++++ .../particle_swarm_optimisation.py | 168 ++++++++++++++++++ src/model/optimisation/simulated_annealing.py | 128 +++++++++++++ src/view/optimisation_tab.py | 74 +++++++- 4 files changed, 406 insertions(+), 9 deletions(-) create mode 100644 src/model/optimisation/impedance_strategy_map.py create mode 100644 src/model/optimisation/particle_swarm_optimisation.py create mode 100644 src/model/optimisation/simulated_annealing.py diff --git a/src/model/optimisation/impedance_strategy_map.py b/src/model/optimisation/impedance_strategy_map.py new file mode 100644 index 0000000..1999a5a --- /dev/null +++ b/src/model/optimisation/impedance_strategy_map.py @@ -0,0 +1,45 @@ +from src.model.strategies.strategy_lib.Nz import AnalyticalNzStrategy +from src.model.strategies.strategy_lib.capacitance import AnalyticalCapacitanceStrategy +from src.model.strategies.strategy_lib.frequency import FrequencyVectorStrategy +from src.model.strategies.strategy_lib.impedance import AnalyticalImpedanceStrategy +from src.model.strategies.strategy_lib.inductance import AnalyticalInductanceStrategy +from src.model.strategies.strategy_lib.lambda_strategy import AnalyticalLambdaStrategy +from src.model.strategies.strategy_lib.mu_app import AnalyticalMu_appStrategy +from src.model.strategies.strategy_lib.resistance import AnalyticalResistanceStrategy, AnalyticalResistanceStrategyv2 + +IMPEDANCE_STRATEGY_MAP = { + "resistance": { + "default": AnalyticalResistanceStrategy, + "strategies": [AnalyticalResistanceStrategy, AnalyticalResistanceStrategyv2] + }, + "frequency_vector": { + "default": FrequencyVectorStrategy, + "strategies": [FrequencyVectorStrategy] + }, + "Nz": { + "default": AnalyticalNzStrategy, + "strategies": [AnalyticalNzStrategy] + }, + "mu_app": { + "default": AnalyticalMu_appStrategy, + "strategies": [AnalyticalMu_appStrategy] + }, + + "lambda_param": { + "default": AnalyticalLambdaStrategy, + "strategies": [AnalyticalLambdaStrategy] + }, + + "inductance": { + "default": AnalyticalInductanceStrategy, + "strategies": [AnalyticalInductanceStrategy] + }, + "capacitance": { + "default": AnalyticalCapacitanceStrategy, + "strategies": [AnalyticalCapacitanceStrategy] + }, + "impedance": { + "default": AnalyticalImpedanceStrategy, + "strategies": [AnalyticalImpedanceStrategy] + } +} \ No newline at end of file diff --git a/src/model/optimisation/particle_swarm_optimisation.py b/src/model/optimisation/particle_swarm_optimisation.py new file mode 100644 index 0000000..4b21e77 --- /dev/null +++ b/src/model/optimisation/particle_swarm_optimisation.py @@ -0,0 +1,168 @@ +import numpy as np +import random +from PyQt6.QtCore import QThread, pyqtSignal + +from src.model.optimisation.impedance_strategy_map import IMPEDANCE_STRATEGY_MAP +from src.controler.controller import CalculationController + +class ParticleSwarmOptimization(QThread): + update_signal = pyqtSignal(int, float, float) # iteration, avg_fitness, best_fitness + finished_signal = pyqtSignal(dict, float) # best_parameters, final_resonance_freq + + def __init__(self, parameters_dict, target_resonance_freq=3255, n_particles=10, n_iterations=10, bounds=None): + super().__init__() + self.parameters_dict = parameters_dict + self.target_resonance_freq = target_resonance_freq + self.n_particles = n_particles + self.n_iterations = n_iterations + self.bounds = [ + (1e-3, 200e-3), # len_coil + (10e-6, 300e-6), # diam_wire + (1000, 20000), # nb_spire + (1e-3, 10e-3), # diam_out_mandrel + (1e-2, 200e-2), # len_core + (1e-3, 100e-3), # diam_core + ] + self.controller = CalculationController() + + self.controller.swap_strategy_map(IMPEDANCE_STRATEGY_MAP) + + + self.w = 0.5 # Inertia weight + self.c1 = 0.5 # Cognitive constant + self.c2 = 0.9 # Social constant + + def clamp_positions(self, positions, bounds): + for i in range(len(bounds)): + positions[:, i] = np.clip(positions[:, i], bounds[i][0], bounds[i][1]) + + def reflect_positions(self, positions, bounds): + for i in range(len(bounds)): + lower_bound, upper_bound = bounds[i] + over_upper = positions[:, i] > upper_bound + under_lower = positions[:, i] < lower_bound + positions[over_upper, i] = 2 * upper_bound - positions[over_upper, i] + positions[under_lower, i] = 2 * lower_bound - positions[under_lower, i] + # Ensure they are within bounds after reflection + positions[:, i] = np.clip(positions[:, i], lower_bound, upper_bound) + + def run(self): + self.run_optimization() + + def determine_resonance_freq(self, freq_vector, impedance_vector): + index = impedance_vector.argmax() + return freq_vector[index] + + def evaluate(self, position): + params = self.parameters_dict.copy() + params.update(dict(zip(['len_coil', 'diam_wire', 'nb_spire', 'diam_out_mandrel', 'len_core', 'diam_core'], position))) + + try: + self.controller.update_parameters(params) + results = self.controller.get_current_results() + impedance = results['impedance']["data"] + resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + return abs(resonance_freq - self.target_resonance_freq), + except Exception as e: + return 1e6, + + def update_target_resonance_freq(self, target_resonance_freq): + self.target_resonance_freq = target_resonance_freq + + def run(self): + positions = np.array([np.random.uniform(low, high, self.n_particles) for low, high in self.bounds]).T + velocities = np.zeros_like(positions) + personal_best_positions = np.copy(positions) + personal_best_scores = np.array([self.evaluate(pos)[0] for pos in + positions]) # Make sure to take the first element of the tuple returned by evaluate + + global_best_position = personal_best_positions[np.argmin(personal_best_scores)] + global_best_score = np.min(personal_best_scores) + + for iteration in range(self.n_iterations): + # Emit the start of a new iteration with the current best global score and average score + avg_fitness = np.mean(personal_best_scores) + self.update_signal.emit(iteration, avg_fitness, global_best_score) + print("Iteration:", iteration, "Average fitness:", avg_fitness, "Best fitness:", global_best_score) + for i in range(self.n_particles): + # Update velocity + r1, r2 = np.random.random(), np.random.random() + velocities[i] = self.w * velocities[i] + self.c1 * r1 * ( + personal_best_positions[i] - positions[i]) + self.c2 * r2 * ( + global_best_position - positions[i]) + # Update position + positions[i] += velocities[i] + self.clamp_positions(positions, self.bounds) + # Evaluate new position + current_score = self.evaluate(positions[i])[0] + + # Update personal best + if current_score < personal_best_scores[i]: + personal_best_positions[i] = positions[i] + personal_bs = personal_best_scores[i] = current_score + + # Update global best + if current_score < global_best_score: + global_best_position = positions[i] + global_best_score = current_score + + # Emit finished signal with best parameters and final results + best_params = dict(zip(['len_coil', 'diam_wire', 'nb_spire', 'diam_out_mandrel', 'len_core', 'diam_core'], + global_best_position)) + + self.parameters_dict.update(best_params) + + self.controller.update_parameters(self.parameters_dict) + final_results = self.controller.get_current_results() + impedance = final_results['impedance']["data"] + final_resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + self.finished_signal.emit(best_params, final_resonance_freq) + + print("Best Parameters:", best_params) + print("Final Resonance Frequency:", final_resonance_freq) + + +# PSO initialization example: +if __name__ == "__main__": + parameters_dict = { + # Initialize all required parameters + 'f_start': 1, + 'f_stop': 1000000, + 'nb_points_per_decade': 1000, + # Add other necessary parameters + 'mu_insulator': 1, + 'kapthon_thick': 30e-6, + 'insulator_thick': 10e-6, + 'diam_out_mandrel': 3.2e-3, + 'len_core': 20e-2, + 'diam_core': 3.2e-3, + 'mu_r': 100000, + 'rho_whire': 1.6, + 'coeff_expansion': 1, + 'stage_1_cutting_freq': 20000, + 'stage_2_cutting_freq': 20000, + 'gain_1_linear': 1, + 'gain_2_linear': 1, + 'mutual_inductance': 0.1, + 'feedback_resistance': 1000, + 'temperature': 300, + 'spice_resistance_test': 1000, + 'Para_A': 1, + 'Para_B': 1, + 'e_en': 1, + 'e_in': 1, + 'Alpha': 1, + "ray_spire": 5e-3, + "capa_tuning": 1e-12, + "capa_triwire": 10e-12 + } + bounds = [ + (1e-3, 200e-3), # len_coil + (10e-6, 300e-6), # diam_wire + (1000, 20000), # nb_spire + (1e-3, 10e-3), # diam_out_mandrel + (1e-2, 200e-2), # len_core + (1e-3, 100e-3), # diam_core + ] + pso = ParticleSwarmOptimization(parameters_dict, bounds=bounds) + pso.run() diff --git a/src/model/optimisation/simulated_annealing.py b/src/model/optimisation/simulated_annealing.py new file mode 100644 index 0000000..4907024 --- /dev/null +++ b/src/model/optimisation/simulated_annealing.py @@ -0,0 +1,128 @@ +import random + +import numpy as np + +from src.controler.controller import CalculationController +from src.model.optimisation.genetic_optimisation import parameters_dict +from src.model.optimisation.impedance_strategy_map import IMPEDANCE_STRATEGY_MAP +from PyQt6.QtCore import pyqtSignal, QThread + +class SimulatedAnnealing(QThread): + update_signal = pyqtSignal(int, float, float) # iteration, avg_fitness, best_fitness + finished_signal = pyqtSignal(dict, float) # best_parameters, final_resonance_freq + + def __init__(self, parameters_dict, target_resonance_freq=3255, n_iterations=10, bounds=None, initial_temperature=1000, cooling_rate=0.003): + super().__init__() + self.parameters_dict = parameters_dict + self.target_resonance_freq = target_resonance_freq + self.n_iterations = n_iterations + self.initial_temperature = initial_temperature + self.cooling_rate = cooling_rate + self.bounds = [ + (1e-3, 200e-3), # len_coil + (10e-6, 300e-6), # diam_wire + (1000, 20000), # nb_spire + (1e-3, 10e-3), # diam_out_mandrel + (1e-2, 200e-2), # len_core + (1e-3, 100e-3), # diam_core + ] + #random init params with bounds + self.initial_paramater = [random.uniform(b[0], b[1]) for b in self.bounds] + + self.controller = CalculationController() + + self.controller.swap_strategy_map(IMPEDANCE_STRATEGY_MAP) + + def update_target_resonance_freq(self, target_resonance_freq): + self.target_resonance_freq = target_resonance_freq + + def set_initial_parameters(self, initial_parameters): + self.initial_paramater = initial_parameters + + def determine_resonance_freq(self, freq_vector, impedance_vector): + index = impedance_vector.argmax() + return freq_vector[index] + + def evaluate(self, position): + # Extract individual parameters from the position + len_coil, diam_wire, nb_spire, diam_out_mandrel, len_core, diam_core = position + + # Update parameter dictionary with the current position's values + params = parameters_dict.copy() + params.update({ + 'len_coil': len_coil, + 'diam_wire': diam_wire, + 'nb_spire': int(nb_spire), + 'diam_out_mandrel': diam_out_mandrel, + 'len_core': len_core, + 'diam_core': diam_core + }) + + try: + self.controller.update_parameters(params) + results = self.controller.get_current_results() + impedance = results['impedance']["data"] + resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + target_resonance_freq = self.target_resonance_freq + return abs(resonance_freq - target_resonance_freq) + except Exception as e: + return 1e6 + + def run(self): + print("Running Simulated Annealing, target resonance freq:", self.target_resonance_freq) + current_params = np.array(self.initial_paramater) + current_cost = self.evaluate(current_params) + best_cost = current_cost # Initialize the best cost + temp = self.initial_temperature + + for i in range(self.n_iterations): + next_params = current_params + np.random.uniform(-0.1, 0.1, size=current_params.shape) * (np.array([b[1] - b[0] for b in self.bounds]) * 0.05) + next_params = np.clip(next_params, [b[0] for b in self.bounds], [b[1] for b in self.bounds]) + next_cost = self.evaluate(next_params) + + if next_cost < current_cost or np.exp((current_cost - next_cost) / temp) > random.random(): + current_params = next_params + current_cost = next_cost + + if current_cost < best_cost: + best_cost = current_cost # Update the best cost if current cost is better + + temp *= self.cooling_rate + + if i % 100 == 0: + print(f"Iteration {i}: Best cost = {best_cost}, Params = {current_params}") + self.update_signal.emit(i, current_cost, best_cost) + + best_params = { + 'len_coil': current_params[0], + 'diam_wire': current_params[1], + 'nb_spire': int(current_params[2]), + 'diam_out_mandrel': current_params[3], + 'len_core': current_params[4], + 'diam_core': current_params[5] + } + + self.parameters_dict.update(best_params) + + # Update parameters for the final evaluation + self.controller.update_parameters(self.parameters_dict) + final_results = self.controller.get_current_results() + impedance = final_results['impedance']["data"] + final_resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + print("Final Resonance Frequency:", final_resonance_freq) + + self.finished_signal.emit(best_params, final_resonance_freq) + + +if __name__ == "__main__": + bounds = [ + (1e-3, 200e-3), # len_coil + (10e-6, 300e-6), # diam_wire + (1000, 20000), # nb_spire + (1e-3, 10e-3), # diam_out_mandrel + (1e-2, 200e-2), # len_core + (1e-3, 100e-3) # diam_core + ] + sa = SimulatedAnnealing(parameters_dict, target_resonance_freq=3255, n_iterations=1000, + initial_temperature=1000, cooling_rate=0.99) + sa.run() \ No newline at end of file diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index ac0718b..f28c11f 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -26,6 +26,8 @@ def __init__(self, parent=None): self.sa_optimisation.update_signal.connect(self.update_progress) self.sa_optimisation.finished_signal.connect(self.display_final_results) + self.update_hyperparameters() + def setup_ui(self): self.layout = QVBoxLayout(self) @@ -34,6 +36,8 @@ def setup_ui(self): self.method_combobox.addItem("Genetic Optimization") self.method_combobox.addItem("Particle Swarm Optimization") self.method_combobox.addItem("Simulated Annealing") + self.method_combobox.currentIndexChanged.connect( + self.update_hyperparameters) # Connect the combobox change event self.layout.addWidget(self.method_combobox) # Scroll area for target selection @@ -51,6 +55,12 @@ def setup_ui(self): self.target_group_box.setLayout(self.target_layout) self.layout.addWidget(self.target_group_box) + # Add hyperparameters section + self.hyperparameters_group_box = QGroupBox("Hyperparameters") + self.hyperparameters_layout = QVBoxLayout() + self.hyperparameters_group_box.setLayout(self.hyperparameters_layout) + self.layout.addWidget(self.hyperparameters_group_box) + # Add other controls self.label = QLabel("Welcome to the optimisation Tab!") self.layout.addWidget(self.label) @@ -63,13 +73,39 @@ def setup_ui(self): self.canvas = FigureCanvas(self.figure) self.layout.addWidget(self.canvas) self.ax = self.figure.add_subplot(111) - self.ax.set_title('Average Fitness over Generations') + self.ax.set_title('Best Fitness over Generations') self.ax.grid() self.ax.semilogy() self.ax.set_xlabel('Generation') - self.ax.set_ylabel('Average Fitness') - - + self.ax.set_ylabel('Best Fitness') + + def update_hyperparameters(self): + # Clear current hyperparameters layout + for i in reversed(range(self.hyperparameters_layout.count())): + self.hyperparameters_layout.itemAt(i).widget().deleteLater() + + method = self.method_combobox.currentText() + if method == "Genetic Optimization": + self.add_hyperparameter_field("Number of Generations", "20") + self.add_hyperparameter_field("Population Size", "100") + self.add_hyperparameter_field("Mutation Rate", "0.3") + elif method == "Particle Swarm Optimization": + self.add_hyperparameter_field("w1", "0.5") + self.add_hyperparameter_field("c1", "1.0") + self.add_hyperparameter_field("c2", "1.0") + self.add_hyperparameter_field("Number of Particles", "50") + self.add_hyperparameter_field("Number of Iterations", "50") + elif method == "Simulated Annealing": + self.add_hyperparameter_field("Cooling Rate", "0.99") + self.add_hyperparameter_field("Initial Temperature", "5000") + self.add_hyperparameter_field("Number of Iterations", "2000") + + def add_hyperparameter_field(self, label_text, default_value): + label = QLabel(label_text) + line_edit = QLineEdit() + line_edit.setText(default_value) + self.hyperparameters_layout.addWidget(label) + self.hyperparameters_layout.addWidget(line_edit) def on_optimise_clicked(self): """Popup message box to confirm the optimisation.""" @@ -93,7 +129,6 @@ def on_optimise_clicked(self): except ValueError: QMessageBox.warning(self, "Invalid Input", "Please enter a valid number for the target impedance.") - def start_optimisation(self, button): if button.text() == "&Yes": # Clear the plot @@ -104,26 +139,47 @@ def start_optimisation(self, button): self.ax.set_xlabel('Generation') self.ax.set_ylabel('Average Fitness') + hyperparameters = self.get_hyperparameters() + if self.method_combobox.currentText() == "Genetic Optimization": + self.optimisation.generations = int(hyperparameters["Number of Generations"]) + self.optimisation.population_size = int(hyperparameters["Population Size"]) + self.optimisation.mutation_rate = float(hyperparameters["Mutation Rate"]) total_iterations = self.optimisation.generations elif self.method_combobox.currentText() == "Particle Swarm Optimization": + self.pso_optimisation.w1 = float(hyperparameters["w1"]) + self.pso_optimisation.c1 = float(hyperparameters["c1"]) + self.pso_optimisation.c2 = float(hyperparameters["c2"]) + self.pso_optimisation.n_particles = int(hyperparameters["Number of Particles"]) + self.pso_optimisation.n_iterations = int(hyperparameters["Number of Iterations"]) total_iterations = self.pso_optimisation.n_iterations elif self.method_combobox.currentText() == "Simulated Annealing": + self.sa_optimisation.cooling_rate = float(hyperparameters["Cooling Rate"]) + self.sa_optimisation.initial_temperature = float(hyperparameters["Initial Temperature"]) + self.sa_optimisation.n_iterations = int(hyperparameters["Number of Iterations"]) total_iterations = self.sa_optimisation.n_iterations - self.progress_dialog = QProgressDialog("Optimizing...", "Abort", 0, total_iterations, self) # Update with correct total iterations + self.progress_dialog = QProgressDialog("Optimizing...", "Abort", 0, total_iterations, self) self.progress_dialog.setModal(True) self.progress_dialog.show() if self.method_combobox.currentText() == "Genetic Optimization": - self.optimisation.start() + self.optimisation.start() # Ensure GeneticOptimisation runs in a thread elif self.method_combobox.currentText() == "Particle Swarm Optimization": - self.pso_optimisation.start() + self.pso_optimisation.start() # Ensure PSO runs in a thread elif self.method_combobox.currentText() == "Simulated Annealing": - self.sa_optimisation.start() + self.sa_optimisation.start() # Ensure Simulated Annealing runs in a thread else: print("Optimization canceled!") + def get_hyperparameters(self): + hyperparameters = {} + for i in range(self.hyperparameters_layout.count() // 2): + label = self.hyperparameters_layout.itemAt(2 * i).widget().text() + value = self.hyperparameters_layout.itemAt(2 * i + 1).widget().text() + hyperparameters[label] = value + return hyperparameters + def update_progress(self, generation, avg_fitness, best_fitness): if self.progress_dialog: self.progress_dialog.setValue(generation) From ecfd8680f82c24cc20852eebd3f471ceebd353f6 Mon Sep 17 00:00:00 2001 From: mroncera Date: Tue, 21 May 2024 09:41:16 +0200 Subject: [PATCH 06/16] minor fixes --- src/model/optimisation/impedance_strategy_map.py | 6 +++++- src/model/visualisation/create_tree.py | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/model/optimisation/impedance_strategy_map.py b/src/model/optimisation/impedance_strategy_map.py index 1999a5a..c40bb3b 100644 --- a/src/model/optimisation/impedance_strategy_map.py +++ b/src/model/optimisation/impedance_strategy_map.py @@ -42,4 +42,8 @@ "default": AnalyticalImpedanceStrategy, "strategies": [AnalyticalImpedanceStrategy] } -} \ No newline at end of file +} + + + + diff --git a/src/model/visualisation/create_tree.py b/src/model/visualisation/create_tree.py index f232cc0..f246996 100644 --- a/src/model/visualisation/create_tree.py +++ b/src/model/visualisation/create_tree.py @@ -213,8 +213,8 @@ def add_nodes_edges_distance(graph, data, parent=None): "barnesHut": { "gravitationalConstant": -500000, "centralGravity": 10, - "springLength": 150, - "springConstant": 0.01, + "springLength": 50, + "springConstant": 0.05, "damping": 0.09, "avoidOverlap": 0.1 }, From 242b4f3c37e61b2321353da64838baff48942cde Mon Sep 17 00:00:00 2001 From: mroncera Date: Mon, 27 May 2024 10:45:30 +0200 Subject: [PATCH 07/16] temp --- src/view/optimisation_tab.py | 124 ++++++++++++++++++++++++++++++----- 1 file changed, 109 insertions(+), 15 deletions(-) diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index f28c11f..96c88e0 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -1,5 +1,5 @@ from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton, QMessageBox, QProgressDialog, QGroupBox, \ - QComboBox, QLineEdit + QComboBox, QLineEdit, QTableWidgetItem, QTableWidget from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure @@ -8,6 +8,8 @@ from src.model.optimisation.particle_swarm_optimisation import ParticleSwarmOptimization +from PyQt6.QtGui import QDoubleValidator, QColor + class OptimisationTab(QWidget): def __init__(self, parent=None): super().__init__(parent) @@ -36,8 +38,7 @@ def setup_ui(self): self.method_combobox.addItem("Genetic Optimization") self.method_combobox.addItem("Particle Swarm Optimization") self.method_combobox.addItem("Simulated Annealing") - self.method_combobox.currentIndexChanged.connect( - self.update_hyperparameters) # Connect the combobox change event + self.method_combobox.currentIndexChanged.connect(self.update_hyperparameters) # Connect the combobox change event self.layout.addWidget(self.method_combobox) # Scroll area for target selection @@ -46,12 +47,22 @@ def setup_ui(self): self.target_combobox = QComboBox() self.target_combobox.addItem("Impedance") + self.target_combobox.addItem("NEMI") + self.target_combobox.currentIndexChanged.connect(self.update_target) self.target_layout.addWidget(self.target_combobox) self.target_value_input = QLineEdit() self.target_value_input.setPlaceholderText("Enter target impedance value") self.target_layout.addWidget(self.target_value_input) + # NEMI table setup + self.nemi_table = QTableWidget(3, 1) + self.nemi_table.setHorizontalHeaderLabels(["Column 1"]) + self.nemi_table.setVerticalHeaderLabels(["Freq", "NEMI Value", "Weight"]) + self.nemi_table.setVisible(False) + self.nemi_table.itemChanged.connect(self.on_nemi_table_item_changed) + self.target_layout.addWidget(self.nemi_table) + self.target_group_box.setLayout(self.target_layout) self.layout.addWidget(self.target_group_box) @@ -107,17 +118,86 @@ def add_hyperparameter_field(self, label_text, default_value): self.hyperparameters_layout.addWidget(label) self.hyperparameters_layout.addWidget(line_edit) + def update_target(self): + if self.target_combobox.currentText() == "NEMI": + self.target_value_input.setVisible(False) + self.nemi_table.setVisible(True) + else: + self.target_value_input.setVisible(True) + self.nemi_table.setVisible(False) + + def on_nemi_table_item_changed(self, item): + self.validate_nemi_table() + + if item.column() == self.nemi_table.columnCount() - 1 and item.text(): + self.nemi_table.setColumnCount(self.nemi_table.columnCount() + 1) + self.nemi_table.setHorizontalHeaderItem(self.nemi_table.columnCount() - 1, + QTableWidgetItem(f"Column {self.nemi_table.columnCount()}")) + + empty_columns = 0 + for col in range(self.nemi_table.columnCount()): + is_empty = True + for row in range(self.nemi_table.rowCount()): + if self.nemi_table.item(row, col) and self.nemi_table.item(row, col).text(): + is_empty = False + break + if is_empty: + empty_columns += 1 + if empty_columns >= 2: + self.nemi_table.setColumnCount(self.nemi_table.columnCount() - 1) + self.nemi_table.setHorizontalHeaderItem(self.nemi_table.columnCount() - 1, + QTableWidgetItem(f"Column {self.nemi_table.columnCount()}")) + empty_columns -= 1 + + def validate_nemi_table(self): + weight_sum = 0 + is_valid = True + for row in range(self.nemi_table.rowCount()): + for col in range(self.nemi_table.columnCount()): + item = self.nemi_table.item(row, col) + if item: + try: + value = float(item.text()) + if row == 2: + weight_sum += value + item.setBackground(QColor(255, 255, 255)) + except ValueError: + item.setBackground(QColor(255, 0, 0)) + is_valid = False + + # Validate the sum of weights + if abs(weight_sum - 1) > 1e-6: # Allowing a small tolerance + for col in range(self.nemi_table.columnCount()): + item = self.nemi_table.item(2, col) + if item: + item.setBackground(QColor(255, 0, 0)) + is_valid = False + else: + for col in range(self.nemi_table.columnCount()): + item = self.nemi_table.item(2, col) + if item and item.background() == QColor(255, 0, 0): + item.setBackground(QColor(255, 255, 255)) + + return is_valid + def on_optimise_clicked(self): """Popup message box to confirm the optimisation.""" try: - target_value = float(self.target_value_input.text()) - # Update target resonance frequency based on the selected method - if self.method_combobox.currentText() == "Genetic Optimization": - self.optimisation.update_target_resonance_freq(target_value) - elif self.method_combobox.currentText() == "Particle Swarm Optimization": - self.pso_optimisation.update_target_resonance_freq(target_value) - elif self.method_combobox.currentText() == "Simulated Annealing": - self.sa_optimisation.update_target_resonance_freq(target_value) + if self.target_combobox.currentText() == "NEMI": + if not self.validate_nemi_table(): + QMessageBox.warning(self, "Invalid Input", "Please correct the invalid inputs in the NEMI table.") + return + target_value = self.get_nemi_table_values() + else: + target_value = float(self.target_value_input.text()) + # Update target resonance frequency based on the selected method + if self.method_combobox.currentText() == "Genetic Optimization": + self.optimisation.update_target_resonance_freq(target_value) + elif self.method_combobox.currentText() == "Particle Swarm Optimization": + self.pso_optimisation.update_target_resonance_freq(target_value) + elif self.method_combobox.currentText() == "Simulated Annealing": + self.sa_optimisation.update_target_resonance_freq(target_value) + msg = QMessageBox() msg.setIcon(QMessageBox.Icon.Information) msg.setText("Do you really want to start the optimisation process, it can take few minutes ?") @@ -129,6 +209,24 @@ def on_optimise_clicked(self): except ValueError: QMessageBox.warning(self, "Invalid Input", "Please enter a valid number for the target impedance.") + def get_nemi_table_values(self): + nemi_values = {"Freq": [], "NEMI Value": [], "Weight": []} + for row in range(self.nemi_table.rowCount()): + for col in range(self.nemi_table.columnCount()): + item = self.nemi_table.item(row, col) + if item and item.text(): + if row == 0: + nemi_values["Freq"].append(float(item.text())) + elif row == 1: + nemi_values["NEMI Value"].append(float(item.text())) + elif row == 2: + nemi_values["Weight"].append(float(item.text())) + else: + nemi_values["Freq"].append(0) + nemi_values["NEMI Value"].append(0) + nemi_values["Weight"].append(0) + return nemi_values + def start_optimisation(self, button): if button.text() == "&Yes": # Clear the plot @@ -213,7 +311,3 @@ def on_message_box_clicked(self, button): - - - - From e781231d22980a309422f307c4f467df7a293077 Mon Sep 17 00:00:00 2001 From: mroncera Date: Tue, 28 May 2024 16:02:58 +0200 Subject: [PATCH 08/16] FEAT - export and reload parameters working, still need to fix the units --- src/view/gui.py | 10 ++- src/view/optimisation_tab.py | 138 ++++++++++++++++++++++++++--------- 2 files changed, 112 insertions(+), 36 deletions(-) diff --git a/src/view/gui.py b/src/view/gui.py index 8f4be61..7bfe4c1 100644 --- a/src/view/gui.py +++ b/src/view/gui.py @@ -844,7 +844,7 @@ def init_ui(self): self.param_tab = QWidget() # QWidget that will contain the parameters layout as a tab self.strategy_tab = QWidget() # QWidget that will contain the strategy selection layout as a tab self.spice_tab = QWidget() # QWidget that will contain the spice layout as a tab - self.optimisation_tab = OptimisationTab() # QWidget that will contain the optimisation layout as a tab + self.optimisation_tab = OptimisationTab(self) # QWidget that will contain the optimisation layout as a tab self.EMC_tab = QWidget() # QWidget that will contain the EMC layout as a tab self.params_layout = QVBoxLayout(self.param_tab) @@ -1213,7 +1213,7 @@ def export_parameters_to_json(self): except Exception as e: self.display_error(f"Error exporting parameters: {e}") - def import_parameters_from_json(self): + def import_parameters_from_json(self, need_filename=True, path=None): """ Imports input parameters from a JSON file. The user is prompted to select a file to import the parameters from. @@ -1222,7 +1222,11 @@ def import_parameters_from_json(self): """ # Show an open file dialog to the user try: - fileName, _ = QFileDialog.getOpenFileName(self, "Import Parameters", "", "JSON Files (*.json)") + if need_filename: + fileName, _ = QFileDialog.getOpenFileName(self, "Import Parameters", "", "JSON Files (*.json)") + else: + if path is not None: + fileName = path if fileName: # If a file is selected, load the parameters from that file with open(fileName, 'r', encoding="utf-8") as json_file: diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index 96c88e0..216aa2b 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -1,5 +1,7 @@ +import json + from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton, QMessageBox, QProgressDialog, QGroupBox, \ - QComboBox, QLineEdit, QTableWidgetItem, QTableWidget + QComboBox, QLineEdit, QTableWidgetItem, QTableWidget, QDialog, QFileDialog from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure @@ -11,8 +13,9 @@ from PyQt6.QtGui import QDoubleValidator, QColor class OptimisationTab(QWidget): - def __init__(self, parent=None): + def __init__(self, gui ,parent=None): super().__init__(parent) + self.gui = gui self.setup_ui() self.optimisation = GeneticOptimisation(100, 20, 0.3, parameters_dict, target_resonance_freq=24430) @@ -152,31 +155,30 @@ def on_nemi_table_item_changed(self, item): def validate_nemi_table(self): weight_sum = 0 is_valid = True - for row in range(self.nemi_table.rowCount()): - for col in range(self.nemi_table.columnCount()): - item = self.nemi_table.item(row, col) - if item: - try: - value = float(item.text()) - if row == 2: - weight_sum += value - item.setBackground(QColor(255, 255, 255)) - except ValueError: - item.setBackground(QColor(255, 0, 0)) - is_valid = False - - # Validate the sum of weights - if abs(weight_sum - 1) > 1e-6: # Allowing a small tolerance - for col in range(self.nemi_table.columnCount()): - item = self.nemi_table.item(2, col) - if item: - item.setBackground(QColor(255, 0, 0)) - is_valid = False - else: - for col in range(self.nemi_table.columnCount()): - item = self.nemi_table.item(2, col) - if item and item.background() == QColor(255, 0, 0): - item.setBackground(QColor(255, 255, 255)) + self.nemi_table.blockSignals(True) # Block signals temporarily + try: + for row in range(self.nemi_table.rowCount()): + for col in range(self.nemi_table.columnCount()): + item = self.nemi_table.item(row, col) + if item: + try: + value = float(item.text()) + if row == 2: + weight_sum += value + item.setBackground(QColor(255, 255, 255)) # Set to white for valid input + except ValueError: + item.setBackground(QColor(255, 0, 0)) # Set to red for invalid input + is_valid = False + + if weight_sum != 1: + print("Weight sum is not equal to 1") + is_valid = False + for col in range(self.nemi_table.columnCount()): + item = self.nemi_table.item(2, col) + if item: + item.setBackground(QColor(255, 0, 0)) # Highlight the weight row if sum is not 1 + finally: + self.nemi_table.blockSignals(False) # Unblock signals return is_valid @@ -295,13 +297,83 @@ def update_progress(self, generation, avg_fitness, best_fitness): self.progress_dialog.close() def display_final_results(self, final_params, final_resonance_freq): - if self.progress_dialog: - self.progress_dialog.close() - message = (f"Optimization Completed!\n\n" - f"Final Resonance Frequency: {final_resonance_freq:.2f}\n" - f"Final Parameters:\n{final_params}") - QMessageBox.information(self, "Optimisation Results", message) + result_dialog = QDialog(self) + result_dialog.setWindowTitle("Optimisation Results") + + layout = QVBoxLayout(result_dialog) + + results_text = f"

Optimization Completed!

" + results_text += f"

Final Resonance Frequency: {final_resonance_freq:.2f}

" + results_text += "

Final Parameters:

    " + for param, value in final_params.items(): + formatted_value = "{:.2e}".format(value) + results_text += f"
  • {param}: {formatted_value}
  • " + results_text += "
" + + results_label = QLabel(results_text) + results_label.setWordWrap(True) + layout.addWidget(results_label) + + save_button = QPushButton("Save Results") + save_button.clicked.connect(lambda: self.save_results(final_params, final_resonance_freq)) + layout.addWidget(save_button) + + result_dialog.setLayout(layout) + result_dialog.exec() + + + def save_results(self, final_params, final_resonance_freq): + try : + path, _ = QFileDialog.getSaveFileName(self, "Export Optimisation data", "", "json Files (*.png)") + if not path: + return + + print("Saving results to:", path) + print(final_params) + + input_parameters_copy = self.gui.input_parameters.copy() + + print(input_parameters_copy) + + # Update the input parameters with the final results + for section, params in input_parameters_copy.items(): + if section == "SPICE_circuit" or section == "SPICE": + continue + for param, value in params.items(): + if str(param) in final_params.keys(): + input_parameters_copy[section][param]["default"] = final_params[param] + print("Updated parameter:", param, "with value:", final_params[param]) + + self.saved_path = path + + try : + # Retrieve the currelnly selected SPICE circuit from the combo box + selected_circuit = self.gui.spice_circuit_combo.currentText() + + # Add the selected SPICE circuit to the updated parameters + input_parameters_copy["SPICE_circuit"] = selected_circuit + except Exception as e: + print(f"Error adding SPICE circuit to updated parameters: {e}") + pass + + # Save the results to a file + with open(path, 'w') as file: + json.dump(input_parameters_copy, file, indent=4) + + self.reload_on_gui() + + except FileNotFoundError: + QMessageBox.warning(self, "Invalid File", "Please enter a valid file name.") + + except Exception as e: + QMessageBox.critical(self, "Error", f"An error occurred while saving the results: {e}") + + def reload_on_gui(self): + # Update the input parameters + self.gui.import_parameters_from_json(path=self.saved_path, need_filename=False) + self.gui.tabs.setCurrentIndex(0) + print("saving json") def on_message_box_clicked(self, button): """Handle the message box button clicked event.""" if button.text() == "&Yes": From 20560a3b456cb6370b82685c787a475c05b97d4b Mon Sep 17 00:00:00 2001 From: mroncera Date: Tue, 28 May 2024 16:12:52 +0200 Subject: [PATCH 09/16] FEAT - partially working reload after optimisation --- src/view/optimisation_tab.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index 216aa2b..e7547ab 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -4,14 +4,31 @@ QComboBox, QLineEdit, QTableWidgetItem, QTableWidget, QDialog, QFileDialog from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure +from pint import UnitRegistry from src.model.optimisation.simulated_annealing import SimulatedAnnealing from src.model.optimisation.genetic_optimisation import GeneticOptimisation, parameters_dict from src.model.optimisation.particle_swarm_optimisation import ParticleSwarmOptimization - from PyQt6.QtGui import QDoubleValidator, QColor + +ureg: UnitRegistry = UnitRegistry() +def convert_unit(value, from_unit, to_unit): + """ + Converts the given value from one unit to another using Pint. + Args: + value (float): The value to convert. + from_unit (str): The unit of the input value. + to_unit (str): The target unit for the conversion. + Returns: + float: The converted value. + """ + if from_unit and to_unit: + return (value * ureg(from_unit)).to(ureg(to_unit)).magnitude + return value + + class OptimisationTab(QWidget): def __init__(self, gui ,parent=None): super().__init__(parent) @@ -341,6 +358,16 @@ def save_results(self, final_params, final_resonance_freq): continue for param, value in params.items(): if str(param) in final_params.keys(): + input_unit = input_parameters_copy[section][param]["input_unit"] + target_unit = input_parameters_copy[section][param]["target_unit"] + + converted_value = convert_unit(final_params[param], target_unit, input_unit) + + # only keep 3 decimal places + converted_value = round(converted_value, 3) + + final_params[param] = converted_value + input_parameters_copy[section][param]["default"] = final_params[param] print("Updated parameter:", param, "with value:", final_params[param]) From 69288ff213962073fb023997a3f29c9ad7c705b0 Mon Sep 17 00:00:00 2001 From: mroncera Date: Wed, 29 May 2024 10:17:41 +0200 Subject: [PATCH 10/16] FEAT - reload to parameters and reload to gui working --- src/view/gui.py | 7 +-- src/view/optimisation_tab.py | 85 +++++++++++++++++++++++++++++++++--- 2 files changed, 83 insertions(+), 9 deletions(-) diff --git a/src/view/gui.py b/src/view/gui.py index 7bfe4c1..1d74bf5 100644 --- a/src/view/gui.py +++ b/src/view/gui.py @@ -925,7 +925,7 @@ def init_menu(self): export_action.triggered.connect(self.export_parameters_to_json) import_action = file_menu.addAction('&Import Parameters') - import_action.triggered.connect(self.import_parameters_from_json) + import_action.triggered.connect(lambda _: self.import_parameters_from_json(need_filename=True)) import_specific_action = file_menu.addAction('&Import Flicker Params') import_specific_action.triggered.connect(self.import_flicker_data_from_json) @@ -1222,6 +1222,7 @@ def import_parameters_from_json(self, need_filename=True, path=None): """ # Show an open file dialog to the user try: + filename = None if need_filename: fileName, _ = QFileDialog.getOpenFileName(self, "Import Parameters", "", "JSON Files (*.json)") else: @@ -1459,10 +1460,10 @@ def display_error(self, error_message): :return: """ # Show an error message to the user - print(f"Calculation failed: {error_message}") + print(f"{error_message}") # use a QMessageBox for GUI error display - QMessageBox.critical(self, "An error occurred", f"Calculation failed: {error_message}") + QMessageBox.critical(self, "An error occurred", f"{error_message}") def update_plot(self, index): def plot_curve(data_with_meta, x_vector, linestyle='-', color=None): diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index e7547ab..2ad04cb 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -132,6 +132,12 @@ def update_hyperparameters(self): self.add_hyperparameter_field("Number of Iterations", "2000") def add_hyperparameter_field(self, label_text, default_value): + """ + Add a hyperparameter field to the layout. + :param label_text: + :param default_value: + :return: + """ label = QLabel(label_text) line_edit = QLineEdit() line_edit.setText(default_value) @@ -139,6 +145,10 @@ def add_hyperparameter_field(self, label_text, default_value): self.hyperparameters_layout.addWidget(line_edit) def update_target(self): + """ + Update the target input based on the selected target. + :return: + """ if self.target_combobox.currentText() == "NEMI": self.target_value_input.setVisible(False) self.nemi_table.setVisible(True) @@ -147,6 +157,11 @@ def update_target(self): self.nemi_table.setVisible(False) def on_nemi_table_item_changed(self, item): + """ + Handle the NEMI table item changed event. + :param item: updated cell item + :return: + """ self.validate_nemi_table() if item.column() == self.nemi_table.columnCount() - 1 and item.text(): @@ -170,6 +185,12 @@ def on_nemi_table_item_changed(self, item): empty_columns -= 1 def validate_nemi_table(self): + """ + Table validator for NEMI values. + If the sum of the weights is not equal to 1, the weight row is highlighted in red. + If any of the values are invalid, the corresponding cell is highlighted in red. + :return: + """ weight_sum = 0 is_valid = True self.nemi_table.blockSignals(True) # Block signals temporarily @@ -229,6 +250,10 @@ def on_optimise_clicked(self): QMessageBox.warning(self, "Invalid Input", "Please enter a valid number for the target impedance.") def get_nemi_table_values(self): + """ + Get the values from the table. + :return: + """ nemi_values = {"Freq": [], "NEMI Value": [], "Weight": []} for row in range(self.nemi_table.rowCount()): for col in range(self.nemi_table.columnCount()): @@ -247,6 +272,11 @@ def get_nemi_table_values(self): return nemi_values def start_optimisation(self, button): + """ + Start the optimisation process, core function to handle the message box button clicked event. + :param button: + :return: + """ if button.text() == "&Yes": # Clear the plot self.ax.clear() @@ -290,6 +320,10 @@ def start_optimisation(self, button): print("Optimization canceled!") def get_hyperparameters(self): + """ + Get the hyperparameters from the input fields. + :return: + """ hyperparameters = {} for i in range(self.hyperparameters_layout.count() // 2): label = self.hyperparameters_layout.itemAt(2 * i).widget().text() @@ -298,6 +332,13 @@ def get_hyperparameters(self): return hyperparameters def update_progress(self, generation, avg_fitness, best_fitness): + """ + Update the progress dialog and plot the best fitness over generations. + :param generation: actual generation + :param avg_fitness: average fitness of the generation + :param best_fitness: best fitness of the generation + :return: + """ if self.progress_dialog: self.progress_dialog.setValue(generation) self.ax.plot(generation, best_fitness, 'ro-') # Plot each point as it comes in @@ -309,11 +350,20 @@ def update_progress(self, generation, avg_fitness, best_fitness): elif self.method_combobox.currentText() == "Simulated Annealing": total_generations = self.sa_optimisation.n_iterations - if generation == total_generations - 1: + if generation == total_generations: self.progress_dialog.setValue(total_generations) self.progress_dialog.close() def display_final_results(self, final_params, final_resonance_freq): + """ + Display the final results of the optimisation. + :param final_params: best parameters found + :param final_resonance_freq: + :return: + """ + + self.progress_dialog.close() + result_dialog = QDialog(self) result_dialog.setWindowTitle("Optimisation Results") @@ -327,21 +377,40 @@ def display_final_results(self, final_params, final_resonance_freq): results_text += f"
  • {param}: {formatted_value}
  • " results_text += "" + self.save_results(final_params, export_specific_path=False, reload_to_parameters=False) + results_label = QLabel(results_text) results_label.setWordWrap(True) layout.addWidget(results_label) save_button = QPushButton("Save Results") - save_button.clicked.connect(lambda: self.save_results(final_params, final_resonance_freq)) + save_button.clicked.connect(lambda: self.save_results(final_params, export_specific_path=True)) + layout.addWidget(save_button) + + save_button = QPushButton("Load to parameters") + save_button.clicked.connect(lambda: self.save_results(final_params, export_specific_path=False)) layout.addWidget(save_button) result_dialog.setLayout(layout) result_dialog.exec() - def save_results(self, final_params, final_resonance_freq): + def save_results(self, final_params, reload_to_parameters = False,export_specific_path = False): + """ + Used to save the results of the optimisation to a JSON file or reload the results to the input parameters. + Also create a temp.json file in the output folder to not lose the results. + :param final_params: best parameters found + :param reload_to_parameters: boolean to reload the results to the input parameters + :param export_specific_path: boolean to export the results to a specific path + :return: + """ try : - path, _ = QFileDialog.getSaveFileName(self, "Export Optimisation data", "", "json Files (*.png)") + if not export_specific_path: + # default path output/temp.json + path = "output/temp.json" + else : + path, _ = QFileDialog.getSaveFileName(self, "Export Optimisation data", "", "json Files (*.png)") + if not path: return @@ -386,8 +455,8 @@ def save_results(self, final_params, final_resonance_freq): # Save the results to a file with open(path, 'w') as file: json.dump(input_parameters_copy, file, indent=4) - - self.reload_on_gui() + if reload_to_parameters: + self.reload_on_gui() except FileNotFoundError: QMessageBox.warning(self, "Invalid File", "Please enter a valid file name.") @@ -397,6 +466,10 @@ def save_results(self, final_params, final_resonance_freq): def reload_on_gui(self): + """ + Reload the results to the input parameters. + :return: + """ # Update the input parameters self.gui.import_parameters_from_json(path=self.saved_path, need_filename=False) self.gui.tabs.setCurrentIndex(0) From 2c62750fc212e8e5b22a2cac5a9e261ba8c58760 Mon Sep 17 00:00:00 2001 From: mroncera Date: Wed, 29 May 2024 10:36:54 +0200 Subject: [PATCH 11/16] FIX - add a popup error message when switching to a bugged strategy --- src/controler/controller.py | 4 ++-- src/model/strategies/strategy_lib/impedance.py | 1 + src/view/gui.py | 6 +++++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/controler/controller.py b/src/controler/controller.py index 348ea7a..74422de 100644 --- a/src/controler/controller.py +++ b/src/controler/controller.py @@ -22,7 +22,7 @@ from src.model.strategies.strategy_lib.Nz import AnalyticalNzStrategy from src.model.strategies.strategy_lib.capacitance import AnalyticalCapacitanceStrategy from src.model.strategies.strategy_lib.frequency import FrequencyVectorStrategy -from src.model.strategies.strategy_lib.impedance import AnalyticalImpedanceStrategy +from src.model.strategies.strategy_lib.impedance import AnalyticalImpedanceStrategy, AnalyticalImpedanceStrategy_hsw from src.model.strategies.strategy_lib.inductance import AnalyticalInductanceStrategy from src.model.strategies.strategy_lib.lambda_strategy import AnalyticalLambdaStrategy from src.model.strategies.strategy_lib.mu_app import AnalyticalMu_appStrategy @@ -63,7 +63,7 @@ }, "impedance": { "default": AnalyticalImpedanceStrategy, - "strategies": [AnalyticalImpedanceStrategy] + "strategies": [AnalyticalImpedanceStrategy, AnalyticalImpedanceStrategy_hsw] }, "TF_ASIC_Stage_1": { "default": TF_ASIC_Stage_1_Strategy_linear, diff --git a/src/model/strategies/strategy_lib/impedance.py b/src/model/strategies/strategy_lib/impedance.py index 2c3a48b..fb02957 100644 --- a/src/model/strategies/strategy_lib/impedance.py +++ b/src/model/strategies/strategy_lib/impedance.py @@ -31,3 +31,4 @@ def calculate_impedance(self, R, L, C, f): @staticmethod def get_dependencies(): return ['resistance', 'inductance', 'capacitance', 'frequency_vector'] + diff --git a/src/view/gui.py b/src/view/gui.py index 1d74bf5..446e4a9 100644 --- a/src/view/gui.py +++ b/src/view/gui.py @@ -1719,7 +1719,11 @@ def update_node_strategy(self, node_name, strategy_class): print(f"Invalid input for parameter '{param}': '{text}'. Skipping calculation.") return - self.controller.set_node_strategy(node_name, strategy_class, params_dict) + try : + self.controller.set_node_strategy(node_name, strategy_class, params_dict) + except Exception as e: + self.display_error(f"Error updating strategy for {node_name}: {e}") + self.calculate() def save_results(self, index, button): From 94d1aa88ef449bd39c62adac1c3e449d1bf3fec0 Mon Sep 17 00:00:00 2001 From: mroncera Date: Thu, 13 Jun 2024 18:25:22 +0200 Subject: [PATCH 12/16] REFACTOR/DOC - delete contributing.md as all the documentation is now compilated and uploaded to readthedoc --- contributing.md | 320 ---------------------------------- docs/contributing.rst | 90 ++++++++-- readme.md | 13 +- src/controler/controller.py | 169 +----------------- src/controler/models/JUICE.py | 152 ++++++++++++++++ 5 files changed, 244 insertions(+), 500 deletions(-) delete mode 100644 contributing.md create mode 100644 src/controler/models/JUICE.py diff --git a/contributing.md b/contributing.md deleted file mode 100644 index 6363dee..0000000 --- a/contributing.md +++ /dev/null @@ -1,320 +0,0 @@ -# Table of Contents - -- [How to add a new calculation strategy](#How-to-add-a-new-calculation-strategy) - - [Preliminary Checks](#Preliminary-Checks) - - [Adding New Parameters](#Adding-New-Parameters) - - [Strategy Implementation](#Strategy-Implementation) - - [Method Specifications](#Method-Specifications) - - [Dependencies](#Dependencies) - - [Calculate method](#Calculate-method) -- [How to add a new parameter](#How-to-add-a-new-parameter) - - [Unit Conversion](#Unit-Conversion) -- [Linting](#Linting) -- [Git Guidelines](#Git-Guidelines) - - [Branching Strategy](#Branching-Strategy) - - [Commit Message Format](#Commit-Message-Format) - - [Types](#Types) - - [Best Practices for Pull Requests](#Best-Practices-for-Pull-Requests) -- [SPICE](#SPICE) - -# How to add a new calculation strategy - -## Preliminary Checks - -1. Review Existing Strategies: Inspect all the calculation strategies in the calculation_strategies folder to ensure your strategy hasn't already been implemented. -2. Review Parameters: Examine the parameters defined in `/data/default.json`. Determine if new parameters are needed for your strategy. - -## Adding New Parameters -3. Parameter Addition: If your strategy introduces new parameters, add them to the ``default.json`` file. Refer to the Adding a New Parameter section for detailed guidance.4. Check all the existing Nodes you can use. The list of existing nodes and their calculation strategy can be found in `src/controler/controller.py`. - -## Strategy Implementation -4. Utilize Existing Nodes: Explore the list of nodes in ``src/controller/controller.py``to understand the available calculation strategies. Avoid recalculating nodes. -```python -self.engine.add_or_update_node('frequency_vector', FrequencyVectorStrategy()) -self.engine.add_or_update_node('resistance', AnalyticalResistanceStrategy()) -self.engine.add_or_update_node('Nz', AnalyticalNzStrategy()) -... -``` -DO NOT recalculate the same node with a different strategy. Instead, apply your new strategy to an existing node. - - -5. If your calculation strategy is not implemented, create a new file in the `src/model/strategies/strategy_lib/` folder with the name of your calculation strategy. - -This file should: -- Inherit from the `CalculationStrategy` class. -- Implement the `calculate` method. -- Implement the `get_dependencies` method. - - -6. Node Association: Incorporate your newly created strategy into the controller by assigning it to a node. -```python - -self.engine.add_or_update_node('node_name', YourStrategy()) - -``` - -## Method Specifications - -### Dependencies -- The get_dependencies method must return a list of required parameters or nodes as strings, matching their names in the default.json file or controller. -### Calculate method -The `calculate` method must return the result of the calculation. The method takes two arguments: -- `dependencies`: A dictionary containing the values of all the nodes available in the engine. The keys are the names of the nodes, and the values are the results of the calculation. -- `parameters`: An instance of the `InputParameters` class containing the values of the parameters entered by the user. - -This method must return the result of the calculation. -The result can be on of the following: -- A single value (int, float, etc.) -- A Tensor (2D array) containing the result of the calculation for each frequency value. The first column must be the frequency values or (the x_axis for the plot), and the following columns must be the result of the calculation. - -ALL OUTPUTS MUST BE IN SI UNITS in linear scale (no dB, no log scale). - - -### Examples : -```python -class AnalyticalResistanceStrategy(CalculationStrategy): - - def calculate(self, dependencies: dict, parameters: InputParameters): - N = parameters.data['nb_spire'] - Rs = parameters.data['ray_spire'] - rho = parameters.data['rho_whire'] - return N * (2 * np.pi * Rs) * rho - - @staticmethod - def get_dependencies(): - return ['nb_spire', 'ray_spire', 'rho_whire'] -``` - -```python -class AnalyticalImpedanceStrategy(CalculationStrategy): - - def calculate(self, dependencies: dict, parameters: InputParameters): - R = dependencies['resistance'] - L = dependencies['inductance'] - C = dependencies['capacitance'] - - frequency_vector = dependencies['frequency_vector'] - - - vectorized_impedance = np.vectorize(self.calculate_impedance) - impedance_values = vectorized_impedance(R, L, C, frequency_vector) - frequency_impedance_tensor = np.column_stack((frequency_vector, impedance_values)) - return frequency_impedance_tensor - - def calculate_impedance(self, R, L, C, f): - impedance_num = (R ** 2) + (L * 2 * np.pi * f) ** 2 - impedance_den = (1 - L * C * (2 * np.pi * f) ** 2) ** 2 + (R * C * (2 * np.pi * f)) ** 2 - return np.sqrt(impedance_num / impedance_den) - - @staticmethod - def get_dependencies(): - return ['resistance', 'inductance', 'capacitance', 'frequency_vector'] - -``` - -# How to add a new parameter - -1. **Existing Parameters:** Verify if the new parameter exists within /data/default.json. -2. **Addition:** Introduce new parameters to `default.json` as needed, adhering to the specified format: -The file must be in the following format: - -```json -{ "section_name": - { - "param_name": { - "default": XX, - "min": XX, - "max": XX, - "description": "Short description, used for the user interface", - "input_unit": "", - "target_unit": "" - } - } -} - -``` - -Note that the `section_name` is the name of the section in the user interface. The `param_name` is the name of the parameter in the user interface. -Each section can have multiple parameters. - -These are the fields that must be filled in if your parameter is a number that require unit conversion: - -```json -"input_unit": "", -"target_unit": "" -``` -### Unit Conversion - - -For example, you don't want to input a lenght in mm and write 0.001 m in the input field. You can define the input unit as mm and the target unit as m. The user will input 1 mm and the system will convert it to 0.001 m. - -Utilize the ``pint`` library for unit conversion. Input and target units should be defined for parameters requiring conversion. -For comprehensive unit support and details, visit Pint's documentation. - -Example: -```json -"capa_triwire": { - "default": 150, - "min": 10, - "max": 1000, - "description": "Triwire capacitance in picofarads", - "input_unit": "picofarad", - "target_unit": "farad" - } -``` - -# Linting - -We use pylint to ensure compliance with PEP8 guidelines. Lint your code with: -```bash - pylint --rcfile pylintrc src/folder/file.py -``` - -Replace `src/folder/file.py` with the path to the file you want to lint. -Check the return of the command to see if there are any errors or warnings in the code. Adapt and correct the code according to the pylint output. - -You can read the [pylint documentation](https://pylint.pycqa.org/en/latest/) for more information on how to use pylint. - -# Git Guidelines - -To maintain the repository's integrity and streamline development processes, we adhere to a GitFlow-inspired workflow and specific naming conventions for branches and commit messages. Below is a comprehensive guide on how to contribute code to this project effectively. - -## Branching Strategy - -We use a branching strategy that categorizes work based on the nature of changes, ensuring that our repository remains organized and manageable. When starting work on a new feature, bug fix, or other tasks, you must create a new branch following these conventions: - -- **Feature Branches**: `engine/branch-name`, `UI/branch-name`, `controller/branch-name` -- **Refactoring**: `refactor/branch-name` - -**Important**: Direct commits to the `dev` branch are prohibited. Always create a new branch for your work, branching off from the latest `dev` branch. - -## Commit Message Format - -Commit messages should be clear, concise, and follow a formal structure to simplify the repository's history. Use the following format: - -``` -TYPE[TAG] - DESCRIPTION - -[optional body] - -[optional footer(s)] -``` - - -**Tags**: Include `#issue_id` if your work addresses a specific open issue. - -### Types - -- `FEAT`: Introduces a new feature. -- `FIX`: Fixes a bug. -- `CHORE`: Changes that don't affect the source or test files, like updating dependencies. -- `REFACTOR`: Code changes that neither fix a bug nor add a feature. -- `DOC`: Documentation updates. -- `QUAL`: General code quality improvements. -- `TEST`: Adds or updates tests. -- `PERF`: Performance improvements. -- `REVERT`: Reverts a previous commit. - -For more detailed examples and best practices on commit messages, refer to [this article](https://www.freecodecamp.org/news/how-to-write-better-git-commit-messages/). - -## Best Practices for Pull Requests - -- **Scope**: Keep your pull requests small and focused on a single feature or bug fix to facilitate the review process. -- **Adherence to Standards**: Ensure your contributions follow the project's coding standards and guidelines. -- **Stay Updated**: Regularly update your fork to keep it in sync with the main project. This helps in minimizing merge conflicts. -- **Linting**: Run the linter on your code before submitting a pull request to ensure compliance with PEP8 guidelines. -- **Documentation**: Update the documentation if your changes affect the project's functionality or require additional information. - -By following these guidelines, you contribute to the efficiency and clarity of the project, making it easier for others to review your contributions and maintain the project's health. - -# SPICE - -Simulation Program with Integrated Circuit Emphasis (SPICE) is a general-purpose analog electronic circuit simulator. It is a powerful tool for simulating and analyzing circuits, providing valuable insights into circuit behavior and performance. SPICE is widely used in the electronics industry for designing and testing circuits, making it an essential tool for electrical engineers and circuit designers. - -In PLASMAG, we integrate spice simulations to allow the user to create their own models and have more accurate results. - -## How to add a new SPICE model - -### 1. Prepare the JSON Configuration for the SPICE Module - -Each SPICE module is defined in a JSON file, which outlines the circuit characteristics along with associated parameters and calculation strategies. Here are the steps to prepare this file: - -1. **Module Key Creation:** -Add a new key in the JSON file (e.g., **spice_new_model**) that will act as a unique identifier for the new module. - -2. **Defining Module Attributes:** - - **name:** The name of the module, such as "New OP AMP Model". - - **description:** A detailed description of the module, used for the user interface. - - **image:** The filename of the image representing the circuit (must be pre-added to the relevant images directory). - -3. **Parameters:** - Define all necessary parameters for the module. Each parameter should include: - - **default, min, max:** Default, minimum, and maximum values. - - **description:** A description of the parameter for the user interface. - - **input_unit and target_unit:** Input and conversion units, if applicable. - -4. **Strategies:** - - Add references to specific calculation strategies used by this module in the `src/model/strategies/strategy_lib/` directory. - - Each strategy must have a **name** and a **file** pointing to the Python script implementing the strategy. - -#### Example JSON Section for a New SPICE Module - -```json -"spice_new_model" : { - "name" : "New OP AMP Model", - "description" : "An advanced test circuit for the spice simulator", - "image" : "new_op_amp_model.png", - "parameters" : { - "R1": { - "default": 500, - "min": 10, - "max": 10000, - "description": "Spice test resistance", - "input_unit": "ohm", - "target_unit": "ohm" - } - }, - "strategies" : { - "SPICE_impedance" : { - "name" : "SPICE Impedance", - "file" : "src/model/strategies/strategy_lib/SPICE.py" - } - } -} - -``` - -### 2. Implement Calculation Strategies - -For each strategy listed in the JSON configuration: - -- Create a Python class in the specified file within `src/model/strategies/strategy_lib/`. -- Each class should inherit from the **CalculationStrategy** class and implement necessary methods such as **calculate** and **get_dependencies**. -- The calculate method should handle the specific SPICE simulation logic based on input parameters and dependencies defined in the module. - - -### 3. Test and Validate - -Once the new module is configured and the strategies are implemented: - -- Test the module extensively to ensure that it works as expected with the SPICE simulator. You can try the script outside of PLASMAG -in the `if __name__ == "__main__"`, with mock data. -- Validate that all parameters and calculations produce accurate and reliable results. - -### 4. Update User Documentation and Interface - -- Add any necessary documentation to help users understand how to use the new SPICE module. - -### 5. Commit Changes - -Follow the project's Git guidelines to commit and push the new module to the repository: - -- Create a feature branch, e.g., feature/spice_new_model. -- Commit your changes with a clear message describing the addition of the new SPICE module. -- Open a pull request for review. - -### 5. MISC - -- Make sure to return the results in SI units for consistency. X-axis values should be in Hz, or seconds for time-domain simulations. -- If the X-axis is in the time domain, make sure to return the time vector as the first column of the tensor, with the following label : "Time" -- If you are returning the Gain and the Phase, make sure to return a linear Gain, and the phase in radians. The first column should be the frequency values, the second column the gain, and the third column the phase, with the following labels : "Frequency", "Gain", "Phase" diff --git a/docs/contributing.rst b/docs/contributing.rst index 47d2259..6335959 100644 --- a/docs/contributing.rst +++ b/docs/contributing.rst @@ -30,6 +30,21 @@ Contributing - `SPICE <#SPICE>`__ +Two cases are possible when you want to contribute to the project: +- You want to add a new calculation strategy and increment the actual model, or +you want to add a new strategy to a Node of the actual model. See `Add a New Strategy <#How-to-add-a-new-calculation-strategy>`__ for more information. + +- You want to start a brand new model, that differs highly from the actual model but keep using PLASMAG's architecture +see `New model <#New-model>`__ for more information. + + +Documentation +------------- + +DO NOT forget to update the documentation in ``PLASMAG/doccs/ for your module``. +Also recompile the documentation on readthedocs if you pushed your changes to Master. + + How to add a new calculation strategy ------------------------------------- @@ -38,7 +53,8 @@ Preliminary Checks 1. Review Existing Strategies: Inspect all the calculation strategies in the calculation_strategies folder to ensure your strategy hasn’t - already been implemented. + already been implemented. All the strategies are located in the + ``src/model/strategies/strategy_lib/`` folder. 2. Review Parameters: Examine the parameters defined in ``/data/default.json``. Determine if new parameters are needed for your strategy. @@ -55,19 +71,31 @@ Adding New Parameters Strategy Implementation ----------------------- -4. Utilize Existing Nodes: Explore the list of nodes in +4. Utilize Existing Nodes: Explore the list of nodes in the actual model STRATEGY_MAP used in ``src/controller/controller.py``\ to understand the available calculation strategies. Avoid recalculating nodes. +The strategy map can be found in the ``src/controler/models/JUICE.py`` file. .. code:: python - self.engine.add_or_update_node('frequency_vector', FrequencyVectorStrategy()) - self.engine.add_or_update_node('resistance', AnalyticalResistanceStrategy()) - self.engine.add_or_update_node('Nz', AnalyticalNzStrategy()) + STRATEGY_MAP = { + "resistance": { + "default": AnalyticalResistanceStrategy, + "strategies": [AnalyticalResistanceStrategy, AnalyticalResistanceStrategyv2] + }, + "frequency_vector": { + "default": FrequencyVectorStrategy, + "strategies": [FrequencyVectorStrategy] + }, + "Nz": { + "default": AnalyticalNzStrategy, + "strategies": [AnalyticalNzStrategy] + }, ... DO NOT recalculate the same node with a different strategy. Instead, -apply your new strategy to an existing node. +apply your new strategy to an existing node. Simply by adding it to the +"strategies" list of the node in the STRATEGY_MAP. Or replacing the "default" strategy by your new strategy. 5. If your calculation strategy is not implemented, create a new file in the ``src/model/strategies/strategy_lib/`` folder with the name of @@ -82,8 +110,12 @@ method. .. code:: python +from src.model.strategies.strategy_lib.YOUR_MODULE import YOUR_STRATEGY - self.engine.add_or_update_node('node_name', YourStrategy()) + "NODE_NAME": { + "default": YOUR_STRATEGY, + "strategies": [YOUR_STRATEGY] + }, Method Specifications --------------------- @@ -93,7 +125,8 @@ Dependencies - The get_dependencies method must return a list of required parameters or nodes as strings, matching their names in the default.json file or - controller. ### Calculate method The ``calculate`` method must return + controller. +- ``The ``calculate`` method must return the result of the calculation. The method takes two arguments: - ``dependencies``: A dictionary containing the values of all the nodes available in the engine. The keys are the names of the nodes, and the @@ -158,7 +191,7 @@ How to add a new parameter 1. **Existing Parameters:** Verify if the new parameter exists within /data/default.json. -2. **Addition:** Introduce new parameters to ``default.json`` as needed, +2. **Addition:** Introduce new parameters to ``default.json`` or ``your_config.json``as needed, adhering to the specified format: The file must be in the following format: @@ -329,11 +362,11 @@ How to add a new SPICE model 1. Prepare the JSON Configuration for the SPICE Module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Each SPICE module is defined in a JSON file, which outlines the circuit +Each SPICE module is defined in a JSON file ``/data/SPICE.json``, which outlines the circuit characteristics along with associated parameters and calculation strategies. Here are the steps to prepare this file: -1. **Module Key Creation:** Add a new key in the JSON file (e.g., +1. **Module Key Creation:** Add a new key/circuit in the JSON file (e.g., **spice_new_model**) that will act as a unique identifier for the new module. @@ -343,7 +376,8 @@ strategies. Here are the steps to prepare this file: - **description:** A detailed description of the module, used for the user interface. - **image:** The filename of the image representing the circuit - (must be pre-added to the relevant images directory). + (must be pre-added to the relevant images directory) ``/ressources/``. + 3. **Parameters:** Define all necessary parameters for the module. Each parameter should include: @@ -354,6 +388,17 @@ strategies. Here are the steps to prepare this file: - **input_unit and target_unit:** Input and conversion units, if applicable. +.. code:: json + + "R1": { + "default": 1000, + "min": 1, + "max": 10000, + "description": "Spice resistance connected to pre amp", + "input_unit": "", + "target_unit": "" + } + 4. **Strategies:** - Add references to specific calculation strategies used by this @@ -361,6 +406,20 @@ strategies. Here are the steps to prepare this file: - Each strategy must have a **name** and a **file** pointing to the Python script implementing the strategy. +.. code:: json + + "strategies" : { + "SPICE_impedance" : { + "name" : "SPICE impedance", + "file" : "src/model/strategies/strategy_lib/SPICE.py" + }, + "SPICE_op_Amp_transcient" : { + "name" : "SPICE op Amp transcient", + "file" : "src/model/strategies/strategy_lib/SPICE.py" + }, + .... + + Example JSON Section for a New SPICE Module ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -442,3 +501,10 @@ the repository: linear Gain, and the phase in radians. The first column should be the frequency values, the second column the gain, and the third column the phase, with the following labels : “Frequency”, “Gain”, “Phase” + + + +New model +--------- + +TODO \ No newline at end of file diff --git a/readme.md b/readme.md index 1fcd9db..f832363 100644 --- a/readme.md +++ b/readme.md @@ -9,6 +9,7 @@ At its core, PLASMAG serves as a comprehensive tool for the parameters adjustmen Currently, PLASMAG is tailored to support search coil type instruments. However, its architecture is built with flexibility and extensibility in mind. This means PLASMAG is not only limited to current implementations but is also designed to easily accommodate the addition of new instruments and the integration of diverse calculation methods and models. +Online documentation can be found [here](https://plasmag.readthedocs.io/en/master/) ## Table of Contents @@ -100,14 +101,15 @@ python PLASMAG.py 3. Modularity and Flexibility: - Strategy Design Pattern: Implements a modular engine design using the strategy pattern, allowing dynamic changes in computation methods and easy adaptation to new requirements. -- Parallel Computation: Supports parallelization of computations for improved efficiency. +- Parallel Computation: Supports parallelization of computations for improved efficiency, to be implemented for futures improvements. - Graph Visualization Tools: Provides full graph visualization to monitor computation dependencies and processes. 4. Export and Import Capabilities: - Export Data: Allows exporting of any product or parameter for plotting or later re-importation. +- NEMI/CLTF Export: Exports the NEMI and Closed Loop Transfer Function (CLTF) graphs for easy design sharing. -5. Optimization Module (Work in Progress): +5. Optimization Module (WIP): - Genetic Optimization (DEAP): Utilizes evolutionary algorithms to find optimal parameter sets. - Particle Swarm Optimization: Implements swarm intelligence techniques to explore solution spaces. @@ -115,6 +117,9 @@ python PLASMAG.py - Mono-parameter and Multi-parameter Optimization: Supports optimization for single and multiple parameters. - Mono-criteria and Multi-criteria Optimization: Handles single and multiple criteria, combining them into a single framework using weighted polynomials. +**Available Targets:** +- Impedance (Resonance Frequency) +- NEMI (WIP) ## Availables Models @@ -135,6 +140,10 @@ increasingly difficult, leading to a slight deviation from expected behaviors. This discrepancy underlines a current limitation of the model, spotlighting the need for further refinement and development to enhance its accuracy. +The model (combination of all calculation strategy) is composed of 2 parts: +- ``data/JUICE.json`` : Contains the parameters of the JUICE search coil magnetometer, their values will be used for computations +- ```` + ## Documentation To generate project documentation: diff --git a/src/controler/controller.py b/src/controler/controller.py index 74422de..82fe5ef 100644 --- a/src/controler/controller.py +++ b/src/controler/controller.py @@ -6,174 +6,11 @@ import json import numpy as np - -from src.model.strategies.strategy_lib.Noise import PSD_R_cr, PSD_R_cr_filtered, PSD_R_Coil, PSD_R_Coil_filtered, \ - PSD_Flicker, PSD_e_en, PSD_e_en_filtered, PSD_e_in, PSD_e_in_filtered, PSD_Total, PSD_Total_filtered, \ - Display_all_PSD, NEMI, Display_all_PSD_filtered, NEMI_FIltered, NEMI_FIlteredv2, NEMI_FIlteredv3, PSD_R_cr_V2, \ - PSD_R_cr_filtered_V2, PSD_R_Coil_V2, PSD_R_Coil_filtered_V2, PSD_Flicker_V2, PSD_e_en_V2, PSD_e_en_filtered_V2, \ - PSD_e_in_V2, PSD_e_in_filtered_V2 -from src.model.strategies.strategy_lib.CLTF import CLTF_Strategy_Filtered, \ - CLTF_Strategy_Non_Filtered_legacy, Display_CLTF_OLTF -from src.model.strategies.strategy_lib.OLTF import OLTF_Strategy_Non_Filtered, OLTF_Strategy_Filtered -from src.model.strategies.strategy_lib.TF_ASIC import TF_ASIC_Stage_1_Strategy_linear, \ - TF_ASIC_Stage_2_Strategy_linear, TF_ASIC_Strategy_linear +from src.controler.models.JUICE import STRATEGY_MAP from src.model.input_parameters import InputParameters from src.model.engine import CalculationEngine -from src.model.strategies.strategy_lib.Nz import AnalyticalNzStrategy -from src.model.strategies.strategy_lib.capacitance import AnalyticalCapacitanceStrategy -from src.model.strategies.strategy_lib.frequency import FrequencyVectorStrategy -from src.model.strategies.strategy_lib.impedance import AnalyticalImpedanceStrategy, AnalyticalImpedanceStrategy_hsw -from src.model.strategies.strategy_lib.inductance import AnalyticalInductanceStrategy -from src.model.strategies.strategy_lib.lambda_strategy import AnalyticalLambdaStrategy -from src.model.strategies.strategy_lib.mu_app import AnalyticalMu_appStrategy -from src.model.strategies.strategy_lib.resistance import AnalyticalResistanceStrategy, AnalyticalResistanceStrategyv2 -from src.model.strategies.strategy_lib.SPICE import SPICE_test, SPICE_op_Amp_gain, SPICE_op_Amp_transcient, \ - SPICE_impedance - -STRATEGY_MAP = { - "resistance": { - "default": AnalyticalResistanceStrategy, - "strategies": [AnalyticalResistanceStrategy, AnalyticalResistanceStrategyv2] - }, - "frequency_vector": { - "default": FrequencyVectorStrategy, - "strategies": [FrequencyVectorStrategy] - }, - "Nz": { - "default": AnalyticalNzStrategy, - "strategies": [AnalyticalNzStrategy] - }, - "mu_app": { - "default": AnalyticalMu_appStrategy, - "strategies": [AnalyticalMu_appStrategy] - }, - - "lambda_param": { - "default": AnalyticalLambdaStrategy, - "strategies": [AnalyticalLambdaStrategy] - }, - - "inductance": { - "default": AnalyticalInductanceStrategy, - "strategies": [AnalyticalInductanceStrategy] - }, - "capacitance": { - "default": AnalyticalCapacitanceStrategy, - "strategies": [AnalyticalCapacitanceStrategy] - }, - "impedance": { - "default": AnalyticalImpedanceStrategy, - "strategies": [AnalyticalImpedanceStrategy, AnalyticalImpedanceStrategy_hsw] - }, - "TF_ASIC_Stage_1": { - "default": TF_ASIC_Stage_1_Strategy_linear, - "strategies": [TF_ASIC_Stage_1_Strategy_linear] - }, - "TF_ASIC_Stage_2": { - "default": TF_ASIC_Stage_2_Strategy_linear, - "strategies": [TF_ASIC_Stage_2_Strategy_linear] - }, - "TF_ASIC_linear": { - "default": TF_ASIC_Strategy_linear, - "strategies": [TF_ASIC_Strategy_linear] - }, - "OLTF_Non_filtered": { - "default": OLTF_Strategy_Non_Filtered, - "strategies": [OLTF_Strategy_Non_Filtered] - }, - "OLTF_Filtered": { - "default": OLTF_Strategy_Filtered, - "strategies": [OLTF_Strategy_Filtered] - }, - "CLTF_Non_filtered": { - "default": CLTF_Strategy_Non_Filtered_legacy, - "strategies": [CLTF_Strategy_Non_Filtered_legacy] - }, - "CLTF_Filtered": { - "default": CLTF_Strategy_Filtered, - "strategies": [CLTF_Strategy_Filtered] - }, - "Display_CLTF_OLTF": { - "default": Display_CLTF_OLTF, - "strategies": [Display_CLTF_OLTF] - }, - "PSD_R_cr": { - "default": PSD_R_cr, - "strategies": [PSD_R_cr, PSD_R_cr_V2] - }, - "PSD_R_cr_filtered": { - "default": PSD_R_cr_filtered, - "strategies": [PSD_R_cr_filtered,PSD_R_cr_filtered_V2] - }, - "PSD_R_Coil": { - "default": PSD_R_Coil, - "strategies": [PSD_R_Coil, PSD_R_Coil_V2] - }, - "PSD_R_Coil_filtered": { - "default": PSD_R_Coil_filtered, - "strategies": [PSD_R_Coil_filtered, PSD_R_Coil_filtered_V2] - }, - "PSD_Flicker": { - "default": PSD_Flicker, - "strategies": [PSD_Flicker, PSD_Flicker_V2] - }, - "PSD_e_en": { - "default": PSD_e_en, - "strategies": [PSD_e_en, PSD_e_en_V2] - }, - "PSD_e_en_filtered": { - "default": PSD_e_en_filtered, - "strategies": [PSD_e_en_filtered, PSD_e_en_filtered_V2] - }, - "PSD_e_in": { - "default": PSD_e_in, - "strategies": [PSD_e_in, PSD_e_in_V2] - }, - "PSD_e_in_filtered": { - "default": PSD_e_in_filtered, - "strategies": [PSD_e_in_filtered, PSD_e_in_filtered_V2] - }, - "PSD_Total": { - "default": PSD_Total, - "strategies": [PSD_Total] - }, - "PSD_Total_filtered": { - "default": PSD_Total_filtered, - "strategies": [PSD_Total_filtered] - }, - "Display_all_PSD": { - "default": Display_all_PSD, - "strategies": [Display_all_PSD] - }, - "Display_all_PSD_filtered": { - "default": Display_all_PSD_filtered, - "strategies": [Display_all_PSD_filtered] - }, - "NEMI": { - "default": NEMI, - "strategies": [NEMI] - }, - "NEMI_FIltered": { - "default": NEMI_FIltered, - "strategies": [NEMI_FIltered,NEMI_FIlteredv2, NEMI_FIlteredv3] - }, - # "SPICE_test": { - # "default": SPICE_test, - # "strategies": [SPICE_test] - # }, - # "SPICE_op_Amp_gain" : { - # "default": SPICE_op_Amp_gain, - # "strategies": [SPICE_op_Amp_gain] - # }, - # "SPICE_op_Amp_transcient": { - # "default": SPICE_op_Amp_transcient, - # "strategies": [SPICE_op_Amp_transcient] - # }, - # "SPICE_impedance" : { - # "default": SPICE_impedance, - # "strategies": [SPICE_impedance] - # } -} + + class CalculationController: """ The CalculationController class is responsible for managing the calculation engine and the input parameters diff --git a/src/controler/models/JUICE.py b/src/controler/models/JUICE.py new file mode 100644 index 0000000..7fd39be --- /dev/null +++ b/src/controler/models/JUICE.py @@ -0,0 +1,152 @@ +from src.model.strategies.strategy_lib.Noise import PSD_R_cr, PSD_R_cr_filtered, PSD_R_Coil, PSD_R_Coil_filtered, \ + PSD_Flicker, PSD_e_en, PSD_e_en_filtered, PSD_e_in, PSD_e_in_filtered, PSD_Total, PSD_Total_filtered, \ + Display_all_PSD, NEMI, Display_all_PSD_filtered, NEMI_FIltered, NEMI_FIlteredv2, NEMI_FIlteredv3, PSD_R_cr_V2, \ + PSD_R_cr_filtered_V2, PSD_R_Coil_V2, PSD_R_Coil_filtered_V2, PSD_Flicker_V2, PSD_e_en_V2, PSD_e_en_filtered_V2, \ + PSD_e_in_V2, PSD_e_in_filtered_V2 +from src.model.strategies.strategy_lib.CLTF import CLTF_Strategy_Filtered, \ + CLTF_Strategy_Non_Filtered_legacy, Display_CLTF_OLTF +from src.model.strategies.strategy_lib.OLTF import OLTF_Strategy_Non_Filtered, OLTF_Strategy_Filtered +from src.model.strategies.strategy_lib.TF_ASIC import TF_ASIC_Stage_1_Strategy_linear, \ + TF_ASIC_Stage_2_Strategy_linear, TF_ASIC_Strategy_linear + +from src.model.strategies.strategy_lib.Nz import AnalyticalNzStrategy +from src.model.strategies.strategy_lib.capacitance import AnalyticalCapacitanceStrategy +from src.model.strategies.strategy_lib.frequency import FrequencyVectorStrategy +from src.model.strategies.strategy_lib.impedance import AnalyticalImpedanceStrategy +from src.model.strategies.strategy_lib.inductance import AnalyticalInductanceStrategy +from src.model.strategies.strategy_lib.lambda_strategy import AnalyticalLambdaStrategy +from src.model.strategies.strategy_lib.mu_app import AnalyticalMu_appStrategy +from src.model.strategies.strategy_lib.resistance import AnalyticalResistanceStrategy, AnalyticalResistanceStrategyv2 +from src.model.strategies.strategy_lib.SPICE import SPICE_test, SPICE_op_Amp_gain, SPICE_op_Amp_transcient, \ + SPICE_impedance + + +STRATEGY_MAP = { + "resistance": { + "default": AnalyticalResistanceStrategy, + "strategies": [AnalyticalResistanceStrategy, AnalyticalResistanceStrategyv2] + }, + "frequency_vector": { + "default": FrequencyVectorStrategy, + "strategies": [FrequencyVectorStrategy] + }, + "Nz": { + "default": AnalyticalNzStrategy, + "strategies": [AnalyticalNzStrategy] + }, + "mu_app": { + "default": AnalyticalMu_appStrategy, + "strategies": [AnalyticalMu_appStrategy] + }, + + "lambda_param": { + "default": AnalyticalLambdaStrategy, + "strategies": [AnalyticalLambdaStrategy] + }, + + "inductance": { + "default": AnalyticalInductanceStrategy, + "strategies": [AnalyticalInductanceStrategy] + }, + "capacitance": { + "default": AnalyticalCapacitanceStrategy, + "strategies": [AnalyticalCapacitanceStrategy] + }, + "impedance": { + "default": AnalyticalImpedanceStrategy, + "strategies": [AnalyticalImpedanceStrategy] + }, + "TF_ASIC_Stage_1": { + "default": TF_ASIC_Stage_1_Strategy_linear, + "strategies": [TF_ASIC_Stage_1_Strategy_linear] + }, + "TF_ASIC_Stage_2": { + "default": TF_ASIC_Stage_2_Strategy_linear, + "strategies": [TF_ASIC_Stage_2_Strategy_linear] + }, + "TF_ASIC_linear": { + "default": TF_ASIC_Strategy_linear, + "strategies": [TF_ASIC_Strategy_linear] + }, + "OLTF_Non_filtered": { + "default": OLTF_Strategy_Non_Filtered, + "strategies": [OLTF_Strategy_Non_Filtered] + }, + "OLTF_Filtered": { + "default": OLTF_Strategy_Filtered, + "strategies": [OLTF_Strategy_Filtered] + }, + "CLTF_Non_filtered": { + "default": CLTF_Strategy_Non_Filtered_legacy, + "strategies": [CLTF_Strategy_Non_Filtered_legacy] + }, + "CLTF_Filtered": { + "default": CLTF_Strategy_Filtered, + "strategies": [CLTF_Strategy_Filtered] + }, + "Display_CLTF_OLTF": { + "default": Display_CLTF_OLTF, + "strategies": [Display_CLTF_OLTF] + }, + "PSD_R_cr": { + "default": PSD_R_cr, + "strategies": [PSD_R_cr, PSD_R_cr_V2] + }, + "PSD_R_cr_filtered": { + "default": PSD_R_cr_filtered, + "strategies": [PSD_R_cr_filtered,PSD_R_cr_filtered_V2] + }, + "PSD_R_Coil": { + "default": PSD_R_Coil, + "strategies": [PSD_R_Coil, PSD_R_Coil_V2] + }, + "PSD_R_Coil_filtered": { + "default": PSD_R_Coil_filtered, + "strategies": [PSD_R_Coil_filtered, PSD_R_Coil_filtered_V2] + }, + "PSD_Flicker": { + "default": PSD_Flicker, + "strategies": [PSD_Flicker, PSD_Flicker_V2] + }, + "PSD_e_en": { + "default": PSD_e_en, + "strategies": [PSD_e_en, PSD_e_en_V2] + }, + "PSD_e_en_filtered": { + "default": PSD_e_en_filtered, + "strategies": [PSD_e_en_filtered, PSD_e_en_filtered_V2] + }, + "PSD_e_in": { + "default": PSD_e_in, + "strategies": [PSD_e_in, PSD_e_in_V2] + }, + "PSD_e_in_filtered": { + "default": PSD_e_in_filtered, + "strategies": [PSD_e_in_filtered, PSD_e_in_filtered_V2] + }, + "PSD_Total": { + "default": PSD_Total, + "strategies": [PSD_Total] + }, + "PSD_Total_filtered": { + "default": PSD_Total_filtered, + "strategies": [PSD_Total_filtered] + }, + "Display_all_PSD": { + "default": Display_all_PSD, + "strategies": [Display_all_PSD] + }, + "Display_all_PSD_filtered": { + "default": Display_all_PSD_filtered, + "strategies": [Display_all_PSD_filtered] + }, + "NEMI": { + "default": NEMI, + "strategies": [NEMI] + }, + "NEMI_FIltered": { + "default": NEMI_FIltered, + "strategies": [NEMI_FIltered,NEMI_FIlteredv2, NEMI_FIlteredv3] + }, + +} \ No newline at end of file From 934080eab4d934d71bd13f19958cc9418b598206 Mon Sep 17 00:00:00 2001 From: mroncera Date: Thu, 30 May 2024 09:47:22 +0200 Subject: [PATCH 13/16] FIX - reload data to parameters wasn't working properly --- src/model/optimisation/cost_function.py | 108 +++++++++++++++ .../genetic_optimisation_refactor.py | 128 ++++++++++++++++++ src/view/gui.py | 19 ++- src/view/optimisation_tab.py | 17 ++- 4 files changed, 262 insertions(+), 10 deletions(-) create mode 100644 src/model/optimisation/cost_function.py create mode 100644 src/model/optimisation/genetic_optimisation_refactor.py diff --git a/src/model/optimisation/cost_function.py b/src/model/optimisation/cost_function.py new file mode 100644 index 0000000..b922bac --- /dev/null +++ b/src/model/optimisation/cost_function.py @@ -0,0 +1,108 @@ +from abc import ABC, abstractmethod + +import numpy as np + +from src.controler.controller import CalculationController + + +class BaseEvaluator(ABC): + def __init__(self, parameters_dict, target, strategy_map): + self.parameters_dict = parameters_dict + self.target = target + self.controller = CalculationController() + self.controller.swap_strategy_map(strategy_map) + + @abstractmethod + def evaluate(self, individual): + pass + + def update_target(self, target): + self.target = target + + def set_calculation_controller(self, controller): + self.controller = controller + + def set_strategy_map(self, strategy_map): + self.controller.swap_strategy_map(strategy_map) + + +class ResonanceFrequencyEvaluator(BaseEvaluator): + + def determine_resonance_freq(self, freq_vector, impedance_vector): + index = impedance_vector.argmax() + return freq_vector[index] + + + def evaluate(self, individual): + len_coil, diam_wire, nb_spire, capa_tuning, capa_triwire = individual + + params = self.parameters_dict.copy() + params.update({ + 'len_coil': len_coil, + 'diam_wire': diam_wire, + 'nb_spire': int(nb_spire), + 'capa_tuning': capa_tuning, + 'capa_triwire': capa_triwire + }) + + try: + self.controller.update_parameters(params) + results = self.controller.get_current_results() + impedance = results['impedance']["data"] + resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + return abs(resonance_freq - self.target), + except Exception as e: + return 1e6, + + +class NEMIEvaluator(BaseEvaluator): + def evaluate(self, individual): + len_coil, diam_wire, nb_spire, capa_tuning, capa_triwire = individual + + params = self.parameters_dict.copy() + params.update({ + 'len_coil': len_coil, + 'diam_wire': diam_wire, + 'nb_spire': int(nb_spire), + 'capa_tuning': capa_tuning, + 'capa_triwire': capa_triwire + }) + + try: + self.controller.update_parameters(params) + results = self.controller.get_current_results() + nemi_values = results['nemi']["data"] + distances = [(nemi_value - target_value)**2 for nemi_value, target_value in zip(nemi_values, self.target)] + return sum(distances), + except Exception as e: + return 1e6, + + +class ResonanceFrequencyEvaluator2(BaseEvaluator): + + def determine_resonance_freq(self, freq_vector, impedance_vector): + index = impedance_vector.argmax() + return freq_vector[index] + + def evaluate(self, individual): + len_coil, diam_wire, nb_spire, capa_tuning, capa_triwire = individual + + params = self.parameters_dict.copy() + params.update({ + 'len_coil': len_coil, + 'diam_wire': diam_wire, + 'nb_spire': int(nb_spire), + 'capa_tuning': capa_tuning, + 'capa_triwire': capa_triwire + }) + + try: + self.controller.update_parameters(params) + results = self.controller.get_current_results() + impedance = results['impedance']["data"] + resonance_freq = self.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + objective1 = abs(resonance_freq - self.target) + objective2 = np.sum(np.abs(impedance[:, 1])) # Example of a second objective + return objective1, objective2 + except Exception as e: + return 1e6, 1e6 diff --git a/src/model/optimisation/genetic_optimisation_refactor.py b/src/model/optimisation/genetic_optimisation_refactor.py new file mode 100644 index 0000000..d2409c5 --- /dev/null +++ b/src/model/optimisation/genetic_optimisation_refactor.py @@ -0,0 +1,128 @@ +import random +import numpy as np +from PyQt6.QtCore import pyqtSignal, QThread +from deap import creator, base, tools, algorithms + +from src.model.optimisation.cost_function import ResonanceFrequencyEvaluator, NEMIEvaluator +from src.model.optimisation.impedance_strategy_map import IMPEDANCE_STRATEGY_MAP +from src.controler.controller import CalculationController + + +class GeneticOptimisation(QThread): + update_signal = pyqtSignal(int, float, float) # generation, fitness average, best fitness + finished_signal = pyqtSignal(dict, float) # best parameters, resonance frequency + + def __init__(self, population_size, generations, mutation_rate, evaluator): + super().__init__() + self.population_size = population_size + self.generations = generations + self.mutation_rate = mutation_rate + self.evaluator = evaluator + self.toolbox = None + + self.init_creator() + + def init_creator(self): + creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) + creator.create("Individual", list, fitness=creator.FitnessMin) + + toolbox = base.Toolbox() + toolbox.register("attr_len_coil", random.uniform, 1e-3, 200e-3) + toolbox.register("attr_diam_wire", random.uniform, 10e-6, 300e-6) + toolbox.register("attr_nb_spire", random.uniform, 1000, 20000) + toolbox.register("attr_capa_tuning", random.uniform, 1e-12, 1000e-12) + toolbox.register("attr_capa_triwire", random.uniform, 10e-12, 1000e-12) + toolbox.register("individual", tools.initCycle, creator.Individual, + (toolbox.attr_len_coil, toolbox.attr_diam_wire, toolbox.attr_nb_spire, + toolbox.attr_capa_tuning, toolbox.attr_capa_triwire), + n=1) + toolbox.register("population", tools.initRepeat, list, toolbox.individual) + toolbox.register("evaluate", self.evaluator.evaluate) + toolbox.register("mate", tools.cxTwoPoint) + toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.3) + toolbox.register("select", tools.selTournament, tournsize=5) + + self.toolbox = toolbox + + def run_optimisation(self): + population = self.toolbox.population(n=self.population_size) + hof = tools.HallOfFame(5) # Keep the top 5 individuals + stats = tools.Statistics(lambda ind: ind.fitness.values) + stats.register("min", min) + stats.register("avg", np.mean) + + for gen in range(self.generations): + population, logbook = algorithms.eaSimple(population, self.toolbox, cxpb=0.7, mutpb=self.mutation_rate, + ngen=1, stats=stats, halloffame=hof, verbose=False) + + avg_fitness = logbook.select("avg")[0] + best_fitness = logbook.select("min")[0][0] + print(best_fitness) + self.update_signal.emit(gen, avg_fitness, best_fitness) + + best_params = hof[0] + print("Best Parameters:", best_params) + print("Best Fitness:", self.evaluator.evaluate(best_params)[0]) + + # Update parameters for the final evaluation + final_params = {'len_coil': best_params[0], 'diam_wire': best_params[1], 'nb_spire': int(best_params[2]), + 'capa_tuning': best_params[3], 'capa_triwire': best_params[4]} + self.evaluator.controller.update_parameters(final_params) + final_results = self.evaluator.controller.get_current_results() + impedance = final_results['impedance']["data"] + final_resonance_freq = self.evaluator.determine_resonance_freq(impedance[:, 0], impedance[:, 1]) + print("Final Resonance Frequency:", final_resonance_freq) + print("Final parameters:", final_params) + self.finished_signal.emit(final_params, final_resonance_freq) + return final_resonance_freq, final_params + + def run(self): + self.run_optimisation() + + + +parameters_dict = { + 'f_start': 1, + 'f_stop': 1000000, + 'nb_points_per_decade': 1000, + 'mu_insulator': 1, + 'kapthon_thick': 30e-6, + 'insulator_thick': 10e-6, + 'diam_out_mandrel': 3.2e-3, + 'len_core': 20e-2, + 'diam_core': 3.2e-3, + 'mu_r': 100000, + 'rho_whire': 1.6, + 'coeff_expansion': 1, + 'stage_1_cutting_freq': 20000, + 'stage_2_cutting_freq': 20000, + 'gain_1_linear': 1, + 'gain_2_linear': 1, + 'mutual_inductance': 0.1, + 'feedback_resistance': 1000, + 'temperature': 300, + 'spice_resistance_test': 1000, + 'Para_A': 1, + 'Para_B': 1, + 'e_en': 1, + 'e_in': 1, + 'Alpha': 1, + "ray_spire": 5e-3, + "capa_tuning": 1e-12, + "capa_triwire": 10e-12 +} + +if __name__ == "__main__": + # For resonance frequency optimization + resonance_evaluator = ResonanceFrequencyEvaluator(parameters_dict, target=2350, strategy_map=IMPEDANCE_STRATEGY_MAP) + optimisation = GeneticOptimisation(100, 20, 0.3, resonance_evaluator) + optimisation.run_optimisation() + + # resonance_evaluator.update_target(1350) + # optimisation.run_optimisation() + + # # For NEMI values optimization + # nemi_target = [1, 2, 3, 4, 5] # Example target values + # nemi_evaluator = NEMIEvaluator(parameters_dict, nemi_target, strategy_map=IMPEDANCE_STRATEGY_MAP) + # optimisation = GeneticOptimisation(100, 20, 0.3, nemi_evaluator) + # optimisation.run_optimisation() diff --git a/src/view/gui.py b/src/view/gui.py index 446e4a9..100b700 100644 --- a/src/view/gui.py +++ b/src/view/gui.py @@ -1213,14 +1213,14 @@ def export_parameters_to_json(self): except Exception as e: self.display_error(f"Error exporting parameters: {e}") - def import_parameters_from_json(self, need_filename=True, path=None): + def import_parameters_from_json(self, need_filename=True, path=None, data=None): """ Imports input parameters from a JSON file. The user is prompted to select a file to import the parameters from. The imported parameters are then used to update the UI. :return: """ - # Show an open file dialog to the user + try: filename = None if need_filename: @@ -1230,8 +1230,21 @@ def import_parameters_from_json(self, need_filename=True, path=None): fileName = path if fileName: # If a file is selected, load the parameters from that file + print(fileName) + # with os merge full path with file name + + path = os.path.dirname(os.path.abspath(__file__)) + # go back 2 times + path = os.path.dirname(path) + path = os.path.dirname(path) + full_path = os.path.join(path, fileName) + + with open(fileName, 'r', encoding="utf-8") as json_file: - self.input_parameters = json.load(json_file) + if data is None: + self.input_parameters = json.load(json_file) + else: + self.input_parameters = data self.reset_parameters(reload=False) # Update the UI with the imported parameters print(f"Parameters imported from {fileName}") except Exception as e: diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index 2ad04cb..58b189b 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -366,6 +366,9 @@ def display_final_results(self, final_params, final_resonance_freq): result_dialog = QDialog(self) result_dialog.setWindowTitle("Optimisation Results") + # big size + result_dialog.resize(800, 600) + layout = QVBoxLayout(result_dialog) @@ -377,7 +380,6 @@ def display_final_results(self, final_params, final_resonance_freq): results_text += f"
  • {param}: {formatted_value}
  • " results_text += "" - self.save_results(final_params, export_specific_path=False, reload_to_parameters=False) results_label = QLabel(results_text) results_label.setWordWrap(True) @@ -388,7 +390,7 @@ def display_final_results(self, final_params, final_resonance_freq): layout.addWidget(save_button) save_button = QPushButton("Load to parameters") - save_button.clicked.connect(lambda: self.save_results(final_params, export_specific_path=False)) + save_button.clicked.connect(lambda: self.save_results(final_params, export_specific_path=False, reload_to_parameters=True)) layout.addWidget(save_button) result_dialog.setLayout(layout) @@ -455,8 +457,7 @@ def save_results(self, final_params, reload_to_parameters = False,export_specifi # Save the results to a file with open(path, 'w') as file: json.dump(input_parameters_copy, file, indent=4) - if reload_to_parameters: - self.reload_on_gui() + self.reload_on_gui(input_parameters_copy) except FileNotFoundError: QMessageBox.warning(self, "Invalid File", "Please enter a valid file name.") @@ -465,15 +466,17 @@ def save_results(self, final_params, reload_to_parameters = False,export_specifi QMessageBox.critical(self, "Error", f"An error occurred while saving the results: {e}") - def reload_on_gui(self): + def reload_on_gui(self, data): """ Reload the results to the input parameters. :return: """ # Update the input parameters - self.gui.import_parameters_from_json(path=self.saved_path, need_filename=False) + print("Updating input parameters from:", self.saved_path) + self.gui.import_parameters_from_json(path=self.saved_path, need_filename=False, data=data) + print("Called function import_parameters_from_json with path:", self.saved_path, "and need_filename:", False) self.gui.tabs.setCurrentIndex(0) - print("saving json") + def on_message_box_clicked(self, button): """Handle the message box button clicked event.""" if button.text() == "&Yes": From 57463c769e6a2bd5d6d19ca01291e555fa7df425 Mon Sep 17 00:00:00 2001 From: mroncera Date: Thu, 13 Jun 2024 17:15:13 +0200 Subject: [PATCH 14/16] REFACTOR - Flag the NEMI optimisation to "WIP", remove spice tab from gui --- src/view/gui.py | 2 +- src/view/optimisation_tab.py | 13 +++---------- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/src/view/gui.py b/src/view/gui.py index 100b700..dbb08e7 100644 --- a/src/view/gui.py +++ b/src/view/gui.py @@ -870,7 +870,7 @@ def init_ui(self): self.tabs.addTab(self.param_tab, "Parameters") self.tabs.addTab(self.strategy_tab, "Strategy Selection") - self.tabs.addTab(self.spice_tab, "Spice Simulation") + #self.tabs.addTab(self.spice_tab, "Spice Simulation") self.tabs.addTab(self.optimisation_tab, "Optimisation") self.tabs.addTab(self.EMC_tab, "EMC") diff --git a/src/view/optimisation_tab.py b/src/view/optimisation_tab.py index 58b189b..fc26c91 100644 --- a/src/view/optimisation_tab.py +++ b/src/view/optimisation_tab.py @@ -67,7 +67,7 @@ def setup_ui(self): self.target_combobox = QComboBox() self.target_combobox.addItem("Impedance") - self.target_combobox.addItem("NEMI") + self.target_combobox.addItem("NEMI(WIP)") self.target_combobox.currentIndexChanged.connect(self.update_target) self.target_layout.addWidget(self.target_combobox) @@ -149,7 +149,7 @@ def update_target(self): Update the target input based on the selected target. :return: """ - if self.target_combobox.currentText() == "NEMI": + if self.target_combobox.currentText() == "NEMI(WIP)": self.target_value_input.setVisible(False) self.nemi_table.setVisible(True) else: @@ -208,13 +208,6 @@ def validate_nemi_table(self): item.setBackground(QColor(255, 0, 0)) # Set to red for invalid input is_valid = False - if weight_sum != 1: - print("Weight sum is not equal to 1") - is_valid = False - for col in range(self.nemi_table.columnCount()): - item = self.nemi_table.item(2, col) - if item: - item.setBackground(QColor(255, 0, 0)) # Highlight the weight row if sum is not 1 finally: self.nemi_table.blockSignals(False) # Unblock signals @@ -223,7 +216,7 @@ def validate_nemi_table(self): def on_optimise_clicked(self): """Popup message box to confirm the optimisation.""" try: - if self.target_combobox.currentText() == "NEMI": + if self.target_combobox.currentText() == "NEMI(WIP)": if not self.validate_nemi_table(): QMessageBox.warning(self, "Invalid Input", "Please correct the invalid inputs in the NEMI table.") return From fc1441d436da948b32c1cfd1da1d0beecd4134fb Mon Sep 17 00:00:00 2001 From: mroncera Date: Fri, 14 Jun 2024 12:03:50 +0200 Subject: [PATCH 15/16] FIX - minor path fixes --- environment.yml | 1 + src/model/optimisation/genetic_optimisation.py | 2 +- src/view/gui.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/environment.yml b/environment.yml index 2609bde..2fac0b3 100644 --- a/environment.yml +++ b/environment.yml @@ -25,3 +25,4 @@ dependencies: - pyvis==0.3.2 - seaborn==0.13.2 - sphinx_rtd_theme==2.0.0 + - deap==1.4.1 diff --git a/src/model/optimisation/genetic_optimisation.py b/src/model/optimisation/genetic_optimisation.py index b8036fa..53e53eb 100644 --- a/src/model/optimisation/genetic_optimisation.py +++ b/src/model/optimisation/genetic_optimisation.py @@ -4,7 +4,7 @@ from PyQt6.QtCore import pyqtSignal, QThread from deap import creator, base, tools, algorithms -from model.optimisation.impedance_strategy_map import IMPEDANCE_STRATEGY_MAP +from src.model.optimisation.impedance_strategy_map import IMPEDANCE_STRATEGY_MAP from src.controler.controller import CalculationController parameters_dict = { diff --git a/src/view/gui.py b/src/view/gui.py index dbb08e7..3fb86f9 100644 --- a/src/view/gui.py +++ b/src/view/gui.py @@ -32,7 +32,7 @@ from src.controler.controller import CalculationController, STRATEGY_MAP from src.model.visualisation.create_tree import create_tree, add_title_description -from view.optimisation_tab import OptimisationTab +from src.view.optimisation_tab import OptimisationTab ureg: UnitRegistry = UnitRegistry() From 638cf86b77f391764631cf071d2b3af698ea2804 Mon Sep 17 00:00:00 2001 From: mroncera Date: Fri, 14 Jun 2024 12:05:59 +0200 Subject: [PATCH 16/16] FIX - env name changes --- environment.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/environment.yml b/environment.yml index 2fac0b3..af8df23 100644 --- a/environment.yml +++ b/environment.yml @@ -1,4 +1,4 @@ -name: PLASMAG_22 +name: PLASMAG channels: - conda-forge - defaults