From acd420fa9b6a5b683548c3309fba9a4bd2a7c513 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Fri, 27 Mar 2026 17:10:28 +0000 Subject: [PATCH 01/40] Add dtocean-economics Already done: + Converted to Python 3 + Converted to Poetry + Running tests from 3.12 to 3.14 --- .../dtocean-economics/.vscode/settings.json | 11 + packages/dtocean-economics/CHANGELOG.md | 29 + packages/dtocean-economics/LICENSE.txt | 674 ++++++++++++++++++ .../dtocean_economics/__init__.py | 0 packages/dtocean-economics/pyproject.toml | 85 ++- .../src/dtocean_economics/__init__.py | 21 + .../src/dtocean_economics/functions.py | 111 +++ .../src/dtocean_economics/main.py | 118 +++ .../src/dtocean_economics/preprocessing.py | 105 +++ packages/dtocean-economics/tests/__init__.py | 0 packages/dtocean-economics/tests/conftest.py | 49 ++ .../dtocean-economics/tests/test_functions.py | 98 +++ packages/dtocean-economics/tests/test_main.py | 56 ++ .../tests/test_preprocessing.py | 106 +++ poetry.lock | 31 +- pyproject.toml | 3 + 16 files changed, 1488 insertions(+), 9 deletions(-) create mode 100644 packages/dtocean-economics/.vscode/settings.json create mode 100644 packages/dtocean-economics/CHANGELOG.md create mode 100644 packages/dtocean-economics/LICENSE.txt delete mode 100644 packages/dtocean-economics/dtocean_economics/__init__.py create mode 100644 packages/dtocean-economics/src/dtocean_economics/__init__.py create mode 100644 packages/dtocean-economics/src/dtocean_economics/functions.py create mode 100644 packages/dtocean-economics/src/dtocean_economics/main.py create mode 100644 packages/dtocean-economics/src/dtocean_economics/preprocessing.py delete mode 100644 packages/dtocean-economics/tests/__init__.py create mode 100644 packages/dtocean-economics/tests/conftest.py create mode 100644 packages/dtocean-economics/tests/test_functions.py create mode 100644 packages/dtocean-economics/tests/test_main.py create mode 100644 packages/dtocean-economics/tests/test_preprocessing.py diff --git a/packages/dtocean-economics/.vscode/settings.json b/packages/dtocean-economics/.vscode/settings.json new file mode 100644 index 00000000..868f6c4f --- /dev/null +++ b/packages/dtocean-economics/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "[python]": { + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll": "explicit", + "source.organizeImports": "explicit" + }, + "editor.defaultFormatter": "charliermarsh.ruff" + }, + "ruff.configuration": "pyproject.toml", +} diff --git a/packages/dtocean-economics/CHANGELOG.md b/packages/dtocean-economics/CHANGELOG.md new file mode 100644 index 00000000..6c852b59 --- /dev/null +++ b/packages/dtocean-economics/CHANGELOG.md @@ -0,0 +1,29 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [2.0.0] - 2019-03-07 + +### Added + +- Added main function which takes three dataframes, one for CAPEX, OPEX, and + energy plus the discount rate and returns a dictionary of results. +- Added a preprocessing module which provides functions for preparing the + required dataframes and for calculating estimates to the inputs. + +### Changed + +- Reorganised the functions module to undertake all dataframe manipulation + work. The main function just collects any valid results. +- Now considers multiple series for energy and OPEX, as per changes in + the dtocean-maintenance module. Returns summed, discounted values and LCOE + calculations for each series. + +## [1.0.0] - 2017-01-05 + +### Added + +- Initial import of dtocean-economics from SETIS. diff --git a/packages/dtocean-economics/LICENSE.txt b/packages/dtocean-economics/LICENSE.txt new file mode 100644 index 00000000..9cecc1d4 --- /dev/null +++ b/packages/dtocean-economics/LICENSE.txt @@ -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. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + 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: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/packages/dtocean-economics/dtocean_economics/__init__.py b/packages/dtocean-economics/dtocean_economics/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index ecee6b62..c3dd9fb8 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -2,11 +2,92 @@ name = "dtocean-economics" version = "2.0.0" description = "Economic assessment module for the DTOcean tools" -authors = ["Mathew Topper "] +authors = ["The DTOcean Developers"] +maintainers = ["Mathew Topper "] +license = "GPL-3.0-or-later" readme = "README.md" +repository = "https://github.com/DTOcean/dtocean" +homepage = "https://dtocean.github.io/dtocean" +classifiers = [ + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX :: Linux", +] + +[tool.poetry.urls] +"Bug Tracker" = "https://github.com/DTOcean/dtocean/issues" [tool.poetry.dependencies] -python = "^3.13" +python = ">=3.12,<3.15" + +[tool.poetry.group.main] +include-groups = ["dtocean-economics"] + +[tool.poetry.group.dtocean-economics.dependencies] +pandas = "^3.0.1" + +[tool.poetry.group.test] +optional = true + +[tool.poetry.group.test.dependencies] +pytest = "^8.3.4" +pytest-cov = "^6.0.0" + +[tool.poetry.group.audit] +optional = true + +[tool.poetry.group.audit.dependencies] +pyright = "^1.1.390" +ruff = "^0.8.3" + +[tool.poetry.group.tox] +optional = true + +[tool.poetry.group.tox.dependencies] +tox = "<4.47" +tox-uv = "<1.33.0" + +[tool.poetry-monoranger-plugin] +enabled = true +monorepo-root = "../../" +version-pinning-rule = '^' + +[tool.pyright] +typeCheckingMode = "basic" + +[tool.ruff] +line-length = 80 + +[tool.tox] +requires = ["tox>=4.19"] +env_list = ["3.14", "3.13", "3.12", "audit"] + +[tool.tox.env_run_base] +description = "Run test under {base_python}" +skip_install = true +allowlist_externals = ["poetry"] +commands_pre = [ + ["poetry", "sync", "--only", "dtocean-economics", "--only", "test"] +] +commands = [ + ["poetry", "run", "pytest", "tests"] +] + +[tool.tox.env.audit] +description = "Run audit check on code base" +skip_install = true +allowlist_externals = ["poetry"] +commands_pre = [ + ["poetry", "sync", "--only", "dtocean-economics", "--only", "audit"] +] +commands = [ + ["poetry", "run", "ruff", "check"], + ["poetry", "run", "pyright", "src"] +] [build-system] requires = ["poetry-core"] diff --git a/packages/dtocean-economics/src/dtocean_economics/__init__.py b/packages/dtocean-economics/src/dtocean_economics/__init__.py new file mode 100644 index 00000000..34e004e5 --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/__init__.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2016 Marta Silva, Mathew Topper +# Copyright (C) 2017-2026 Mathew Topper +# +# 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 . + +from .main import main + +__all__ = ["main"] diff --git a/packages/dtocean-economics/src/dtocean_economics/functions.py b/packages/dtocean-economics/src/dtocean_economics/functions.py new file mode 100644 index 00000000..eb32fe6f --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/functions.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2016 Marta Silva, Mathew Topper +# Copyright (C) 2017-2026 Mathew Topper +# +# 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 . + +""" +Created on Thu Mar 05 16:16:39 2015 + +Functions to be used within DTOcean tool + +.. moduleauthor:: Marta Silva +.. moduleauthor:: Mathew Topper +""" + +import pandas as pd + + +def get_combined_lcoe(lcoe_capex=None, lcoe_opex=None): + if lcoe_capex is not None and lcoe_opex is not None: + lcoe = lcoe_capex + lcoe_opex + elif lcoe_capex is not None: + lcoe = lcoe_capex + else: + lcoe = lcoe_opex + + return lcoe + + +def costs_from_bom(bom): + costs = bom["quantity"] * bom["unitary_cost"] + + costs_dict = {"project_year": bom["project_year"].values, "costs": costs} + costs_df = pd.DataFrame(costs_dict) + + return costs_df + + +def get_discounted_values(values_df: pd.DataFrame, discount_rate): + years = values_df["project_year"] + values_df = values_df.set_index("project_year") + + discounted_values = [] + + for _, value_series in values_df.items(): + present_values = get_present_values(value_series, years, discount_rate) + + discounted_value = present_values.sum() + discounted_values.append(discounted_value) + + return pd.Series(discounted_values) + + +def get_lcoe(discounted_cost, discounted_energy): + lcoe = discounted_cost.astype(float) / discounted_energy + + return lcoe + + +def get_phase_breakdown(bom): + # Check for null phases + null_phases = pd.isnull(bom["phase"]) + + # No breakdown available + if null_phases.all(): + return None + + # Replace any null phase values + bom.loc[pd.isnull(bom["phase"]), "phase"] = "Other" + + phase_groups = bom.groupby("phase") + + phase_breakdown = {} + + for phase_name, phase_bom in phase_groups: + phase_cost = get_total_cost(phase_bom) + phase_breakdown[phase_name] = phase_cost + + return phase_breakdown + + +def get_present_values(value, yr, dr): + """ + Function to calculate present value + It should be applied to a table with costs and year cost occurs, and to + energy output table + Costs could be calculated with the above function. + It can be applied in an item by item basis, or on the sum by year + """ + + present_value = value / ((1 + dr) ** yr) + + return present_value + + +def get_total_cost(bom): + result = (bom["unitary_cost"] * bom["quantity"]).sum() + + return result diff --git a/packages/dtocean-economics/src/dtocean_economics/main.py b/packages/dtocean-economics/src/dtocean_economics/main.py new file mode 100644 index 00000000..540ec7f3 --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/main.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2016 Marta Silva, Mathew Topper +# Copyright (C) 2017-2026 Mathew Topper +# +# 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 . + +""" +Created on Tue Mar 17 16:06:59 2015 + +Main economic analysis used within DTOcean tool + +.. moduleauthor:: Marta Silva +.. moduleauthor:: Mathew Topper +""" + +from typing import Any, Optional + +from .functions import ( + costs_from_bom, + get_combined_lcoe, + get_discounted_values, + get_lcoe, + get_phase_breakdown, + get_total_cost, +) + + +def main(capex, opex, energy, discount_rate=None): + # Note, nominal units of energy and costs are kWs and Euro + # Year 0 represents costs prior to beginning of operations + if discount_rate is None: + discount_rate = 0.0 + + # Define the results dictionary + result: dict[str, Optional[Any]] = { + "CAPEX": None, + "Discounted CAPEX": None, + "CAPEX breakdown": None, + "OPEX": None, + "Discounted OPEX": None, + "Energy": None, + "Discounted Energy": None, + "LCOE CAPEX": None, + "LCOE OPEX": None, + "LCOE": None, + } + + ### COSTS + + # CAPEX + if not capex.empty: + breakdown = get_phase_breakdown(capex) + total = get_total_cost(capex) + + costs_df = costs_from_bom(capex) + discounted = get_discounted_values(costs_df, discount_rate) + + if breakdown is not None: + result["CAPEX breakdown"] = breakdown + + result["CAPEX"] = total + result["Discounted CAPEX"] = discounted.iloc[0] + + # OPEX + if not opex.empty: + opex_by_year = opex.set_index("project_year") + total = opex_by_year.sum() + discounted = get_discounted_values(opex, discount_rate) + + result["OPEX"] = total + result["Discounted OPEX"] = discounted + + ### ENERGY + + # Can exit if no energy records are provided + if energy.empty: + return result + + energy_by_year = energy.set_index("project_year") + total = energy_by_year.sum() + discounted = get_discounted_values(energy, discount_rate) + + result["Energy"] = total + result["Discounted Energy"] = discounted + + ### LCOE + + if result["Discounted CAPEX"] is not None: + lcoe = get_lcoe(result["Discounted CAPEX"], result["Discounted Energy"]) + + result["LCOE CAPEX"] = lcoe + + if result["Discounted OPEX"] is not None: + lcoe = get_lcoe(result["Discounted OPEX"], result["Discounted Energy"]) + + result["LCOE OPEX"] = lcoe + + # Can exit if no LCOE values were created + if result["LCOE CAPEX"] is None and result["LCOE OPEX"] is None: + return result + + lcoe = get_combined_lcoe(result["LCOE CAPEX"], result["LCOE OPEX"]) + + result["LCOE"] = lcoe + + return result diff --git a/packages/dtocean-economics/src/dtocean_economics/preprocessing.py b/packages/dtocean-economics/src/dtocean_economics/preprocessing.py new file mode 100644 index 00000000..073e12dc --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/preprocessing.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2016 Marta Silva, Mathew Topper +# Copyright (C) 2017-2026 Mathew Topper +# +# 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 . + +""" +.. moduleauthor:: Marta Silva +.. moduleauthor:: Mathew Topper +""" + +import pandas as pd + + +def estimate_cost_per_power(total_rated_power, unit_cost, phase=None): + cost = total_rated_power * unit_cost + cost_bom = make_phase_bom([1], [cost], [0], phase) + + return cost_bom + + +def estimate_energy(lifetime, year_energy, network_efficiency=None): + # Note units of energy are kW + + if network_efficiency is not None: + net_coeff = network_efficiency + else: + net_coeff = 1.0 + + energy_kw = [0] + [year_energy * net_coeff] * lifetime + energy_year = range(lifetime + 1) + + raw_energy = {"energy": energy_kw, "project_year": energy_year} + + energy_record = pd.DataFrame(raw_energy) + + return energy_record + + +def estimate_opex( + lifetime, + total_rated_power=None, + opex_estimate=None, + annual_repair_cost_estimate=None, + annual_array_mttf_estimate=None, +): + # Note, units of mttf is hours + + # Collect opex costs + annual_costs = 0.0 + + if total_rated_power is not None and opex_estimate is not None: + annual_costs += total_rated_power * opex_estimate + + if ( + annual_repair_cost_estimate is not None + and annual_array_mttf_estimate is not None + ): + year_mttf = annual_array_mttf_estimate / 24.0 / 365.25 + failure_cost = annual_repair_cost_estimate / year_mttf + + annual_costs += failure_cost + + opex_unit_cost = [0.0] + [annual_costs] * lifetime + opex_year = range(lifetime + 1) + + raw_costs = {"costs": opex_unit_cost, "project_year": opex_year} + + opex_bom = pd.DataFrame(raw_costs) + + return opex_bom + + +def make_phase_bom(quantities, costs, years, phase=None): + if not (len(quantities) == len(costs) == len(years)): + errStr = ( + "Number of quantities, unit costs and project years must be " + "equal" + ) + raise ValueError(errStr) + + phase_years = [phase] * len(years) + + raw_costs = { + "phase": phase_years, + "quantity": quantities, + "unitary_cost": costs, + "project_year": years, + } + + phase_bom = pd.DataFrame(raw_costs) + + return phase_bom diff --git a/packages/dtocean-economics/tests/__init__.py b/packages/dtocean-economics/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/packages/dtocean-economics/tests/conftest.py b/packages/dtocean-economics/tests/conftest.py new file mode 100644 index 00000000..d7a309fc --- /dev/null +++ b/packages/dtocean-economics/tests/conftest.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Aug 08 12:36:48 2017 + +@author: mtopper +""" + +import pytest +import pandas as pd + + +@pytest.fixture(scope="module") +def bom(): + + bom_dict = {'phase': [None, None, None, "Test", "Test", "Test"], + 'unitary_cost': [0.0, 100000.0, 100000.0, 1, 1, 1], + 'project_year': [0, 1, 2, 0, 1, 2], + 'quantity': [1, 1, 1, 1, 10, 20] + } + + bom_df = pd.DataFrame(bom_dict) + + return bom_df + + +@pytest.fixture(scope="module") +def energy_record(): + + energy_dict = {'project_year': [0, 1, 2, 3, 4, 5], + 'energy 0': [0, 1, 2, 0, 10, 20], + 'energy 1': [0, 1, 32, 0, 0, 20] + } + + energy_df = pd.DataFrame(energy_dict) + + return energy_df + + +@pytest.fixture(scope="module") +def opex_costs(): + + opex_dict = {'project_year': [0, 1, 2, 3, 4, 5], + 'cost 0': [0.0, 100000.0, 100000.0, 1, 1, 1], + 'cost 1': [0.0, 100000.0, 0, 1, 1, 100000.0] + } + + opex_df = pd.DataFrame(opex_dict) + + return opex_df diff --git a/packages/dtocean-economics/tests/test_functions.py b/packages/dtocean-economics/tests/test_functions.py new file mode 100644 index 00000000..b0f837de --- /dev/null +++ b/packages/dtocean-economics/tests/test_functions.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2017-2026 Mathew Topper +# +# 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 . + +import numpy as np +import pandas as pd +import pytest + +from dtocean_economics.functions import ( + costs_from_bom, + get_combined_lcoe, + get_discounted_values, + get_lcoe, + get_phase_breakdown, + get_present_values, +) + + +@pytest.mark.parametrize( + "capex, opex, expected", + [ + (1, None, 1), + (None, 1, 1), + (1, 1, 2), + ], +) +def test_get_combined_lcoe_capex(capex, opex, expected): + result = get_combined_lcoe(capex, opex) + + assert result == expected + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (0.0, 200031), + (0.1, 173580.34), + (0.2, 152801), + ], +) +def test_get_discounted_values(bom, test_input, expected): + costs_df = costs_from_bom(bom) + result = get_discounted_values(costs_df, test_input) + + assert np.isclose(result.iloc[0], expected) + + +def test_get_lcoe(): + result = get_lcoe(np.array([1]), np.array([10])) + + assert np.isclose(result[0], 0.1) + + +def test_get_phase_breakdown(bom): + result = get_phase_breakdown(bom) + + assert result is not None + assert set(result.keys()) == set(["Test", "Other"]) + assert result["Test"] == 31.0 + assert result["Other"] == 200000.0 + + +def test_get_phase_breakdown_none(bom): + none_bom = bom[pd.isnull(bom["phase"])] + + result = get_phase_breakdown(none_bom) + + assert result is None + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (0.0, [0, 10, 20]), + (0.1, [0, 9.0909, 16.5289]), + (0.2, [0, 8.3333, 13.8888]), + ], +) +def test_get_present_values(test_input, expected): + value = np.array([0, 10, 20]) + year = np.array([0, 1, 2]) + + result = get_present_values(value, year, test_input) + + assert np.isclose(result, expected).all() diff --git a/packages/dtocean-economics/tests/test_main.py b/packages/dtocean-economics/tests/test_main.py new file mode 100644 index 00000000..01f530b4 --- /dev/null +++ b/packages/dtocean-economics/tests/test_main.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2017-2026 Mathew Topper +# +# 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 . + +from dtocean_economics import main + + +def test_main(bom, opex_costs, energy_record): + result = main(bom, opex_costs, energy_record) + + for value in result.values(): + assert value is not None + + +def test_main_no_capex(bom, opex_costs, energy_record): + capex_empty = bom.drop(bom.index) + result = main(capex_empty, opex_costs, energy_record) + + assert result["CAPEX breakdown"] is None + assert result["CAPEX"] is None + assert result["Discounted CAPEX"] is None + assert result["LCOE CAPEX"] is None + + +def test_main_no_opex(bom, energy_record): + opex_empty = bom.drop(bom.index) + + result = main(bom, opex_empty, energy_record) + + assert result["OPEX"] is None + assert result["Discounted OPEX"] is None + assert result["LCOE OPEX"] is None + + +def test_main_no_energy(bom, opex_costs, energy_record): + energy_empty = energy_record.drop(energy_record.index) + result = main(bom, opex_costs, energy_empty) + + assert result["Energy"] is None + assert result["Discounted Energy"] is None + assert result["LCOE CAPEX"] is None + assert result["LCOE OPEX"] is None + assert result["LCOE"] is None diff --git a/packages/dtocean-economics/tests/test_preprocessing.py b/packages/dtocean-economics/tests/test_preprocessing.py new file mode 100644 index 00000000..d3e8327c --- /dev/null +++ b/packages/dtocean-economics/tests/test_preprocessing.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2017-2026 Mathew Topper +# +# 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 . + +import numpy as np +import pandas as pd +import pytest + +from dtocean_economics.preprocessing import ( + estimate_cost_per_power, + estimate_energy, + estimate_opex, + make_phase_bom, +) + + +def test_estimate_cost_per_power(): + df = estimate_cost_per_power(100, 1e6) + series = df.iloc[0] + + assert len(df) == 1 + assert series["phase"] is None + assert series["project_year"] == 0 + assert series["quantity"] == 1 + assert series["unitary_cost"] == 100 * 1e6 + + +def test_estimate_cost_per_power_phase(): + df = estimate_cost_per_power(100, 1e6, "Devices") + series = df.iloc[0] + + assert len(df) == 1 + assert series["phase"] == "Devices" + + +def test_estimate_energy(): + df = estimate_energy(2, 1e6, 0.95) + year_one = df.loc[df["project_year"] == 0] + other_years = df.loc[df["project_year"] != 0] + + assert (year_one["energy"] == 0.0).all() + assert (other_years["energy"] == 0.95 * 1e6).all() + + +def test_estimate_opex_rated_power(): + df = estimate_opex(2, 100, 1e3) + year_one = df.loc[df["project_year"] == 0] + other_years = df.loc[df["project_year"] != 0] + + assert (year_one["costs"] == 0.0).all() + assert (other_years["costs"] == 100 * 1e3).all() + + +def test_estimate_opex_mttf(): + df = estimate_opex( + 2, annual_repair_cost_estimate=1e3, annual_array_mttf_estimate=8766 + ) + + year_one = df.loc[df["project_year"] == 0] + other_years = df.loc[df["project_year"] != 0] + + assert (year_one["costs"] == 0.0).all() + assert (other_years["costs"] == 1e3).all() + + +def test_estimate_opex_combined(): + df = estimate_opex(2, 100, 1e3, 1e3, 8766) + + year_one = df.loc[df["project_year"] == 0] + other_years = df.loc[df["project_year"] != 0] + + assert (year_one["costs"] == 0.0).all() + assert (other_years["costs"] == 100 * 1e3 + 1e3).all() + + +def test_make_phase_bom(): + df = make_phase_bom([0, 1, 2], [10, 20, 30], [0, 1, 2]) + + assert (pd.isnull(df["phase"])).all() + assert np.isclose(df["quantity"], [0, 1, 2]).all() + assert np.isclose(df["unitary_cost"], [10, 20, 30]).all() + assert np.isclose(df["project_year"], [0, 1, 2]).all() + + +def test_make_phase_bom_phase(): + df = make_phase_bom([0, 1, 2], [10, 20, 30], [0, 1, 2], "Test") + + assert (df["phase"] == "Test").all() + + +def test_make_phase_bom_phase_fail(): + with pytest.raises(ValueError): + make_phase_bom([0, 1, 2], [10, 20, 30], [0, 1]) diff --git a/poetry.lock b/poetry.lock index c8fdd1f9..a2ce882a 100644 --- a/poetry.lock +++ b/poetry.lock @@ -868,6 +868,23 @@ xlwt = "^1.3.0" type = "directory" url = "packages/dtocean-dummy-module" +[[package]] +name = "dtocean-economics" +version = "2.0.0" +description = "Economic assessment module for the DTOcean tools" +optional = false +python-versions = ">=3.12,<3.15" +groups = ["dtocean-economics"] +files = [] +develop = true + +[package.dependencies] +pandas = "^3.0.1" + +[package.source] +type = "directory" +url = "packages/dtocean-economics" + [[package]] name = "dtocean-hydrodynamics" version = "4.0.3" @@ -1766,7 +1783,7 @@ version = "2.3.5" description = "Fundamental package for array computing in Python" optional = false python-versions = ">=3.11" -groups = ["audit", "dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] +groups = ["audit", "dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-economics", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] files = [ {file = "numpy-2.3.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:de5672f4a7b200c15a4127042170a694d4df43c992948f5e1af57f0174beed10"}, {file = "numpy-2.3.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:acfd89508504a19ed06ef963ad544ec6664518c863436306153e13e94605c218"}, @@ -1880,7 +1897,7 @@ version = "3.0.1" description = "Powerful data structures for data analysis, time series, and statistics" optional = false python-versions = ">=3.11" -groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] +groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-economics", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] files = [ {file = "pandas-3.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:de09668c1bf3b925c07e5762291602f0d789eca1b3a781f99c1c78f6cac0e7ea"}, {file = "pandas-3.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:24ba315ba3d6e5806063ac6eb717504e499ce30bd8c236d8693a5fd3f084c796"}, @@ -2846,7 +2863,7 @@ version = "2.9.0.post0" description = "Extensions to the standard Python datetime module" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" -groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] +groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-economics", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] files = [ {file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"}, {file = "python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427"}, @@ -3528,7 +3545,7 @@ version = "1.17.0" description = "Python 2 and 3 compatibility utilities" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" -groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] +groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-economics", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine"] files = [ {file = "six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274"}, {file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"}, @@ -4005,12 +4022,12 @@ version = "2025.3" description = "Provider of IANA time zone data" optional = false python-versions = ">=2" -groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine", "test-postgresql"] +groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-dummy-module", "dtocean-economics", "dtocean-hydrodynamics", "dtocean-qt", "mdo-engine", "test-postgresql"] files = [ {file = "tzdata-2025.3-py2.py3-none-any.whl", hash = "sha256:06a47e5700f3081aab02b2e513160914ff0694bce9947d6b76ebd6bf57cfc5d1"}, {file = "tzdata-2025.3.tar.gz", hash = "sha256:de39c2ca5dc7b0344f2eba86f49d614019d29f060fc4ebc8a417896a620b56a7"}, ] -markers = {dtocean = "python_version < \"3.14\" and (sys_platform == \"win32\" or sys_platform == \"emscripten\")", dtocean-app = "python_version < \"3.14\" and (sys_platform == \"win32\" or sys_platform == \"emscripten\")", dtocean-core = "python_version < \"3.14\" and (sys_platform == \"win32\" or sys_platform == \"emscripten\")", dtocean-dummy-module = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", dtocean-hydrodynamics = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", dtocean-qt = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", mdo-engine = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", test-postgresql = "sys_platform == \"win32\""} +markers = {dtocean = "python_version < \"3.14\" and (sys_platform == \"win32\" or sys_platform == \"emscripten\")", dtocean-app = "python_version < \"3.14\" and (sys_platform == \"win32\" or sys_platform == \"emscripten\")", dtocean-core = "python_version < \"3.14\" and (sys_platform == \"win32\" or sys_platform == \"emscripten\")", dtocean-dummy-module = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", dtocean-economics = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", dtocean-hydrodynamics = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", dtocean-qt = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", mdo-engine = "sys_platform == \"win32\" or sys_platform == \"emscripten\"", test-postgresql = "sys_platform == \"win32\""} [[package]] name = "urllib3" @@ -4450,4 +4467,4 @@ markers = {dtocean = "python_version < \"3.14\"", dtocean-app = "python_version [metadata] lock-version = "2.1" python-versions = ">=3.12,<3.15" -content-hash = "fda0c883fbb490198782624a5ee5103387cf0e536655e520f6ab0e2e0fc63a48" +content-hash = "4dea8b4bdacf67a0772a751e2e8c9421af37ac3df02bba29f2a0577a4ea050f2" diff --git a/pyproject.toml b/pyproject.toml index 9be7d60f..0b606433 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,9 @@ dtocean-docs = { path = "packages/dtocean-docs", develop = true } [tool.poetry.group.dtocean-dummy-module.dependencies] dtocean-dummy-module = { path = "packages/dtocean-dummy-module", develop = true } +[tool.poetry.group.dtocean-economics.dependencies] +dtocean-economics = { path = "packages/dtocean-economics", develop = true } + [tool.poetry.group.dtocean-hydrodynamics.dependencies] dtocean-hydrodynamics = { path = "packages/dtocean-hydrodynamics", develop = true } From 5d6d5e0455ada8d968cea72239093c4d3b255125 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Sat, 28 Mar 2026 16:37:48 +0000 Subject: [PATCH 02/40] Start moving interface code and tests --- packages/dtocean-core/pyproject.toml | 1 - .../dtocean-economics/.vscode/settings.json | 3 + packages/dtocean-economics/pyproject.toml | 65 +- .../src/dtocean_economics/stats.py | 281 +++++++ .../src/dtocean_plugins/themes/economics.py | 748 ++++++++++++++++++ .../tests/{ => dtocean_economics}/conftest.py | 0 .../{ => dtocean_economics}/test_functions.py | 2 +- .../{ => dtocean_economics}/test_main.py | 0 .../test_preprocessing.py | 0 .../tests/dtocean_economics/test_stats.py | 389 +++++++++ .../tests/dtocean_plugins/themes/conftest.py | 3 + .../themes/test_themes_economics.py | 186 +++++ poetry.lock | 6 +- 13 files changed, 1665 insertions(+), 19 deletions(-) create mode 100644 packages/dtocean-economics/src/dtocean_economics/stats.py create mode 100644 packages/dtocean-economics/src/dtocean_plugins/themes/economics.py rename packages/dtocean-economics/tests/{ => dtocean_economics}/conftest.py (100%) rename packages/dtocean-economics/tests/{ => dtocean_economics}/test_functions.py (98%) rename packages/dtocean-economics/tests/{ => dtocean_economics}/test_main.py (100%) rename packages/dtocean-economics/tests/{ => dtocean_economics}/test_preprocessing.py (100%) create mode 100644 packages/dtocean-economics/tests/dtocean_economics/test_stats.py create mode 100644 packages/dtocean-economics/tests/dtocean_plugins/themes/conftest.py create mode 100644 packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py diff --git a/packages/dtocean-core/pyproject.toml b/packages/dtocean-core/pyproject.toml index fd2f4763..42654b51 100644 --- a/packages/dtocean-core/pyproject.toml +++ b/packages/dtocean-core/pyproject.toml @@ -52,7 +52,6 @@ python-dateutil = "^2.9.0.post0" pyyaml = "^6.0.2" ruamel-yaml-clib = "^0.2.12" ruamel-yaml = "^0.19.1" -scipy = "^1.17.0" shapely = "^2.0.6" utm = "^0.8.1" xarray = "~2026.2.0" diff --git a/packages/dtocean-economics/.vscode/settings.json b/packages/dtocean-economics/.vscode/settings.json index 868f6c4f..8820374f 100644 --- a/packages/dtocean-economics/.vscode/settings.json +++ b/packages/dtocean-economics/.vscode/settings.json @@ -7,5 +7,8 @@ }, "editor.defaultFormatter": "charliermarsh.ruff" }, + "[toml]": { + "editor.formatOnSave": true, + }, "ruff.configuration": "pyproject.toml", } diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index c3dd9fb8..cf57f7ee 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -9,13 +9,13 @@ readme = "README.md" repository = "https://github.com/DTOcean/dtocean" homepage = "https://dtocean.github.io/dtocean" classifiers = [ - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.14", - "Programming Language :: Python :: 3.13", - "Programming Language :: Python :: 3.12", - "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", - "Operating System :: Microsoft :: Windows", - "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX :: Linux", ] [tool.poetry.urls] @@ -29,6 +29,7 @@ include-groups = ["dtocean-economics"] [tool.poetry.group.dtocean-economics.dependencies] pandas = "^3.0.1" +scipy = "^1.17.0" [tool.poetry.group.test] optional = true @@ -37,6 +38,16 @@ optional = true pytest = "^8.3.4" pytest-cov = "^6.0.0" +[tool.poetry.group.dtocean-core] +optional = true + +[tool.poetry.group.dtocean-core.dependencies] +dtocean-core = { path = "../dtocean-core", develop = true } + +[tool.poetry.group.test-extras] +optional = true +include-groups = ["dtocean-core"] + [tool.poetry.group.audit] optional = true @@ -71,22 +82,48 @@ description = "Run test under {base_python}" skip_install = true allowlist_externals = ["poetry"] commands_pre = [ - ["poetry", "sync", "--only", "dtocean-economics", "--only", "test"] -] -commands = [ - ["poetry", "run", "pytest", "tests"] + [ + "poetry", + "sync", + "--only", + "dtocean-core", + "--only", + "dtocean-economics", + "--only", + "test", + ], ] +commands = [["poetry", "run", "pytest", "tests"]] [tool.tox.env.audit] description = "Run audit check on code base" skip_install = true allowlist_externals = ["poetry"] commands_pre = [ - ["poetry", "sync", "--only", "dtocean-economics", "--only", "audit"] + [ + "poetry", + "sync", + "--only", + "dtocean-core", + "--only", + "dtocean-economics", + "--only", + "audit", + ], ] commands = [ - ["poetry", "run", "ruff", "check"], - ["poetry", "run", "pyright", "src"] + [ + "poetry", + "run", + "ruff", + "check", + ], + [ + "poetry", + "run", + "pyright", + "src", + ], ] [build-system] diff --git a/packages/dtocean-economics/src/dtocean_economics/stats.py b/packages/dtocean-economics/src/dtocean_economics/stats.py new file mode 100644 index 00000000..0e9c476f --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/stats.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2020 National Technology & Engineering Solutions of Sandia +# Copyright (C) 2017-2024 Mathew Topper +# +# 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 . + +""" +Created on Mon Sep 11 08:49:07 2017 + +.. moduleauthor:: Mathew Topper +""" + +import logging +from typing import TypeAlias, cast + +import numpy as np +import numpy.typing as npt +from contourpy import LineType, contour_generator +from scipy import optimize, stats +from scipy.special import gamma + +PointArray: TypeAlias = npt.NDArray[np.float64] + +# Set up logging +module_logger = logging.getLogger(__name__) + + +class UniVariateKDE: + def __init__(self, data, bandwidth=0.3): + self._kde = stats.gaussian_kde(data, bw_method=bandwidth) + self._cdf = None + self._ppf = None + self._x0 = 0.0 + + def pdf(self, values): + return self._kde(values) + + def cdf(self, values): + if self._cdf is None: + self._cdf = self._calc_cdf() + + return self._cdf(values) + + def ppf(self, probabilities, x0=None): + if self._ppf is None or self._x0 != x0: + self._ppf = self._calc_ppf(x0) + self._x0 = x0 + + result = self._ppf(probabilities) + + if np.isnan(result).any(): + result = None + + return result + + def mean(self): + return self._kde.dataset.mean() + + def median(self): + return np.median(self._kde.dataset) + + def mode(self, samples=1000): + """Numerically search for the mode""" + + x = np.linspace( + self._kde.dataset.min(), self._kde.dataset.max(), samples + ) + most_likely = x[np.argsort(self._kde(x))[-1]] + + return most_likely + + def confidence_interval(self, percent, x0=None): + if self._ppf is None: + self._ppf = self._calc_ppf(x0) + + x = percent / 100.0 + bottom = (1 - x) / 2 + top = (1 + x) / 2 + + result = self._ppf([bottom, top]) + + if np.isnan(result).any(): + result = None + + return result + + def _calc_cdf(self): + def _kde_cdf(x): + return self._kde.integrate_box_1d(-np.inf, x) + + kde_cdf = np.vectorize(_kde_cdf) + + return kde_cdf + + def _calc_ppf(self, x0=None): + if self._cdf is None: + self._cdf = self._calc_cdf() + + def _kde_ppf(q): + def f(x, q): + assert self._cdf is not None + return self._cdf(x) - q + + x0_list = [ + self.mean(), + 0.0, + self._kde.dataset.min(), + self._kde.dataset.max(), + ] + + if x0 is not None: + x0_list = [x0] + x0_list + + for x0_local in x0_list: + result = optimize.fsolve( + f, + x0_local, + args=(q,), + full_output=True, + ) + + if result[2] == 1: + return result[0][0] + + return np.nan + + kde_ppf = np.vectorize(_kde_ppf) + + return kde_ppf + + +class BiVariateKDE: + def __init__(self, x, y): + self.x = x + self.y = y + self.kernel = self._set_kernel() + + def _set_kernel(self): + values = np.vstack([self.x, self.y]) + return stats.gaussian_kde(values) + + def mean(self): + return self.x.mean(), self.y.mean() + + def median(self): + return np.median(self.kernel.dataset, 1) + + def mode(self, xtol=0.0001, ftol=0.0001, disp=False): + """Determine the ordinate of the most likely value of the given KDE""" + + median = self.median() + modal_coords = optimize.fmin( + lambda x: -1 * self.kernel(x), + median, + xtol=xtol, + ftol=ftol, + disp=disp, + ) + + return modal_coords + + def pdf(self, x_range=None, y_range=None, npoints=1000): + # Wide estimate on the ranges if not given + if x_range is None: + dx = self.x.max() - self.x.min() + x_range = (self.x.min() - dx, self.x.max() + dx) + + if y_range is None: + dy = self.y.max() - self.y.min() + y_range = (self.y.min() - dy, self.y.max() + dy) + + X, Y = np.mgrid[ + x_range[0] : x_range[1] : (npoints * 1j), + y_range[0] : y_range[1] : (npoints * 1j), + ] + positions = np.vstack([X.ravel(), Y.ravel()]) + + xx = X[:, 0] + yy = Y[0, :] + pdf = np.reshape(self.kernel(positions).T, X.shape) + + return xx, yy, pdf + + +def pdf_confidence_densities(pdf, levels=None): + """Determine the required density values to satisfy a list of confidence + levels in the given pdf""" + + def diff_frac(density, pdf, target_frac, pdf_sum): + density_frac = pdf[pdf >= density].sum() / pdf_sum + return density_frac - target_frac + + if levels is None: + levels = np.array([95.0]) + else: + levels = np.array(levels) + + fracs = levels / 100.0 + pdf_sum = pdf.sum() + densities = [] + + for frac in fracs: + local_pdf = np.copy(pdf) + + try: + density = optimize.brentq( + diff_frac, pdf.min(), pdf.max(), args=(local_pdf, frac, pdf_sum) + ) + + densities.append(density) + except ValueError as e: + module_logger.debug(e, exc_info=True) + + return densities + + +def pdf_contour_coords(xx, yy, pdf, level): + cont_gen = contour_generator(xx, yy, pdf.T, line_type=LineType.Separate) + lines = cast(list[PointArray], cont_gen.lines(level)) + + cx = [] + cy = [] + + for v in lines: + cx.extend(v[:, 0]) + cy.extend(v[:, 1]) + + return cx, cy + + +def get_standard_error(values): + """ + Calculates the standard error of the mean of a given function. + + This function can either be used to reduce the standard error to + a certain level or calculate the standard error given a fixed number + of samples. + + Args: + values + + Returns: the standard error metric vector + """ + + def get_c4(n): + # Correction for unbiased estimate of the standard deviation. + # https://en.wikipedia.org/wiki/Unbiased_estimation_of_standard_deviation + b_bottom = gamma((n - 1) / 2.0) + + if np.isinf(b_bottom): + return np.inf + + a = np.sqrt(2.0 / (n - 1)) + b_top = gamma(n / 2.0) + return a * b_top / b_bottom + + n = len(values) + + if n < 2: + return None + + c4 = get_c4(n) + + if not np.isfinite(c4): + c4 = 1 + + result_error = c4 * np.std(values) / np.sqrt(n) + + return result_error diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py new file mode 100644 index 00000000..4f5d9836 --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -0,0 +1,748 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2016-2026 Mathew Topper +# +# 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 . + +""" +This module contains the package interface to the dtocean economics functions. + +Note: + The function decorators (such as "@classmethod", etc) must not be removed. + +.. module:: economics + :platform: Windows + :synopsis: Aneris interface for dtocean_core package + +.. moduleauthor:: Mathew Topper +""" + +import numpy as np +import pandas as pd + +from dtocean_economics import main +from dtocean_economics.preprocessing import ( + estimate_cost_per_power, + estimate_energy, + estimate_opex, + make_phase_bom, +) +from dtocean_economics.stats import ( + BiVariateKDE, + UniVariateKDE, + pdf_confidence_densities, + pdf_contour_coords, +) +from dtocean_plugins.themes.base import ThemeInterface + + +class EconomicInterface(ThemeInterface): + """Interface to the economics thematic functions.""" + + def __init__(self): + super(EconomicInterface, self).__init__() + + @classmethod + def get_name(cls): + """A class method for the common name of the interface. + + Returns: + str: A unique string + """ + + return "Economics" + + @classmethod + def declare_weight(cls): + return 1 + + @classmethod + def declare_inputs(cls): + """A class method to declare all the variables required as inputs by + this interface. + + Returns: + list: List of inputs identifiers + + Example: + The returned value can be None or a list of identifier strings which + appear in the data descriptions. For example:: + + inputs = ["My:first:variable", + "My:second:variable", + ] + """ + + input_list = [ + "device.system_cost", + "project.lifetime", + "project.discount_rate", + "project.number_of_devices", + "project.electrical_economics_data", + "project.moorings_foundations_economics_data", + "project.installation_economics_data", + "project.capex_oandm", + "project.opex_per_year", + "project.energy_per_year", + "project.electrical_network_efficiency", + "project.externalities_capex", + "project.externalities_opex", + "project.electrical_cost_estimate", + "project.moorings_cost_estimate", + "project.installation_cost_estimate", + "project.opex_estimate", + "project.annual_repair_cost_estimate", + "project.annual_array_mttf_estimate", + "project.electrical_network_efficiency", + "project.annual_energy", + "project.estimate_energy_record", + ] + + return input_list + + @classmethod + def declare_outputs(cls): + """A class method to declare all the output variables provided by + this interface. + + Returns: + list: List of output identifiers + + Example: + The returned value can be None or a list of identifier strings which + appear in the data descriptions. For example:: + + outputs = ["My:first:variable", + "My:third:variable", + ] + """ + + output_list = [ + "project.economics_metrics", + "project.lcoe_mode_opex", + "project.lcoe_mode_energy", + "project.lcoe_mode", + "project.lcoe_interval_lower", + "project.lcoe_interval_upper", + "project.lcoe_mean", + "project.capex_total", + "project.capex_without_externalities", + "project.discounted_capex", + "project.lifetime_opex_mean", + "project.lifetime_opex_mode", + "project.discounted_opex_mode", + "project.discounted_opex_mean", + "project.discounted_opex_interval_lower", + "project.discounted_opex_interval_upper", + "project.lifetime_cost_mean", + "project.lifetime_cost_mode", + "project.discounted_lifetime_cost_mean", + "project.discounted_lifetime_cost_mode", + "project.discounted_energy_mode", + "project.discounted_energy_mean", + "project.discounted_energy_interval_lower", + "project.discounted_energy_interval_upper", + "project.lcoe_breakdown", + "project.capex_lcoe_breakdown", + "project.opex_lcoe_breakdown", + "project.cost_breakdown", + "project.capex_breakdown", + "project.opex_breakdown", + "project.confidence_density", + "project.lcoe_pdf", + ] + + return output_list + + @classmethod + def declare_optional(cls): + """A class method to declare all the variables which should be flagged + as optional. + + Returns: + list: List of optional variable identifiers + + Note: + Currently only inputs marked as optional have any logical effect. + However, this may change in future releases hence the general + approach. + + Example: + The returned value can be None or a list of identifier strings which + appear in the declare_inputs output. For example:: + + optional = ["My:first:variable", + ] + """ + + optional = [ + "device.system_cost", + "project.number_of_devices", + "project.electrical_network_efficiency", + "project.electrical_economics_data", + "project.moorings_foundations_economics_data", + "project.installation_economics_data", + "project.opex_per_year", + "project.energy_per_year", + "project.capex_oandm", + "project.lifetime", + "project.discount_rate", + "project.externalities_capex", + "project.externalities_opex", + "project.electrical_cost_estimate", + "project.moorings_cost_estimate", + "project.installation_cost_estimate", + "project.opex_estimate", + "project.annual_repair_cost_estimate", + "project.annual_array_mttf_estimate", + "project.annual_energy", + "project.estimate_energy_record", + ] + + return optional + + @classmethod + def declare_id_map(cls): + """Declare the mapping for variable identifiers in the data description + to local names for use in the interface. This helps isolate changes in + the data description or interface from effecting the other. + + Returns: + dict: Mapping of local to data description variable identifiers + + Example: + The returned value must be a dictionary containing all the inputs and + outputs from the data description and a local alias string. For + example:: + + id_map = {"var1": "My:first:variable", + "var2": "My:second:variable", + "var3": "My:third:variable" + } + + """ + + id_map = { + "device_cost": "device.system_cost", + "annual_energy": "project.annual_energy", + "n_devices": "project.number_of_devices", + "discount_rate": "project.discount_rate", + "electrical_bom": "project.electrical_economics_data", + "moorings_bom": "project.moorings_foundations_economics_data", + "installation_bom": "project.installation_economics_data", + "capex_oandm": "project.capex_oandm", + "opex_per_year": "project.opex_per_year", + "energy_per_year": "project.energy_per_year", + "lifetime_opex_mean": "project.lifetime_opex_mean", + "lifetime_opex_mode": "project.lifetime_opex_mode", + "network_efficiency": "project.electrical_network_efficiency", + "externalities_capex": "project.externalities_capex", + "externalities_opex": "project.externalities_opex", + "lifetime": "project.lifetime", + "electrical_estimate": "project.electrical_cost_estimate", + "moorings_estimate": "project.moorings_cost_estimate", + "install_estimate": "project.installation_cost_estimate", + "opex_estimate": "project.opex_estimate", + "annual_repair_cost_estimate": "project.annual_repair_cost_estimate", + "annual_array_mttf_estimate": "project.annual_array_mttf_estimate", + "estimate_energy_record": "project.estimate_energy_record", + "economics_metrics": "project.economics_metrics", + "lcoe_mean": "project.lcoe_mean", + "lcoe_mode_opex": "project.lcoe_mode_opex", + "lcoe_mode_energy": "project.lcoe_mode_energy", + "lcoe_mode": "project.lcoe_mode", + "lcoe_lower": "project.lcoe_interval_lower", + "lcoe_upper": "project.lcoe_interval_upper", + "discounted_opex_mean": "project.discounted_opex_mean", + "discounted_opex_mode": "project.discounted_opex_mode", + "discounted_opex_lower": "project.discounted_opex_interval_lower", + "discounted_opex_upper": "project.discounted_opex_interval_upper", + "discounted_energy_mean": "project.discounted_energy_mean", + "discounted_energy_mode": "project.discounted_energy_mode", + "discounted_energy_lower": "project.discounted_energy_interval_lower", + "discounted_energy_upper": "project.discounted_energy_interval_upper", + "capex_total": "project.capex_total", + "capex_no_externalities": "project.capex_without_externalities", + "discounted_capex": "project.discounted_capex", + "lifetime_cost_mean": "project.lifetime_cost_mean", + "lifetime_cost_mode": "project.lifetime_cost_mode", + "discounted_lifetime_cost_mean": "project.discounted_lifetime_cost_mean", + "discounted_lifetime_cost_mode": "project.discounted_lifetime_cost_mode", + "cost_breakdown": "project.cost_breakdown", + "capex_breakdown": "project.capex_breakdown", + "capex_lcoe_breakdown": "project.capex_lcoe_breakdown", + "opex_breakdown": "project.opex_breakdown", + "opex_lcoe_breakdown": "project.opex_lcoe_breakdown", + "lcoe_breakdown": "project.lcoe_breakdown", + "confidence_density": "project.confidence_density", + "lcoe_pdf": "project.lcoe_pdf", + } + + return id_map + + def connect(self, debug_entry=False): + """The connect method is used to execute the external program and + populate the interface data store with values. + + Note: + Collecting data from the interface for use in the external program + can be accessed using self.data.my_input_variable. To put new values + into the interface once the program has run we set + self.data.my_output_variable = value + + """ + + bom_cols = ["phase", "quantity", "unitary_cost", "project_year"] + + # CAPEX Dataframes + device_bom = pd.DataFrame(columns=bom_cols) + electrical_bom = pd.DataFrame(columns=bom_cols) + moorings_bom = pd.DataFrame(columns=bom_cols) + installation_bom = pd.DataFrame(columns=bom_cols) + capex_oandm_bom = pd.DataFrame(columns=bom_cols) + externalities_bom = pd.DataFrame(columns=bom_cols) + + opex_bom = pd.DataFrame() + energy_record = pd.DataFrame() + + # Prepare costs + if ( + self.data.n_devices is not None + and self.data.device_cost is not None + ): + quantities = [self.data.n_devices] + costs = [self.data.device_cost] + years = [0] + + device_bom = make_phase_bom(quantities, costs, years, "Devices") + + # Patch double counting of umbilical + if ( + self.data.electrical_bom is not None + and self.data.moorings_bom is not None + ): + # Remove matching identifiers from electrical bom + unique = list(set(self.data.moorings_bom["Key Identifier"])) + + matching = self.data.electrical_bom["Key Identifier"].isin(unique) + self.data.electrical_bom = self.data.electrical_bom[~matching] + + if self.data.electrical_bom is not None: + electrical_bom = self.data.electrical_bom.drop( + "Key Identifier", axis=1 + ) + + name_map = { + "Quantity": "quantity", + "Cost": "unitary_cost", + "Year": "project_year", + } + + electrical_bom = electrical_bom.rename(columns=name_map) + electrical_bom["phase"] = "Electrical Sub-Systems" + + elif self.data.electrical_estimate is not None: + electrical_bom = estimate_cost_per_power( + 1, self.data.electrical_estimate, "Electrical Sub-Systems" + ) + + if self.data.moorings_bom is not None: + moorings_bom = self.data.moorings_bom.drop("Key Identifier", axis=1) + + name_map = { + "Quantity": "quantity", + "Cost": "unitary_cost", + "Year": "project_year", + } + + moorings_bom = moorings_bom.rename(columns=name_map) + moorings_bom["phase"] = "Mooring and Foundations" + + elif self.data.moorings_estimate is not None: + moorings_bom = estimate_cost_per_power( + 1, self.data.moorings_estimate, "Mooring and Foundations" + ) + + if self.data.installation_bom is not None: + installation_bom = self.data.installation_bom.drop( + "Key Identifier", axis=1 + ) + + name_map = { + "Quantity": "quantity", + "Cost": "unitary_cost", + "Year": "project_year", + } + + installation_bom = installation_bom.rename(columns=name_map) + installation_bom["phase"] = "Installation" + + elif self.data.install_estimate is not None: + installation_bom = estimate_cost_per_power( + 1, self.data.install_estimate, "Installation" + ) + + if self.data.capex_oandm is not None: + quantities = [1] + costs = [self.data.capex_oandm] + years = [0] + + capex_oandm_bom = make_phase_bom( + quantities, costs, years, "Condition Monitoring" + ) + + if self.data.externalities_capex is not None: + quantities = [1] + costs = [self.data.externalities_capex] + years = [0] + + externalities_bom = make_phase_bom( + quantities, costs, years, "Externalities" + ) + + # Combine the capex dataframes + capex_bom = pd.concat( + [ + device_bom, + electrical_bom, + moorings_bom, + installation_bom, + capex_oandm_bom, + externalities_bom, + ], + ignore_index=True, + sort=False, + ) + + if self.data.opex_per_year is not None: + opex_bom = self.data.opex_per_year.copy() + opex_bom.index.name = "project_year" + opex_bom = opex_bom.reset_index() + + elif self.data.lifetime is not None and ( + self.data.opex_estimate is not None + or ( + self.data.annual_repair_cost_estimate is not None + and self.data.annual_array_mttf_estimate is not None + ) + ): + opex_bom = estimate_opex( + self.data.lifetime, + 1, + self.data.opex_estimate, + self.data.annual_repair_cost_estimate, + self.data.annual_array_mttf_estimate, + ) + + # Add OPEX externalities + if not opex_bom.empty and self.data.externalities_opex is not None: + opex_bom = opex_bom.set_index("project_year") + opex_bom += self.data.externalities_opex + opex_bom = opex_bom.reset_index() + + # Prepare energy + if self.data.network_efficiency is not None: + net_coeff = self.data.network_efficiency * 1e3 + else: + net_coeff = 1e3 + + if self.data.energy_per_year is not None: + energy_record = self.data.energy_per_year.copy() + energy_record = energy_record * net_coeff + energy_record.index.name = "project_year" + energy_record = energy_record.reset_index() + + elif ( + self.data.estimate_energy_record + and self.data.lifetime is not None + and self.data.annual_energy is not None + ): + energy_record = estimate_energy( + self.data.lifetime, self.data.annual_energy, net_coeff + ) + + if debug_entry: + return + + result = main( + capex_bom, + opex_bom, + energy_record, + self.data.discount_rate, + ) + + discounted_capex = result["Discounted CAPEX"] + assert discounted_capex is not None + + self.data.capex_total = result["CAPEX"] + self.data.discounted_capex = discounted_capex + self.data.capex_breakdown = result["CAPEX breakdown"] + + if self.data.externalities_capex is not None: + self.data.capex_no_externalities = ( + self.data.capex_total - self.data.externalities_capex + ) + + # Build metrics table if possible + n_rows = None + + if not opex_bom.empty: + n_rows = len(opex_bom.columns) - 1 + elif not energy_record.empty: + n_rows = len(energy_record.columns) - 1 + else: + return + + table_cols = [ + "LCOE", + "LCOE CAPEX", + "LCOE OPEX", + "OPEX", + "Energy", + "Discounted OPEX", + "Discounted Energy", + ] + + metrics_dict = {} + + for col_name in table_cols: + col_result = result[col_name] + if col_result is not None: + values = col_result.values + if "Energy" in col_name: + values /= 1e3 + else: + values = [None] * n_rows + + metrics_dict[col_name] = values + + metrics_table = pd.DataFrame(metrics_dict) + + self.data.economics_metrics = metrics_table + + # Do univariate stats on discounted metrics and optionally LCOE + args_table = {"Discounted Energy": "discounted_energy"} + + if metrics_table["Discounted OPEX"].isnull().any(): + args_table["LCOE"] = "lcoe" + else: + args_table["Discounted OPEX"] = "discounted_opex" + args_table["OPEX"] = "lifetime_opex" + + for key, arg_root in args_table.items(): + if metrics_table[key].isnull().any(): + continue + + data = metrics_table[key].values + + mean = None + mode = None + lower = None + upper = None + + # Catch one or two data points + if len(data) == 1: + mean = data[0] + + elif len(data) == 2: + assert isinstance(data, np.ndarray) + mean = data.mean() + + else: + assert isinstance(data, np.ndarray) + + try: + distribution = UniVariateKDE(data) + mean = distribution.mean() + mode = distribution.mode() + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + lower = intervals[0] + upper = intervals[1] + + except np.linalg.LinAlgError: + mean = data.mean() + + arg_mean = "{}_mean".format(arg_root) + arg_mode = "{}_mode".format(arg_root) + arg_lower = "{}_lower".format(arg_root) + arg_upper = "{}_upper".format(arg_root) + + self.data[arg_mean] = mean + self.data[arg_mode] = mode + self.data[arg_lower] = lower + self.data[arg_upper] = upper + + # Calculate total costs + lifetime_cost_mean = result["CAPEX"] + lifetime_cost_mode = result["CAPEX"] + lifetime_discounted_cost_mean = discounted_capex + lifetime_discounted_cost_mode = discounted_capex + + if self.data.lifetime_opex_mean is not None: + if lifetime_cost_mean is None: + lifetime_cost_mean = 0 + lifetime_cost_mean += self.data.lifetime_opex_mean + + if self.data.lifetime_opex_mode is not None: + if lifetime_cost_mode is None: + lifetime_cost_mode = 0 + lifetime_cost_mode += self.data.lifetime_opex_mode + + self.data.lifetime_cost_mean = lifetime_cost_mean + self.data.lifetime_cost_mode = lifetime_cost_mode + + # Calculate total discounted costs + if self.data.discounted_opex_mean is not None: + if lifetime_discounted_cost_mean is None: + lifetime_discounted_cost_mean = 0 + lifetime_discounted_cost_mean += self.data.discounted_opex_mean + + if self.data.discounted_opex_mode is not None: + if lifetime_discounted_cost_mode is None: + lifetime_discounted_cost_mode = 0 + lifetime_discounted_cost_mode += self.data.discounted_opex_mode + + self.data.discounted_lifetime_cost_mean = lifetime_discounted_cost_mean + self.data.discounted_lifetime_cost_mode = lifetime_discounted_cost_mode + + if ( + metrics_table["Discounted Energy"].isnull().any() + or metrics_table["Discounted OPEX"].isnull().any() + ): + return + + energy = metrics_table["Discounted Energy"] + opex = metrics_table["Discounted OPEX"] / 1000.0 + + if len(metrics_table["Discounted Energy"]) < 3: + mean_lcoe = (discounted_capex / 1000.0 + np.mean(opex)) / np.mean( + energy + ) + + self.data.lcoe_mean = mean_lcoe + discounted_opex_base = np.mean(opex) * 1000.0 + discounted_energy_base = np.mean(energy) * 10.0 + + else: + try: + distribution = BiVariateKDE(opex, energy) + except np.linalg.LinAlgError: + return + + mean_coords = distribution.mean() + self.data.lcoe_mean = ( + discounted_capex / 1000.0 + mean_coords[0] + ) / mean_coords[1] + + mode_coords = distribution.mode() + lcoe_mode = ( + discounted_capex / 1000.0 + mode_coords[0] + ) / mode_coords[1] + + self.data.lcoe_mode_opex = mode_coords[0] * 1000 + self.data.lcoe_mode_energy = mode_coords[1] + self.data.lcoe_mode = lcoe_mode + + xx, yy, pdf = distribution.pdf() + clevels = pdf_confidence_densities(pdf) + + if clevels: + cx, cy = pdf_contour_coords(xx, yy, pdf, clevels[0]) + + lcoes = [] + + for discounted_opex, discounted_energy in zip(cx, cy): + lcoe = ( + discounted_capex / 1000.0 + discounted_opex + ) / discounted_energy + lcoes.append(lcoe) + + self.data.confidence_density = clevels[0] + self.data.lcoe_lower = min(lcoes) + self.data.lcoe_upper = max(lcoes) + + # LCOE distribution + raw = {"values": pdf, "coords": [xx, yy]} + + self.data.lcoe_pdf = raw + + discounted_opex_base = mode_coords[0] * 1000.0 + discounted_energy_base = mode_coords[1] * 10.0 + + # Calculate values using most likely OPEX / Energy combination + + # CAPEX vs OPEX Breakdown and OPEX Breakdown if externalities + breakdown = { + "Discounted CAPEX": discounted_capex, + "Discounted OPEX": discounted_opex_base, + } + + self.data.cost_breakdown = breakdown + + if self.data.externalities_opex is None: + discounted_maintenance = discounted_opex_base + + else: + years = range(1, len(opex_bom) + 1) + + discounted_externals = [ + self.data.externalities_opex + / (1 + self.data.discount_rate) ** i + for i in years + ] + + discounted_external = np.array(discounted_externals).sum() + discounted_maintenance = discounted_opex_base - discounted_external + + self.data.opex_breakdown = { + "Maintenance": discounted_external, + "Externalities": discounted_maintenance, + } + + # LCOE Breakdowns in cent/kWh + + if self.data.capex_breakdown is not None: + capex_lcoe_breakdown = {} + + for k, v in self.data.capex_breakdown.iteritems(): + capex_lcoe_breakdown[k] = round(v / discounted_energy_base, 2) + + self.data.capex_lcoe_breakdown = capex_lcoe_breakdown + + lcoe_maintenance = round( + discounted_maintenance / discounted_energy_base, 2 + ) + + if self.data.externalities_opex is None: + lcoe_external = 0 + + else: + lcoe_external = round( + discounted_external / discounted_energy_base, 2 + ) + + self.data.opex_lcoe_breakdown = { + "Maintenance": lcoe_maintenance, + "Externalities": lcoe_external, + } + + total_capex = sum(capex_lcoe_breakdown.values()) + total_opex = lcoe_maintenance + lcoe_external + + self.data.lcoe_breakdown = {"CAPEX": total_capex, "OPEX": total_opex} + + return diff --git a/packages/dtocean-economics/tests/conftest.py b/packages/dtocean-economics/tests/dtocean_economics/conftest.py similarity index 100% rename from packages/dtocean-economics/tests/conftest.py rename to packages/dtocean-economics/tests/dtocean_economics/conftest.py diff --git a/packages/dtocean-economics/tests/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py similarity index 98% rename from packages/dtocean-economics/tests/test_functions.py rename to packages/dtocean-economics/tests/dtocean_economics/test_functions.py index b0f837de..2ca07389 100644 --- a/packages/dtocean-economics/tests/test_functions.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2017-2026 Mathew Topper +# Copyright (C) 2017-2026 Mathew Topper # # 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 diff --git a/packages/dtocean-economics/tests/test_main.py b/packages/dtocean-economics/tests/dtocean_economics/test_main.py similarity index 100% rename from packages/dtocean-economics/tests/test_main.py rename to packages/dtocean-economics/tests/dtocean_economics/test_main.py diff --git a/packages/dtocean-economics/tests/test_preprocessing.py b/packages/dtocean-economics/tests/dtocean_economics/test_preprocessing.py similarity index 100% rename from packages/dtocean-economics/tests/test_preprocessing.py rename to packages/dtocean-economics/tests/dtocean_economics/test_preprocessing.py diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_stats.py b/packages/dtocean-economics/tests/dtocean_economics/test_stats.py new file mode 100644 index 00000000..6ba2ac18 --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_economics/test_stats.py @@ -0,0 +1,389 @@ +# -*- coding: utf-8 -*- + +import numpy as np +import pytest +from scipy.stats import norm + +from dtocean_economics.stats import ( + BiVariateKDE, + UniVariateKDE, + get_standard_error, + pdf_confidence_densities, + pdf_contour_coords, +) + +SLACK = 85 + + +@pytest.fixture(scope="module") +def gaussian(): + """Build an estimate of a gaussian distribution. Object is shared""" + + data = np.random.normal(size=10000) + distribution = UniVariateKDE(data) + + return distribution + + +@pytest.fixture +def gaussian_fresh(): + """Build an estimate of a gaussian distribution. Object is recreated""" + + data = np.random.normal(size=10000) + distribution = UniVariateKDE(data) + + return distribution + + +@pytest.fixture(scope="module") +def bigaussian(): + """Build an estimate of a bivariate gaussian distribution. + Object is shared""" + + mean = [0, 0] + cov = [[1, 0], [0, 1]] # diagonal covariance + + x, y = np.random.multivariate_normal(mean, cov, int(1e6)).T + distribution = BiVariateKDE(x, y) + + return distribution + + +@pytest.fixture(scope="module") +def bigaussian_pdf(bigaussian): + xx, yy, pdf = bigaussian.pdf(npoints=10) + + result = {"xx": xx, "yy": yy, "pdf": pdf} + + return result + + +def test_UniVariateKDE_pdf(gaussian): + values = np.linspace(-5, 5, 200) + estimated = gaussian.pdf(values) + ideal = norm.pdf(values) + + assert np.isclose(estimated, ideal, rtol=0, atol=5e-02).all() + + +def test_UniVariateKDE_cdf(gaussian): + values = np.linspace(-5, 5, 200) + estimated = gaussian.cdf(values) + ideal = norm.cdf(values) + + assert np.isclose(estimated, ideal, rtol=0, atol=5e-02).all() + + +def test_UniVariateKDE_ppf(gaussian): + probs = np.linspace(0.01, 0.99, 200) + estimated = gaussian.ppf(probs) + ideal = norm.ppf(probs) + + assert np.isclose(estimated, ideal, rtol=0, atol=2e-1).all() + + +def test_UniVariateKDE_ppf_nan(mocker, gaussian): + mocker.patch( + "dtocean_core.utils.stats.optimize.fsolve", + return_value=[0, 0, 0], + autospec=True, + ) + + probs = np.linspace(0.01, 0.99, 200) + estimated = gaussian.ppf(probs) + + assert estimated is None + + +def test_UniVariateKDE_mean(): + """Trival function calculates mean of initial dataset not distribution""" + + def get_vals(): + results = [] + for _ in range(30): + data = np.random.normal(size=50) + distribution = UniVariateKDE(data) + results.append(distribution.mean()) + return results + + expected = 0 + confidence = 3.291 # 99.9% interval + + n_tests = 20 + tests = [] + + for _ in range(n_tests): + values = get_vals() + std_error = get_standard_error(values) + assert std_error is not None + + # Check that the expected value is within interval + actual = np.array(values).mean() + test = (actual - confidence * std_error < expected) and ( + expected < actual + confidence * std_error + ) + tests.append(int(test)) + + tpct = sum(tests) * 100.0 / n_tests + + # Add some slack! + assert tpct >= SLACK + + +def test_UniVariateKDE_median(): + """Trival function calculates median of initial dataset not distribution""" + + def get_vals(): + results = [] + for _ in range(30): + data = np.random.normal(size=50) + distribution = UniVariateKDE(data) + results.append(distribution.median()) + return results + + expected = 0 + confidence = 3.291 # 99.9% interval + + n_tests = 20 + tests = [] + + for _ in range(n_tests): + values = get_vals() + std_error = get_standard_error(values) + assert std_error is not None + + # Check that the expected value is within interval + actual = np.median(values) + test = (actual - confidence * std_error < expected) and ( + expected < actual + confidence * std_error + ) + tests.append(int(test)) + + tpct = sum(tests) * 100.0 / n_tests + + # Add some slack! + assert tpct >= SLACK + + +def test_UniVariateKDE_mode(): + def get_vals(): + results = [] + for _ in range(30): + data = np.random.normal(size=50) + distribution = UniVariateKDE(data) + results.append(distribution.mode()) + return results + + expected = 0 + confidence = 3.291 # 99.9% interval + + n_tests = 20 + tests = [] + + for _ in range(n_tests): + values = get_vals() + std_error = get_standard_error(values) + assert std_error is not None + + # Check that the expected value is within interval + actual = np.array(values).mean() + test = (actual - confidence * std_error < expected) and ( + expected < actual + confidence * std_error + ) + tests.append(int(test)) + + tpct = sum(tests) * 100.0 / n_tests + + # Add some slack! + assert tpct >= SLACK + + +def test_UniVariateKDE_interval(gaussian): + estimated = gaussian.confidence_interval(90) + ideal = norm.interval(0.9) + + assert np.isclose(estimated, ideal, rtol=0, atol=2e-1).all() + + +def test_UniVariateKDE_ppf_x0(gaussian): + probs = np.linspace(0.01, 0.99, 200) + estimated = gaussian.ppf(probs) + + assert estimated.all() + + +def test_UniVariateKDE_interval_x0(gaussian): + estimated = gaussian.confidence_interval(90) + + assert estimated.all() + + +def test_UniVariateKDE_ppf_fresh(gaussian_fresh): + probs = np.linspace(0.01, 0.99, 200) + estimated = gaussian_fresh.ppf(probs) + ideal = norm.ppf(probs) + + assert np.isclose(estimated, ideal, rtol=0, atol=2e-1).all() + + +def test_UniVariateKDE_interval_fresh(gaussian_fresh): + estimated = gaussian_fresh.confidence_interval(90) + ideal = norm.interval(0.9) + + assert np.isclose(estimated, ideal, rtol=0, atol=2e-1).all() + + +def test_BiVariateKDE_mean(): + def get_vals(): + results = [] + mean = [0, 0] + cov = [[1, 0], [0, 1]] + for _ in range(30): + x, y = np.random.multivariate_normal(mean, cov, int(1e4)).T + distribution = BiVariateKDE(x, y) + results.append(sum(distribution.mean())) + return results + + expected = 0 + confidence = 3.291 # 99.9% interval + + n_tests = 20 + tests = [] + + for _ in range(n_tests): + values = get_vals() + std_error = get_standard_error(values) + assert std_error is not None + + # Check that the expected value is within interval + actual = np.array(values).mean() + test = (actual - confidence * std_error < expected) and ( + expected < actual + confidence * std_error + ) + tests.append(int(test)) + + tpct = sum(tests) * 100.0 / n_tests + + # Add some slack! + assert tpct >= SLACK + + +def test_BiVariateKDE_mode(): + def get_vals(): + results = [] + mean = [0, 0] + cov = [[1, 0], [0, 1]] + for _ in range(30): + x, y = np.random.multivariate_normal(mean, cov, int(1e4)).T + distribution = BiVariateKDE(x, y) + results.append(sum(distribution.mode())) + return results + + expected = 0 + confidence = 3.291 # 99.9% interval + + n_tests = 20 + tests = [] + + for _ in range(n_tests): + values = get_vals() + std_error = get_standard_error(values) + assert std_error is not None + + # Check that the expected value is within interval + actual = np.array(values).mean() + test = (actual - confidence * std_error < expected) and ( + expected < actual + confidence * std_error + ) + tests.append(int(test)) + + tpct = sum(tests) * 100.0 / n_tests + + # Add some slack! + assert tpct >= SLACK + + +def test_BiVariateKDE_pdf(bigaussian_pdf): + xx = bigaussian_pdf["xx"] + yy = bigaussian_pdf["yy"] + pdf = bigaussian_pdf["pdf"] + + assert pdf.shape == (len(xx), len(yy)) + + +def test_pdf_confidence_densities(bigaussian_pdf): + pdf = bigaussian_pdf["pdf"] + result = pdf_confidence_densities(pdf) + is_positive = [x > 0 for x in result] + + assert all(is_positive) + + +def test_pdf_confidence_densities_levels(bigaussian_pdf): + pdf = bigaussian_pdf["pdf"] + result = pdf_confidence_densities(pdf, [50, 95]) + is_positive = [x > 0 for x in result] + + assert all(is_positive) + + +def test_pdf_contour_coords(bigaussian_pdf): + xx = bigaussian_pdf["xx"] + yy = bigaussian_pdf["yy"] + pdf = bigaussian_pdf["pdf"] + + levels = pdf_confidence_densities(pdf) + + if not levels: + pytest.skip("No levels generated for testing") + + cx, cy = pdf_contour_coords(xx, yy, pdf, levels[0]) + + assert len(cx) > 0 + assert len(cy) > 0 + + +def test_get_standard_error(): + def get_vals(): + results = [] + for _ in range(30): + result = np.mean(np.random.standard_normal(size=10) + 1) + results.append(result) + return results + + expected = 1 + confidence = 3.291 # 99.9% interval + + n_tests = 100 + tests = [] + + for _ in range(n_tests): + values = get_vals() + std_error = get_standard_error(values) + assert std_error is not None + + # Check that the expected value is within interval + actual = np.array(values).mean() + test = (actual - confidence * std_error < expected) and ( + expected < actual + confidence * std_error + ) + tests.append(int(test)) + + tpct = sum(tests) * 100.0 / n_tests + + # Add some slack! + assert tpct >= SLACK + + +def test_get_standard_error_large(): + values = np.random.normal(size=1000) + result = get_standard_error(values) + + assert result is not None + assert result > 0 + + +@pytest.mark.parametrize("length", [0, 1]) +def test_get_standard_error_one_value(length): + values = [1] * length + assert get_standard_error(values) is None diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/conftest.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/conftest.py new file mode 100644 index 00000000..df1e86f6 --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/conftest.py @@ -0,0 +1,3 @@ +import pytest + +pytest.importorskip("dtocean_core") diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py new file mode 100644 index 00000000..15b0ae50 --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -0,0 +1,186 @@ +import os +from copy import deepcopy +from pprint import pprint + +import pytest +from dtocean_core.core import Core +from dtocean_core.menu import DataMenu, ProjectMenu, ThemeMenu +from dtocean_core.pipeline import Tree, _get_connector + +DIR_PATH = os.path.dirname(__file__) + + +@pytest.fixture(scope="module") +def core(): + """Share a Core object""" + + new_core = Core() + + return new_core + + +@pytest.fixture(scope="module") +def var_tree(): + return Tree() + + +@pytest.fixture(scope="module") +def theme_menu(core): + """Share a ModuleMenu object""" + + return ThemeMenu() + + +# Using a py.test fixture to reduce boilerplate and test times. +@pytest.fixture(scope="module") +def tidal_project(core, var_tree): + """Share a Project object""" + + project_menu = ProjectMenu() + + new_project = project_menu.new_project(core, "test tidal") + + options_branch = var_tree.get_branch( + core, new_project, "System Type Selection" + ) + device_type = options_branch.get_input_variable( + core, new_project, "device.system_type" + ) + device_type.set_raw_interface(core, "Tidal Fixed") + device_type.read(core, new_project) + + project_menu.initiate_pipeline(core, new_project) + + return new_project + + +def test_economics_inputs(theme_menu, core, tidal_project, var_tree): + theme_name = "Economics" + data_menu = DataMenu() + + project_menu = ProjectMenu() + project = deepcopy(tidal_project) + theme_menu.activate(core, project, theme_name) + project_menu.initiate_dataflow(core, project) + data_menu.load_data(core, project) + + economics_branch = var_tree.get_branch(core, project, theme_name) + economics_input_status = economics_branch.get_input_status(core, project) + + assert "project.estimate_energy_record" in economics_input_status + + +def test_get_economics_interface(theme_menu, core, tidal_project, var_tree): + theme_name = "Economics" + + project_menu = ProjectMenu() + project = deepcopy(tidal_project) + theme_menu.activate(core, project, theme_name) + project_menu.initiate_dataflow(core, project) + + economics_branch = var_tree.get_branch(core, project, theme_name) + economics_branch.read_test_data( + core, project, os.path.join(DIR_PATH, "inputs_economics.pkl") + ) + economics_branch.read_auto(core, project) + + can_execute = theme_menu.is_executable(core, project, theme_name) + + if not can_execute: + inputs = economics_branch.get_input_status(core, project) + pprint(inputs) + assert can_execute + + connector = _get_connector(project, "themes") + interface = connector.get_interface(core, project, theme_name) + + assert interface.data.electrical_bom is not None + + +def test_economics_interface_entry(theme_menu, core, tidal_project, var_tree): + theme_name = "Economics" + + project_menu = ProjectMenu() + project = deepcopy(tidal_project) + theme_menu.activate(core, project, theme_name) + project_menu.initiate_dataflow(core, project) + + economics_branch = var_tree.get_branch(core, project, theme_name) + economics_branch.read_test_data( + core, project, os.path.join(DIR_PATH, "inputs_economics.pkl") + ) + economics_branch.read_auto(core, project) + + can_execute = theme_menu.is_executable(core, project, theme_name) + + if not can_execute: + inputs = economics_branch.get_input_status(core, project) + pprint(inputs) + assert can_execute + + connector = _get_connector(project, "themes") + interface = connector.get_interface(core, project, theme_name) + + interface.connect(debug_entry=True) + + assert True + + +def test_get_economics_interface_estimate( + theme_menu, core, tidal_project, var_tree +): + theme_name = "Economics" + + project_menu = ProjectMenu() + project = deepcopy(tidal_project) + theme_menu.activate(core, project, theme_name) + project_menu.initiate_dataflow(core, project) + + economics_branch = var_tree.get_branch(core, project, theme_name) + economics_branch.read_test_data( + core, project, os.path.join(DIR_PATH, "inputs_economics_estimate.pkl") + ) + economics_branch.read_auto(core, project) + + can_execute = theme_menu.is_executable(core, project, theme_name) + + if not can_execute: + inputs = economics_branch.get_input_status(core, project) + pprint(inputs) + assert can_execute + + connector = _get_connector(project, "themes") + interface = connector.get_interface(core, project, theme_name) + + assert interface.data.electrical_estimate is not None + + +def test_economics_interface_entry_estimate( + theme_menu, core, tidal_project, var_tree +): + theme_name = "Economics" + + project_menu = ProjectMenu() + project = deepcopy(tidal_project) + theme_menu.activate(core, project, theme_name) + project_menu.initiate_dataflow(core, project) + + economics_branch = var_tree.get_branch(core, project, theme_name) + economics_branch.read_test_data( + core, project, os.path.join(DIR_PATH, "inputs_economics_estimate.pkl") + ) + economics_branch.read_auto(core, project) + + can_execute = theme_menu.is_executable(core, project, theme_name) + + if not can_execute: + inputs = economics_branch.get_input_status(core, project) + pprint(inputs) + assert can_execute + + connector = _get_connector(project, "themes") + interface = connector.get_interface(core, project, theme_name) + + interface.connect(debug_entry=True) + + assert True diff --git a/poetry.lock b/poetry.lock index a2ce882a..410872b0 100644 --- a/poetry.lock +++ b/poetry.lock @@ -820,7 +820,6 @@ pywin32 = {version = ">=308", markers = "sys_platform == \"win32\""} pyyaml = "^6.0.2" ruamel-yaml = "^0.19.1" ruamel-yaml-clib = "^0.2.12" -scipy = "^1.17.0" shapely = "^2.0.6" utm = "^0.8.1" xarray = "~2026.2.0" @@ -880,6 +879,7 @@ develop = true [package.dependencies] pandas = "^3.0.1" +scipy = "^1.17.0" [package.source] type = "directory" @@ -3362,7 +3362,7 @@ version = "1.17.1" description = "Fundamental algorithms for scientific computing in Python" optional = false python-versions = ">=3.11" -groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-hydrodynamics"] +groups = ["dtocean", "dtocean-economics", "dtocean-hydrodynamics"] files = [ {file = "scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec"}, {file = "scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696"}, @@ -3426,7 +3426,7 @@ files = [ {file = "scipy-1.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:200e1050faffacc162be6a486a984a0497866ec54149a01270adc8a59b7c7d21"}, {file = "scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0"}, ] -markers = {dtocean = "python_version < \"3.14\"", dtocean-app = "python_version < \"3.14\"", dtocean-core = "python_version < \"3.14\""} +markers = {dtocean = "python_version < \"3.14\""} [package.dependencies] numpy = ">=1.26.4,<2.7" From dfcc5585aa01ad57392b828c518c229513efe792 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Sun, 29 Mar 2026 16:50:06 +0100 Subject: [PATCH 03/40] Get interface tests working Also add contourpy as dependency for stats module --- packages/dtocean-economics/pyproject.toml | 1 + .../test_data/inputs_economics.py | 61 +++++++++++++++++++ .../test_data/inputs_economics_estimate.py | 33 ++++++++++ .../tests/dtocean_economics/test_stats.py | 2 +- .../tests/dtocean_plugins/conftest.py | 51 ++++++++++++++++ .../themes/test_themes_economics.py | 44 ++++++++----- poetry.lock | 3 +- 7 files changed, 177 insertions(+), 18 deletions(-) create mode 100644 packages/dtocean-economics/test_data/inputs_economics.py create mode 100644 packages/dtocean-economics/test_data/inputs_economics_estimate.py create mode 100644 packages/dtocean-economics/tests/dtocean_plugins/conftest.py diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index cf57f7ee..d7d06b88 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -28,6 +28,7 @@ python = ">=3.12,<3.15" include-groups = ["dtocean-economics"] [tool.poetry.group.dtocean-economics.dependencies] +contourpy = "^1.3.1" pandas = "^3.0.1" scipy = "^1.17.0" diff --git a/packages/dtocean-economics/test_data/inputs_economics.py b/packages/dtocean-economics/test_data/inputs_economics.py new file mode 100644 index 00000000..321fae1b --- /dev/null +++ b/packages/dtocean-economics/test_data/inputs_economics.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Apr 09 10:39:38 2015 + +@author: 108630 +""" + +import os + +import pandas as pd + +discount_rate = 0.1 +electrical_network_efficiency = 0.99 +capex_oandm = 100.0 +externalities_capex = 1e6 + +zero_bom_dict = { + "Key Identifier": [0, 1], + "Quantity": [5, 10], + "Cost": [100, 50], + "Year": [0, 0], +} +zero_bom = pd.DataFrame(zero_bom_dict) + +electrical_bom = zero_bom.copy() +moorings_bom = zero_bom.copy() + +install_bom_dict = { + "Key Identifier": [0, 1], + "Quantity": [1, 1], + "Cost": [1000, 2000], + "Year": [1, 2], +} +install_bom = pd.DataFrame(install_bom_dict) + +opex_bom_dict = {"Cost": [1000, 2000], "Year": [3, 4]} +opex_bom = pd.DataFrame(opex_bom_dict) + +energy_record_dict = {"Energy": [10000, 20000], "Year": [3, 4]} +energy_record = pd.DataFrame(energy_record_dict) + + +test_data = { + "project.discount_rate": discount_rate, + "project.electrical_economics_data": electrical_bom, + "project.moorings_foundations_economics_data": moorings_bom, + "project.installation_economics_data": install_bom, + "project.capex_oandm": capex_oandm, + "project.opex_per_year": opex_bom, + "project.energy_per_year": energy_record, + "project.electrical_network_efficiency": electrical_network_efficiency, + "project.externalities_capex": externalities_capex, +} + +if __name__ == "__main__": + from dtocean_core.utils.files import pickle_test_data + + file_path = os.path.abspath(__file__) + pkl_path = pickle_test_data(file_path, test_data) + + print("generate test data: {}".format(pkl_path)) diff --git a/packages/dtocean-economics/test_data/inputs_economics_estimate.py b/packages/dtocean-economics/test_data/inputs_economics_estimate.py new file mode 100644 index 00000000..f54fc72b --- /dev/null +++ b/packages/dtocean-economics/test_data/inputs_economics_estimate.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Apr 09 10:39:38 2015 + +@author: 108630 +""" + +import os + +test_data = { + "project.discount_rate": 0.1, + "project.lifetime": 20, + "project.number_of_devices": 5, + "device.system_cost": 1e6, + "device.power_rating": 1.0, + "project.electrical_cost_estimate": 1e5, + "project.moorings_cost_estimate": 1e5, + "project.installation_cost_estimate": 1e5, + "project.opex_estimate": 1e4, + "project.annual_repair_cost_estimate": 1e4, + "project.annual_array_mttf_estimate": 10000.0, + "project.electrical_network_efficiency": 0.95, + "project.annual_energy": 10000.0, + "project.estimate_energy_record": True, +} + +if __name__ == "__main__": + from dtocean_core.utils.files import pickle_test_data + + file_path = os.path.abspath(__file__) + pkl_path = pickle_test_data(file_path, test_data) + + print("generate test data: {}".format(pkl_path)) diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_stats.py b/packages/dtocean-economics/tests/dtocean_economics/test_stats.py index 6ba2ac18..89ad6daf 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_stats.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_stats.py @@ -84,7 +84,7 @@ def test_UniVariateKDE_ppf(gaussian): def test_UniVariateKDE_ppf_nan(mocker, gaussian): mocker.patch( - "dtocean_core.utils.stats.optimize.fsolve", + "dtocean_economics.stats.optimize.fsolve", return_value=[0, 0, 0], autospec=True, ) diff --git a/packages/dtocean-economics/tests/dtocean_plugins/conftest.py b/packages/dtocean-economics/tests/dtocean_plugins/conftest.py new file mode 100644 index 00000000..03fbe1bc --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_plugins/conftest.py @@ -0,0 +1,51 @@ +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +FILE = Path(__file__).resolve() + + +@pytest.fixture(scope="session") +def test_data_path(): + return FILE.parents[2] / "test_data" + + +@pytest.fixture(scope="session") +def inputs_economics(test_data_path): + yield _make_test_data(test_data_path, "inputs_economics") + _remove_test_data("inputs_economics") + + +@pytest.fixture(scope="session") +def inputs_economics_estimate(test_data_path): + yield _make_test_data(test_data_path, "inputs_economics_estimate") + _remove_test_data("inputs_economics_estimate") + + +def _make_test_data(data_dir: Path, name: str): + # Pickle data files and move to test directory + test_dir = FILE.parent + + src_path_py = (data_dir / name).with_suffix(".py") + result = subprocess.run( + [sys.executable, src_path_py], + capture_output=True, + text=True, + ) + + if result.returncode: + raise ChildProcessError(result.stderr) + + src_path_pkl = (data_dir / name).with_suffix(".pkl") + dst_path_pkl = (test_dir / name).with_suffix(".pkl") + shutil.move(src_path_pkl, dst_path_pkl) + + return dst_path_pkl + + +def _remove_test_data(name: str): + test_dir = FILE.parent + (test_dir / name).with_suffix(".pkl").unlink() diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index 15b0ae50..0409c0f8 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -70,7 +70,13 @@ def test_economics_inputs(theme_menu, core, tidal_project, var_tree): assert "project.estimate_energy_record" in economics_input_status -def test_get_economics_interface(theme_menu, core, tidal_project, var_tree): +def test_get_economics_interface( + inputs_economics, + theme_menu, + core, + tidal_project, + var_tree, +): theme_name = "Economics" project_menu = ProjectMenu() @@ -79,9 +85,7 @@ def test_get_economics_interface(theme_menu, core, tidal_project, var_tree): project_menu.initiate_dataflow(core, project) economics_branch = var_tree.get_branch(core, project, theme_name) - economics_branch.read_test_data( - core, project, os.path.join(DIR_PATH, "inputs_economics.pkl") - ) + economics_branch.read_test_data(core, project, inputs_economics) economics_branch.read_auto(core, project) can_execute = theme_menu.is_executable(core, project, theme_name) @@ -97,7 +101,13 @@ def test_get_economics_interface(theme_menu, core, tidal_project, var_tree): assert interface.data.electrical_bom is not None -def test_economics_interface_entry(theme_menu, core, tidal_project, var_tree): +def test_economics_interface_entry( + inputs_economics, + theme_menu, + core, + tidal_project, + var_tree, +): theme_name = "Economics" project_menu = ProjectMenu() @@ -106,9 +116,7 @@ def test_economics_interface_entry(theme_menu, core, tidal_project, var_tree): project_menu.initiate_dataflow(core, project) economics_branch = var_tree.get_branch(core, project, theme_name) - economics_branch.read_test_data( - core, project, os.path.join(DIR_PATH, "inputs_economics.pkl") - ) + economics_branch.read_test_data(core, project, inputs_economics) economics_branch.read_auto(core, project) can_execute = theme_menu.is_executable(core, project, theme_name) @@ -127,7 +135,11 @@ def test_economics_interface_entry(theme_menu, core, tidal_project, var_tree): def test_get_economics_interface_estimate( - theme_menu, core, tidal_project, var_tree + inputs_economics_estimate, + theme_menu, + core, + tidal_project, + var_tree, ): theme_name = "Economics" @@ -137,9 +149,7 @@ def test_get_economics_interface_estimate( project_menu.initiate_dataflow(core, project) economics_branch = var_tree.get_branch(core, project, theme_name) - economics_branch.read_test_data( - core, project, os.path.join(DIR_PATH, "inputs_economics_estimate.pkl") - ) + economics_branch.read_test_data(core, project, inputs_economics_estimate) economics_branch.read_auto(core, project) can_execute = theme_menu.is_executable(core, project, theme_name) @@ -156,7 +166,11 @@ def test_get_economics_interface_estimate( def test_economics_interface_entry_estimate( - theme_menu, core, tidal_project, var_tree + inputs_economics_estimate, + theme_menu, + core, + tidal_project, + var_tree, ): theme_name = "Economics" @@ -166,9 +180,7 @@ def test_economics_interface_entry_estimate( project_menu.initiate_dataflow(core, project) economics_branch = var_tree.get_branch(core, project, theme_name) - economics_branch.read_test_data( - core, project, os.path.join(DIR_PATH, "inputs_economics_estimate.pkl") - ) + economics_branch.read_test_data(core, project, inputs_economics_estimate) economics_branch.read_auto(core, project) can_execute = theme_menu.is_executable(core, project, theme_name) diff --git a/poetry.lock b/poetry.lock index 410872b0..1508f84b 100644 --- a/poetry.lock +++ b/poetry.lock @@ -429,7 +429,7 @@ version = "1.3.3" description = "Python library for calculating contours of 2D quadrilateral grids" optional = false python-versions = ">=3.11" -groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-hydrodynamics"] +groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-economics", "dtocean-hydrodynamics"] files = [ {file = "contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1"}, {file = "contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381"}, @@ -878,6 +878,7 @@ files = [] develop = true [package.dependencies] +contourpy = "^1.3.1" pandas = "^3.0.1" scipy = "^1.17.0" From a113cb6193f5c834c1c24b2acc4131c686f1aa68 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 30 Mar 2026 09:50:45 +0100 Subject: [PATCH 04/40] Add testing workflow --- .github/workflows/test-dtocean-economics.yml | 96 ++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 .github/workflows/test-dtocean-economics.yml diff --git a/.github/workflows/test-dtocean-economics.yml b/.github/workflows/test-dtocean-economics.yml new file mode 100644 index 00000000..8fad9f6b --- /dev/null +++ b/.github/workflows/test-dtocean-economics.yml @@ -0,0 +1,96 @@ +name: dtocean-economics tests +on: + push: + branches: + - main + paths: + - ".codecov.yml" + - ".github/workflows/test-dtocean-economics.yml" + - "packages/dtocean-core/src/**" + - "packages/dtocean-economics/**" + - "poetry.lock" + pull_request: + branches: + - main + paths: + - ".codecov.yml" + - ".github/workflows/test-dtocean-economics.yml" + - "packages/dtocean-core/src/**" + - "packages/dtocean-economics/**" + - "poetry.lock" + +jobs: + pytest: + name: Unit tests + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + python-version: ["3.14", "3.13", "3.12"] + defaults: + run: + working-directory: packages/dtocean-economics + steps: + - uses: actions/checkout@v6 + with: + lfs: true + persist-credentials: false + - name: Install package + uses: ./.github/actions/poetry-install + with: + groups: '["dtocean-economics", "test"]' + python-version: ${{ matrix.python-version }} + - name: Run tests + run: | + poetry run pytest + pytest-extras: + name: Unit tests with plugins + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + python-version: ["3.13", "3.12"] + defaults: + run: + working-directory: packages/dtocean-economics + steps: + - uses: actions/checkout@v6 + with: + lfs: true + persist-credentials: false + - name: Install package + uses: ./.github/actions/poetry-install + with: + groups: '["dtocean-core", "dtocean-economics", "test"]' + python-version: ${{ matrix.python-version }} + - name: Run tests + run: | + poetry run pytest -v --cov src --cov-report=xml tests + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + flags: dtocean-economics + audit: + name: Code audit + runs-on: ubuntu-latest + defaults: + run: + working-directory: packages/dtocean-economics + steps: + - uses: actions/checkout@v6 + with: + lfs: true + persist-credentials: false + - name: Install package + uses: ./.github/actions/poetry-install + with: + groups: '["audit", "dtocean-core", "dtocean-economics"]' + python-version: 3.13 + - name: Run ruff + run: | + poetry run ruff check --output-format github + - name: Run pyright + run: | + poetry run pyright src From 92f343ecf95e92270eb2cdc36afbc36381759002 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 30 Mar 2026 14:15:33 +0100 Subject: [PATCH 05/40] Undo incorrect removal of scipy from dtocean-core --- packages/dtocean-core/pyproject.toml | 1 + poetry.lock | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/dtocean-core/pyproject.toml b/packages/dtocean-core/pyproject.toml index 42654b51..a9f2976b 100644 --- a/packages/dtocean-core/pyproject.toml +++ b/packages/dtocean-core/pyproject.toml @@ -60,6 +60,7 @@ pywin32 = { version = ">=308", platform = "win32" } cmocean = "^4.0.3" packaging = ">=24.0" cartopy = "^0.25.0" +scipy = "^1.17.0" [tool.poetry.group.test] optional = true diff --git a/poetry.lock b/poetry.lock index 1508f84b..20a960ae 100644 --- a/poetry.lock +++ b/poetry.lock @@ -820,6 +820,7 @@ pywin32 = {version = ">=308", markers = "sys_platform == \"win32\""} pyyaml = "^6.0.2" ruamel-yaml = "^0.19.1" ruamel-yaml-clib = "^0.2.12" +scipy = "^1.17.0" shapely = "^2.0.6" utm = "^0.8.1" xarray = "~2026.2.0" @@ -3363,7 +3364,7 @@ version = "1.17.1" description = "Fundamental algorithms for scientific computing in Python" optional = false python-versions = ">=3.11" -groups = ["dtocean", "dtocean-economics", "dtocean-hydrodynamics"] +groups = ["dtocean", "dtocean-app", "dtocean-core", "dtocean-economics", "dtocean-hydrodynamics"] files = [ {file = "scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec"}, {file = "scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696"}, @@ -3427,7 +3428,7 @@ files = [ {file = "scipy-1.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:200e1050faffacc162be6a486a984a0497866ec54149a01270adc8a59b7c7d21"}, {file = "scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0"}, ] -markers = {dtocean = "python_version < \"3.14\""} +markers = {dtocean = "python_version < \"3.14\"", dtocean-app = "python_version < \"3.14\"", dtocean-core = "python_version < \"3.14\""} [package.dependencies] numpy = ">=1.26.4,<2.7" From ae3a31850e34479c23d7362a836ad2f76706e47f Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 30 Mar 2026 16:19:07 +0100 Subject: [PATCH 06/40] Use easier to calculate expected values in tests --- .../src/dtocean_economics/functions.py | 5 +- .../src/dtocean_plugins/themes/economics.py | 350 +++++++++++------- .../tests/dtocean_economics/conftest.py | 57 +-- .../tests/dtocean_economics/test_functions.py | 38 +- .../tests/dtocean_economics/test_main.py | 39 +- 5 files changed, 290 insertions(+), 199 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_economics/functions.py b/packages/dtocean-economics/src/dtocean_economics/functions.py index eb32fe6f..386b8652 100644 --- a/packages/dtocean-economics/src/dtocean_economics/functions.py +++ b/packages/dtocean-economics/src/dtocean_economics/functions.py @@ -56,7 +56,6 @@ def get_discounted_values(values_df: pd.DataFrame, discount_rate): for _, value_series in values_df.items(): present_values = get_present_values(value_series, years, discount_rate) - discounted_value = present_values.sum() discounted_values.append(discounted_value) @@ -64,9 +63,7 @@ def get_discounted_values(values_df: pd.DataFrame, discount_rate): def get_lcoe(discounted_cost, discounted_energy): - lcoe = discounted_cost.astype(float) / discounted_energy - - return lcoe + return discounted_cost.astype(float) / discounted_energy def get_phase_breakdown(bom): diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 4f5d9836..a53ffe93 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -28,6 +28,8 @@ .. moduleauthor:: Mathew Topper """ +from typing import Any, Optional + import numpy as np import pandas as pd @@ -481,7 +483,14 @@ def connect(self, debug_entry=False): energy_record, self.data.discount_rate, ) - + self._process_result(result, opex_bom, energy_record) + + def _process_result( + self, + result: dict[str, Optional[Any]], + opex_bom: pd.DataFrame, + energy_record: pd.DataFrame, + ): discounted_capex = result["Discounted CAPEX"] assert discounted_capex is not None @@ -494,41 +503,10 @@ def connect(self, debug_entry=False): self.data.capex_total - self.data.externalities_capex ) - # Build metrics table if possible - n_rows = None - - if not opex_bom.empty: - n_rows = len(opex_bom.columns) - 1 - elif not energy_record.empty: - n_rows = len(energy_record.columns) - 1 - else: + metrics_table = _get_metrics_table(result, opex_bom, energy_record) + if metrics_table is None: return - table_cols = [ - "LCOE", - "LCOE CAPEX", - "LCOE OPEX", - "OPEX", - "Energy", - "Discounted OPEX", - "Discounted Energy", - ] - - metrics_dict = {} - - for col_name in table_cols: - col_result = result[col_name] - if col_result is not None: - values = col_result.values - if "Energy" in col_name: - values /= 1e3 - else: - values = [None] * n_rows - - metrics_dict[col_name] = values - - metrics_table = pd.DataFrame(metrics_dict) - self.data.economics_metrics = metrics_table # Do univariate stats on discounted metrics and optionally LCOE @@ -545,46 +523,11 @@ def connect(self, debug_entry=False): continue data = metrics_table[key].values + assert isinstance(data, np.ndarray) + arg_stats = _get_metric_stats(data, arg_root) - mean = None - mode = None - lower = None - upper = None - - # Catch one or two data points - if len(data) == 1: - mean = data[0] - - elif len(data) == 2: - assert isinstance(data, np.ndarray) - mean = data.mean() - - else: - assert isinstance(data, np.ndarray) - - try: - distribution = UniVariateKDE(data) - mean = distribution.mean() - mode = distribution.mode() - - intervals = distribution.confidence_interval(95) - - if intervals is not None: - lower = intervals[0] - upper = intervals[1] - - except np.linalg.LinAlgError: - mean = data.mean() - - arg_mean = "{}_mean".format(arg_root) - arg_mode = "{}_mode".format(arg_root) - arg_lower = "{}_lower".format(arg_root) - arg_upper = "{}_upper".format(arg_root) - - self.data[arg_mean] = mean - self.data[arg_mode] = mode - self.data[arg_lower] = lower - self.data[arg_upper] = upper + for k, v in arg_stats: + self.data[k] = v # Calculate total costs lifetime_cost_mean = result["CAPEX"] @@ -625,63 +568,24 @@ def connect(self, debug_entry=False): ): return - energy = metrics_table["Discounted Energy"] - opex = metrics_table["Discounted OPEX"] / 1000.0 - - if len(metrics_table["Discounted Energy"]) < 3: - mean_lcoe = (discounted_capex / 1000.0 + np.mean(opex)) / np.mean( - energy - ) - - self.data.lcoe_mean = mean_lcoe - discounted_opex_base = np.mean(opex) * 1000.0 - discounted_energy_base = np.mean(energy) * 10.0 - - else: - try: - distribution = BiVariateKDE(opex, energy) - except np.linalg.LinAlgError: - return - - mean_coords = distribution.mean() - self.data.lcoe_mean = ( - discounted_capex / 1000.0 + mean_coords[0] - ) / mean_coords[1] - - mode_coords = distribution.mode() - lcoe_mode = ( - discounted_capex / 1000.0 + mode_coords[0] - ) / mode_coords[1] - - self.data.lcoe_mode_opex = mode_coords[0] * 1000 - self.data.lcoe_mode_energy = mode_coords[1] - self.data.lcoe_mode = lcoe_mode - - xx, yy, pdf = distribution.pdf() - clevels = pdf_confidence_densities(pdf) - - if clevels: - cx, cy = pdf_contour_coords(xx, yy, pdf, clevels[0]) - - lcoes = [] - - for discounted_opex, discounted_energy in zip(cx, cy): - lcoe = ( - discounted_capex / 1000.0 + discounted_opex - ) / discounted_energy - lcoes.append(lcoe) - - self.data.confidence_density = clevels[0] - self.data.lcoe_lower = min(lcoes) - self.data.lcoe_upper = max(lcoes) + lcoe_metrics = _get_lcoe(metrics_table, discounted_capex) + if lcoe_metrics is None: + return - # LCOE distribution - raw = {"values": pdf, "coords": [xx, yy]} + self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] + discounted_opex_base = lcoe_metrics["discounted_opex_base"] + discounted_energy_base = lcoe_metrics["discounted_energy_base"] - self.data.lcoe_pdf = raw + if "lcoe_mode" in lcoe_metrics: + self.data.lcoe_mode = lcoe_metrics["lcoe_mode"] + self.data.lcoe_mode_opex = lcoe_metrics["lcoe_mode_opex"] + self.data.lcoe_mode_energy = lcoe_metrics["lcoe_mode_energy"] + self.data.lcoe_pdf = lcoe_metrics["lcoe_pdf"] - discounted_opex_base = mode_coords[0] * 1000.0 - discounted_energy_base = mode_coords[1] * 10.0 + if "confidence_density" in lcoe_metrics: + self.data.confidence_density = lcoe_metrics["confidence_density"] + self.data.lcoe_lower = lcoe_metrics["lcoe_lower"] + self.data.lcoe_upper = lcoe_metrics["lcoe_upper"] # Calculate values using most likely OPEX / Energy combination @@ -695,23 +599,16 @@ def connect(self, debug_entry=False): if self.data.externalities_opex is None: discounted_maintenance = discounted_opex_base - else: - years = range(1, len(opex_bom) + 1) - - discounted_externals = [ - self.data.externalities_opex - / (1 + self.data.discount_rate) ** i - for i in years - ] - - discounted_external = np.array(discounted_externals).sum() - discounted_maintenance = discounted_opex_base - discounted_external - - self.data.opex_breakdown = { - "Maintenance": discounted_external, - "Externalities": discounted_maintenance, - } + opex_breakdown = _get_opex_breakdown( + opex_bom, + self.data.externalities_opex, + discounted_opex_base, + self.data.discount_rate, + ) + self.data.opex_breakdown = opex_breakdown + discounted_maintenance = opex_breakdown["Maintenance"] + discounted_external = opex_breakdown["Externalities"] # LCOE Breakdowns in cent/kWh @@ -746,3 +643,170 @@ def connect(self, debug_entry=False): self.data.lcoe_breakdown = {"CAPEX": total_capex, "OPEX": total_opex} return + + +def _get_metrics_table( + result: dict[str, Optional[Any]], + opex_bom: pd.DataFrame, + energy_record: pd.DataFrame, +) -> Optional[pd.DataFrame]: + # Build metrics table if possible + n_rows = None + + if not opex_bom.empty: + n_rows = len(opex_bom.columns) - 1 + elif not energy_record.empty: + n_rows = len(energy_record.columns) - 1 + else: + return + + table_cols = [ + "LCOE", + "LCOE CAPEX", + "LCOE OPEX", + "OPEX", + "Energy", + "Discounted OPEX", + "Discounted Energy", + ] + + metrics_dict = {} + + for col_name in table_cols: + col_result = result[col_name] + if col_result is not None: + values = col_result.values + if "Energy" in col_name: + values /= 1e3 + else: + values = [None] * n_rows + + metrics_dict[col_name] = values + + return pd.DataFrame(metrics_dict) + + +def _get_metric_stats(data: np.ndarray, arg_root: str): + mean = None + mode = None + lower = None + upper = None + + # Catch one or two data points + if len(data) == 1: + mean = data[0] + + elif len(data) == 2: + assert isinstance(data, np.ndarray) + mean = data.mean() + + else: + assert isinstance(data, np.ndarray) + + try: + distribution = UniVariateKDE(data) + mean = distribution.mean() + mode = distribution.mode() + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + lower = intervals[0] + upper = intervals[1] + + except np.linalg.LinAlgError: + mean = data.mean() + + arg_mean = "{}_mean".format(arg_root) + arg_mode = "{}_mode".format(arg_root) + arg_lower = "{}_lower".format(arg_root) + arg_upper = "{}_upper".format(arg_root) + + return { + arg_mean: mean, + arg_mode: mode, + arg_lower: lower, + arg_upper: upper, + } + + +def _get_lcoe(metrics_table, discounted_capex): + result = {} + + energy = metrics_table["Discounted Energy"] + opex = metrics_table["Discounted OPEX"] / 1000.0 + + if len(metrics_table["Discounted Energy"]) < 3: + mean_lcoe = (discounted_capex / 1000.0 + np.mean(opex)) / np.mean( + energy + ) + + result["lcoe_mean"] = mean_lcoe + result["discounted_opex_base"] = np.mean(opex) * 1000.0 + result["discounted_energy_base"] = np.mean(energy) * 10.0 + + return result + + try: + distribution = BiVariateKDE(opex, energy) + except np.linalg.LinAlgError: + return + + mean_coords = distribution.mean() + result["lcoe_mean"] = ( + discounted_capex / 1000.0 + mean_coords[0] + ) / mean_coords[1] + + mode_coords = distribution.mode() + result["lcoe_mode"] = ( + discounted_capex / 1000.0 + mode_coords[0] + ) / mode_coords[1] + + result["lcoe_mode_opex"] = mode_coords[0] * 1000 + result["lcoe_mode_energy"] = mode_coords[1] + + xx, yy, pdf = distribution.pdf() + clevels = pdf_confidence_densities(pdf) + + if clevels: + cx, cy = pdf_contour_coords(xx, yy, pdf, clevels[0]) + + lcoes = [] + + for discounted_opex, discounted_energy in zip(cx, cy): + lcoe = ( + discounted_capex / 1000.0 + discounted_opex + ) / discounted_energy + lcoes.append(lcoe) + + result["confidence_density"] = clevels[0] + result["lcoe_lower"] = min(lcoes) + result["lcoe_upper"] = max(lcoes) + + # LCOE distribution + result["lcoe_pdf"] = {"values": pdf, "coords": [xx, yy]} + result["discounted_opex_base"] = mode_coords[0] * 1000.0 + result["discounted_energy_base"] = mode_coords[1] * 10.0 + + return result + + +def _get_opex_breakdown( + opex_bom, + externalities_opex, + discounted_opex_base, + discount_rate, +): + years = range(1, len(opex_bom) + 1) + + discounted_externals = [ + externalities_opex / (1 + discount_rate) ** i for i in years + ] + + discounted_external = np.array(discounted_externals).sum() + discounted_maintenance = discounted_opex_base - discounted_external + + return { + "Maintenance": discounted_maintenance, + "Externalities": discounted_external, + } diff --git a/packages/dtocean-economics/tests/dtocean_economics/conftest.py b/packages/dtocean-economics/tests/dtocean_economics/conftest.py index d7a309fc..50bb8d97 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/conftest.py +++ b/packages/dtocean-economics/tests/dtocean_economics/conftest.py @@ -5,45 +5,56 @@ @author: mtopper """ -import pytest import pandas as pd +import pytest + +YEAR_ONE = 6 / 5 +YEAR_TWO = 36 / 25 +YEAR_THREE = 216 / 125 @pytest.fixture(scope="module") def bom(): - - bom_dict = {'phase': [None, None, None, "Test", "Test", "Test"], - 'unitary_cost': [0.0, 100000.0, 100000.0, 1, 1, 1], - 'project_year': [0, 1, 2, 0, 1, 2], - 'quantity': [1, 1, 1, 1, 10, 20] - } - + bom_dict = { + "phase": [None, None, None, "Test", "Test", "Test"], + "unitary_cost": [ + 100, + YEAR_ONE * 100, + YEAR_TWO * 100, + 1, + YEAR_ONE, + YEAR_TWO, + ], + "project_year": [0, 1, 2, 0, 1, 2], + "quantity": [1, 1, 1, 1, 10, 20], + } + bom_df = pd.DataFrame(bom_dict) - + return bom_df @pytest.fixture(scope="module") def energy_record(): - - energy_dict = {'project_year': [0, 1, 2, 3, 4, 5], - 'energy 0': [0, 1, 2, 0, 10, 20], - 'energy 1': [0, 1, 32, 0, 0, 20] - } - + energy_dict = { + "project_year": [0, 1, 2, 3], + "energy 0": [1, YEAR_ONE, YEAR_TWO, YEAR_THREE], + "energy 1": [10, YEAR_ONE * 10, YEAR_TWO * 10, YEAR_THREE * 10], + } + energy_df = pd.DataFrame(energy_dict) - + return energy_df @pytest.fixture(scope="module") def opex_costs(): - - opex_dict = {'project_year': [0, 1, 2, 3, 4, 5], - 'cost 0': [0.0, 100000.0, 100000.0, 1, 1, 1], - 'cost 1': [0.0, 100000.0, 0, 1, 1, 100000.0] - } - + opex_dict = { + "project_year": [0, 1, 2, 3], + "cost 0": [1, YEAR_ONE, YEAR_TWO, YEAR_THREE], + "cost 1": [10, YEAR_ONE * 10, YEAR_TWO * 10, YEAR_THREE * 10], + } + opex_df = pd.DataFrame(opex_dict) - + return opex_df diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py index 2ca07389..730b6787 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -43,34 +43,26 @@ def test_get_combined_lcoe_capex(capex, opex, expected): assert result == expected -@pytest.mark.parametrize( - "test_input, expected", - [ - (0.0, 200031), - (0.1, 173580.34), - (0.2, 152801), - ], -) -def test_get_discounted_values(bom, test_input, expected): +def test_get_discounted_values(bom): costs_df = costs_from_bom(bom) - result = get_discounted_values(costs_df, test_input) + result = get_discounted_values(costs_df, 1 / 5) - assert np.isclose(result.iloc[0], expected) + assert np.isclose(result.iloc[0], 331) def test_get_lcoe(): result = get_lcoe(np.array([1]), np.array([10])) - assert np.isclose(result[0], 0.1) def test_get_phase_breakdown(bom): result = get_phase_breakdown(bom) + print(result) assert result is not None assert set(result.keys()) == set(["Test", "Other"]) - assert result["Test"] == 31.0 - assert result["Other"] == 200000.0 + assert result["Test"] == 41.8 + assert result["Other"] == 364 def test_get_phase_breakdown_none(bom): @@ -81,18 +73,12 @@ def test_get_phase_breakdown_none(bom): assert result is None -@pytest.mark.parametrize( - "test_input, expected", - [ - (0.0, [0, 10, 20]), - (0.1, [0, 9.0909, 16.5289]), - (0.2, [0, 8.3333, 13.8888]), - ], -) -def test_get_present_values(test_input, expected): - value = np.array([0, 10, 20]) - year = np.array([0, 1, 2]) +def test_get_present_values(): + value = np.array([1, 6 / 5, 36 / 25, 216 / 125]) + year = np.array([0, 1, 2, 3]) + dr = 1 / 5 + expected = np.array([1, 1, 1, 1]) - result = get_present_values(value, year, test_input) + result = get_present_values(value, year, dr) assert np.isclose(result, expected).all() diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_main.py b/packages/dtocean-economics/tests/dtocean_economics/test_main.py index 01f530b4..5623e299 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_main.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_main.py @@ -15,14 +15,47 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +import numpy as np + from dtocean_economics import main def test_main(bom, opex_costs, energy_record): - result = main(bom, opex_costs, energy_record) + result = main(bom, opex_costs, energy_record, 1 / 5) + import pprint + + pprint.pprint(result) + assert result["CAPEX"] == 405.8 + + breakdown = result["CAPEX breakdown"] + assert breakdown is not None + assert breakdown["Test"] == 41.8 + assert breakdown["Other"] == 364 + + assert result["Discounted CAPEX"] == 331 + + expected = 1 + 6 / 5 + 36 / 25 + 216 / 125 + + assert result["OPEX"] is not None + assert np.isclose(result["OPEX"], [expected, 10 * expected]).all() + + assert result["Energy"] is not None + assert np.isclose(result["Energy"], [expected, 10 * expected]).all() + + assert result["Discounted OPEX"] is not None + assert np.isclose(result["Discounted OPEX"], [4, 40]).all() + + assert result["Discounted Energy"] is not None + assert np.isclose(result["Discounted Energy"], [4, 40]).all() + + assert result["LCOE CAPEX"] is not None + assert np.isclose(result["LCOE CAPEX"], [331 / 4, 331 / 40]).all() + + assert result["LCOE OPEX"] is not None + assert np.isclose(result["LCOE OPEX"], [1, 1]).all() - for value in result.values(): - assert value is not None + assert result["LCOE"] is not None + assert np.isclose(result["LCOE"], [335 / 4, 371 / 40]).all() def test_main_no_capex(bom, opex_costs, energy_record): From c3723e1c582edf94ab317839fd9f212c597ba04c Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Tue, 31 Mar 2026 14:47:50 +0100 Subject: [PATCH 07/40] Try and fix some of the units madness I'm considering removing the main module entirely and just calling the functions individually. --- .../src/dtocean_economics/functions.py | 14 +- .../src/dtocean_economics/main.py | 49 +++++ .../src/dtocean_economics/preprocessing.py | 6 +- .../src/dtocean_plugins/themes/economics.py | 169 +++++++++--------- 4 files changed, 139 insertions(+), 99 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_economics/functions.py b/packages/dtocean-economics/src/dtocean_economics/functions.py index 386b8652..079a566c 100644 --- a/packages/dtocean-economics/src/dtocean_economics/functions.py +++ b/packages/dtocean-economics/src/dtocean_economics/functions.py @@ -41,11 +41,8 @@ def get_combined_lcoe(lcoe_capex=None, lcoe_opex=None): def costs_from_bom(bom): costs = bom["quantity"] * bom["unitary_cost"] - costs_dict = {"project_year": bom["project_year"].values, "costs": costs} - costs_df = pd.DataFrame(costs_dict) - - return costs_df + return pd.DataFrame(costs_dict) def get_discounted_values(values_df: pd.DataFrame, discount_rate): @@ -96,13 +93,8 @@ def get_present_values(value, yr, dr): Costs could be calculated with the above function. It can be applied in an item by item basis, or on the sum by year """ - - present_value = value / ((1 + dr) ** yr) - - return present_value + return value / ((1 + dr) ** yr) def get_total_cost(bom): - result = (bom["unitary_cost"] * bom["quantity"]).sum() - - return result + return (bom["unitary_cost"] * bom["quantity"]).sum() diff --git a/packages/dtocean-economics/src/dtocean_economics/main.py b/packages/dtocean-economics/src/dtocean_economics/main.py index 540ec7f3..4718c2db 100644 --- a/packages/dtocean-economics/src/dtocean_economics/main.py +++ b/packages/dtocean-economics/src/dtocean_economics/main.py @@ -27,6 +27,8 @@ from typing import Any, Optional +import pandas as pd + from .functions import ( costs_from_bom, get_combined_lcoe, @@ -116,3 +118,50 @@ def main(capex, opex, energy, discount_rate=None): result["LCOE"] = lcoe return result + + +def get_capex(bom: pd.DataFrame, discount_rate=0.0): + if bom.empty: + return + + breakdown = get_phase_breakdown(bom) + total = get_total_cost(bom) + + costs_df = costs_from_bom(bom) + discounted = get_discounted_values(costs_df, discount_rate) + + result = {} + if breakdown is not None: + result["CAPEX breakdown"] = breakdown + + result["CAPEX"] = total + result["Discounted CAPEX"] = discounted.iloc[0] + + return result + + +def get_opex(bom: pd.DataFrame, discount_rate=0.0): + if bom.empty: + return + + opex_by_year = bom.set_index("project_year") + total = opex_by_year.sum() + discounted = get_discounted_values(bom, discount_rate) + + result = {} + result["OPEX"] = total + result["Discounted OPEX"] = discounted + + return result + + +def get_energy(): + if energy.empty: + return result + + energy_by_year = energy.set_index("project_year") + total = energy_by_year.sum() + discounted = get_discounted_values(energy, discount_rate) + + result["Energy"] = total + result["Discounted Energy"] = discounted diff --git a/packages/dtocean-economics/src/dtocean_economics/preprocessing.py b/packages/dtocean-economics/src/dtocean_economics/preprocessing.py index 073e12dc..1b42fecd 100644 --- a/packages/dtocean-economics/src/dtocean_economics/preprocessing.py +++ b/packages/dtocean-economics/src/dtocean_economics/preprocessing.py @@ -32,17 +32,15 @@ def estimate_cost_per_power(total_rated_power, unit_cost, phase=None): def estimate_energy(lifetime, year_energy, network_efficiency=None): - # Note units of energy are kW - if network_efficiency is not None: net_coeff = network_efficiency else: net_coeff = 1.0 - energy_kw = [0] + [year_energy * net_coeff] * lifetime + energy = [0] + [year_energy * net_coeff] * lifetime energy_year = range(lifetime + 1) - raw_energy = {"energy": energy_kw, "project_year": energy_year} + raw_energy = {"energy": energy, "project_year": energy_year} energy_record = pd.DataFrame(raw_energy) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index a53ffe93..a2958668 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -455,12 +455,15 @@ def connect(self, debug_entry=False): # Prepare energy if self.data.network_efficiency is not None: - net_coeff = self.data.network_efficiency * 1e3 + net_coeff = self.data.network_efficiency else: - net_coeff = 1e3 + net_coeff = 1 - if self.data.energy_per_year is not None: - energy_record = self.data.energy_per_year.copy() + # Convert energy to Wh + MWh_to_Wh = 1e6 + + if self.data.energy_per_year is not None: # + energy_record = self.data.energy_per_year.copy() * MWh_to_Wh energy_record = energy_record * net_coeff energy_record.index.name = "project_year" energy_record = energy_record.reset_index() @@ -470,8 +473,11 @@ def connect(self, debug_entry=False): and self.data.lifetime is not None and self.data.annual_energy is not None ): + annual_energy = self.data.annual_energy * MWh_to_Wh energy_record = estimate_energy( - self.data.lifetime, self.data.annual_energy, net_coeff + self.data.lifetime, + annual_energy, + net_coeff, ) if debug_entry: @@ -483,25 +489,16 @@ def connect(self, debug_entry=False): energy_record, self.data.discount_rate, ) - self._process_result(result, opex_bom, energy_record) - def _process_result( - self, - result: dict[str, Optional[Any]], - opex_bom: pd.DataFrame, - energy_record: pd.DataFrame, - ): discounted_capex = result["Discounted CAPEX"] assert discounted_capex is not None self.data.capex_total = result["CAPEX"] self.data.discounted_capex = discounted_capex self.data.capex_breakdown = result["CAPEX breakdown"] - - if self.data.externalities_capex is not None: - self.data.capex_no_externalities = ( - self.data.capex_total - self.data.externalities_capex - ) + self.data.capex_no_externalities = _get_capex_no_externalities( + self.data.externalities_capex, self.data.capex_total + ) metrics_table = _get_metrics_table(result, opex_bom, energy_record) if metrics_table is None: @@ -512,14 +509,14 @@ def _process_result( # Do univariate stats on discounted metrics and optionally LCOE args_table = {"Discounted Energy": "discounted_energy"} - if metrics_table["Discounted OPEX"].isnull().any(): + if result["Discounted OPEX"] is None: args_table["LCOE"] = "lcoe" else: args_table["Discounted OPEX"] = "discounted_opex" args_table["OPEX"] = "lifetime_opex" for key, arg_root in args_table.items(): - if metrics_table[key].isnull().any(): + if result[key] is None: continue data = metrics_table[key].values @@ -529,38 +526,18 @@ def _process_result( for k, v in arg_stats: self.data[k] = v - # Calculate total costs - lifetime_cost_mean = result["CAPEX"] - lifetime_cost_mode = result["CAPEX"] - lifetime_discounted_cost_mean = discounted_capex - lifetime_discounted_cost_mode = discounted_capex - - if self.data.lifetime_opex_mean is not None: - if lifetime_cost_mean is None: - lifetime_cost_mean = 0 - lifetime_cost_mean += self.data.lifetime_opex_mean - - if self.data.lifetime_opex_mode is not None: - if lifetime_cost_mode is None: - lifetime_cost_mode = 0 - lifetime_cost_mode += self.data.lifetime_opex_mode - - self.data.lifetime_cost_mean = lifetime_cost_mean - self.data.lifetime_cost_mode = lifetime_cost_mode - - # Calculate total discounted costs - if self.data.discounted_opex_mean is not None: - if lifetime_discounted_cost_mean is None: - lifetime_discounted_cost_mean = 0 - lifetime_discounted_cost_mean += self.data.discounted_opex_mean - - if self.data.discounted_opex_mode is not None: - if lifetime_discounted_cost_mode is None: - lifetime_discounted_cost_mode = 0 - lifetime_discounted_cost_mode += self.data.discounted_opex_mode - - self.data.discounted_lifetime_cost_mean = lifetime_discounted_cost_mean - self.data.discounted_lifetime_cost_mode = lifetime_discounted_cost_mode + self.data.lifetime_cost_mean = _get_lifetime_cost( + result["CAPEX"], self.data.lifetime_opex_mean + ) + self.data.lifetime_cost_mode = _get_lifetime_cost( + result["CAPEX"], self.data.lifetime_opex_mode + ) + self.data.discounted_lifetime_cost_mean = _get_lifetime_cost( + discounted_capex, self.data.discounted_opex_mean + ) + self.data.discounted_lifetime_cost_mode = _get_lifetime_cost( + discounted_capex, self.data.discounted_opex_mode + ) if ( metrics_table["Discounted Energy"].isnull().any() @@ -568,6 +545,24 @@ def _process_result( ): return + energy = result["Discounted Energy"] + opex = result["Discounted OPEX"] + + if len(metrics_table["Discounted Energy"]) < 3: + lcoe_basic = _get_lcoe_basic(discounted_capex, opex, energy) + + lcoe_metrics = _get_lcoe(metrics_table, discounted_capex) + if lcoe_metrics is None: + return + + self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] + + def _process_result( + self, + result: dict[str, Optional[Any]], + opex_bom: pd.DataFrame, + energy_record: pd.DataFrame, + ): lcoe_metrics = _get_lcoe(metrics_table, discounted_capex) if lcoe_metrics is None: return @@ -660,24 +655,22 @@ def _get_metrics_table( else: return - table_cols = [ - "LCOE", - "LCOE CAPEX", - "LCOE OPEX", - "OPEX", - "Energy", - "Discounted OPEX", - "Discounted Energy", + table_cols_and_conversion = [ + ("LCOE", 1e-3), # from Euro/Wh to Euro/kWh + ("LCOE CAPEX", 1e-3), # from Euro/Wh to Euro/kWh + ("LCOE OPEX", 1e-3), # from Euro/Wh to Euro/kWh + ("OPEX", 1), + ("Energy", 1e-6), # from Wh to MWh + ("Discounted OPEX", 1), + ("Discounted Energy", 1e-6), # from Wh to MWh ] metrics_dict = {} - for col_name in table_cols: + for col_name, factor in table_cols_and_conversion: col_result = result[col_name] if col_result is not None: - values = col_result.values - if "Energy" in col_name: - values /= 1e3 + values = col_result.values * factor else: values = [None] * n_rows @@ -730,22 +723,19 @@ def _get_metric_stats(data: np.ndarray, arg_root: str): } -def _get_lcoe(metrics_table, discounted_capex): - result = {} +def _get_lcoe_basic(capex, opex, energy): + mean_lcoe = (capex / 1000.0 + np.mean(opex)) / np.mean(energy) - energy = metrics_table["Discounted Energy"] - opex = metrics_table["Discounted OPEX"] / 1000.0 + result = {} + result["lcoe_mean"] = mean_lcoe + result["discounted_opex_base"] = np.mean(opex) * 1000.0 + result["discounted_energy_base"] = np.mean(energy) * 10.0 - if len(metrics_table["Discounted Energy"]) < 3: - mean_lcoe = (discounted_capex / 1000.0 + np.mean(opex)) / np.mean( - energy - ) + return result - result["lcoe_mean"] = mean_lcoe - result["discounted_opex_base"] = np.mean(opex) * 1000.0 - result["discounted_energy_base"] = np.mean(energy) * 10.0 - return result +def _get_lcoe_kde(capex, opex, energy): + result = {} try: distribution = BiVariateKDE(opex, energy) @@ -753,14 +743,10 @@ def _get_lcoe(metrics_table, discounted_capex): return mean_coords = distribution.mean() - result["lcoe_mean"] = ( - discounted_capex / 1000.0 + mean_coords[0] - ) / mean_coords[1] + result["lcoe_mean"] = (capex / 1000.0 + mean_coords[0]) / mean_coords[1] mode_coords = distribution.mode() - result["lcoe_mode"] = ( - discounted_capex / 1000.0 + mode_coords[0] - ) / mode_coords[1] + result["lcoe_mode"] = (capex / 1000.0 + mode_coords[0]) / mode_coords[1] result["lcoe_mode_opex"] = mode_coords[0] * 1000 result["lcoe_mode_energy"] = mode_coords[1] @@ -774,9 +760,7 @@ def _get_lcoe(metrics_table, discounted_capex): lcoes = [] for discounted_opex, discounted_energy in zip(cx, cy): - lcoe = ( - discounted_capex / 1000.0 + discounted_opex - ) / discounted_energy + lcoe = (capex / 1000.0 + discounted_opex) / discounted_energy lcoes.append(lcoe) result["confidence_density"] = clevels[0] @@ -810,3 +794,20 @@ def _get_opex_breakdown( "Maintenance": discounted_maintenance, "Externalities": discounted_external, } + + +def _get_capex_no_externalities(externalities_capex, capex_total): + if externalities_capex is None: + return + return capex_total - externalities_capex + + +def _get_lifetime_cost(capex, lifetime_opex): + lifetime_cost = capex + + if lifetime_opex is not None: + if lifetime_cost is None: + lifetime_cost = 0 + lifetime_cost += lifetime_opex + + return lifetime_cost From 05297d50854d54af6062bda5864a3eb364c1fd69 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Wed, 1 Apr 2026 12:21:59 +0100 Subject: [PATCH 08/40] Continue with tidy up --- .../src/dtocean_economics/__init__.py | 99 ++++++- .../src/dtocean_plugins/themes/economics.py | 256 +++++++++++------- 2 files changed, 257 insertions(+), 98 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_economics/__init__.py b/packages/dtocean-economics/src/dtocean_economics/__init__.py index 34e004e5..b5ab3c5f 100644 --- a/packages/dtocean-economics/src/dtocean_economics/__init__.py +++ b/packages/dtocean-economics/src/dtocean_economics/__init__.py @@ -16,6 +16,103 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +from typing import Optional + +import pandas as pd + from .main import main -__all__ = ["main"] + +def costs_from_bom(bom): + costs = bom["quantity"] * bom["unitary_cost"] + costs_dict = {"project_year": bom["project_year"].values, "costs": costs} + return pd.DataFrame(costs_dict) + + +def get_discounted_values(values_df: pd.DataFrame, discount_rate): + years = values_df["project_year"] + values_df = values_df.set_index("project_year") + + discounted_values = [] + + for _, value_series in values_df.items(): + present_values = get_present_values(value_series, years, discount_rate) + discounted_value = present_values.sum() + discounted_values.append(discounted_value) + + return pd.Series(discounted_values) + + +def get_phase_breakdown(bom): + # Check for null phases + null_phases = pd.isnull(bom["phase"]) + + # No breakdown available + if null_phases.all(): + return None + + # Replace any null phase values + bom.loc[pd.isnull(bom["phase"]), "phase"] = "Other" + + phase_groups = bom.groupby("phase") + + phase_breakdown = {} + + for phase_name, phase_bom in phase_groups: + phase_cost = get_total_cost(phase_bom) + phase_breakdown[phase_name] = phase_cost + + return phase_breakdown + + +def get_present_values(value, yr, dr): + """ + Function to calculate present value + It should be applied to a table with costs and year cost occurs, and to + energy output table + Costs could be calculated with the above function. + It can be applied in an item by item basis, or on the sum by year + """ + return value / ((1 + dr) ** yr) + + +def get_total_cost(bom): + return (bom["unitary_cost"] * bom["quantity"]).sum() + + +def get_metrics_table( + opex_bom: pd.DataFrame, + energy_record: pd.DataFrame, +) -> Optional[pd.DataFrame]: + # Build metrics table if possible + n_rows = None + + if not opex_bom.empty: + n_rows = len(opex_bom.columns) - 1 + elif not energy_record.empty: + n_rows = len(energy_record.columns) - 1 + else: + return + + table_cols_and_conversion = [ + ("LCOE", 1e-3), # from Euro/Wh to Euro/kWh + ("LCOE CAPEX", 1e-3), # from Euro/Wh to Euro/kWh + ("LCOE OPEX", 1e-3), # from Euro/Wh to Euro/kWh + ("OPEX", 1), + ("Energy", 1e-6), # from Wh to MWh + ("Discounted OPEX", 1), + ("Discounted Energy", 1e-6), # from Wh to MWh + ] + + metrics_dict = {} + + for col_name, factor in table_cols_and_conversion: + col_result = result[col_name] + if col_result is not None: + values = col_result.values * factor + else: + values = [None] * n_rows + + metrics_dict[col_name] = values + + return pd.DataFrame(metrics_dict) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index a2958668..69c22675 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -33,7 +33,12 @@ import numpy as np import pandas as pd -from dtocean_economics import main +from dtocean_economics import ( + costs_from_bom, + get_discounted_values, + get_phase_breakdown, + get_total_cost, +) from dtocean_economics.preprocessing import ( estimate_cost_per_power, estimate_energy, @@ -483,7 +488,7 @@ def connect(self, debug_entry=False): if debug_entry: return - result = main( + outputs = _get_outputs( capex_bom, opex_bom, energy_record, @@ -557,126 +562,183 @@ def connect(self, debug_entry=False): self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] - def _process_result( - self, - result: dict[str, Optional[Any]], - opex_bom: pd.DataFrame, - energy_record: pd.DataFrame, - ): - lcoe_metrics = _get_lcoe(metrics_table, discounted_capex) - if lcoe_metrics is None: - return - self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] - discounted_opex_base = lcoe_metrics["discounted_opex_base"] - discounted_energy_base = lcoe_metrics["discounted_energy_base"] - - if "lcoe_mode" in lcoe_metrics: - self.data.lcoe_mode = lcoe_metrics["lcoe_mode"] - self.data.lcoe_mode_opex = lcoe_metrics["lcoe_mode_opex"] - self.data.lcoe_mode_energy = lcoe_metrics["lcoe_mode_energy"] - self.data.lcoe_pdf = lcoe_metrics["lcoe_pdf"] - - if "confidence_density" in lcoe_metrics: - self.data.confidence_density = lcoe_metrics["confidence_density"] - self.data.lcoe_lower = lcoe_metrics["lcoe_lower"] - self.data.lcoe_upper = lcoe_metrics["lcoe_upper"] - - # Calculate values using most likely OPEX / Energy combination - - # CAPEX vs OPEX Breakdown and OPEX Breakdown if externalities - breakdown = { - "Discounted CAPEX": discounted_capex, - "Discounted OPEX": discounted_opex_base, - } +def _get_outputs( + capex_bom: pd.DataFrame, + opex_bom: pd.DataFrame, + energy_record: pd.DataFrame, + discount_rate: float, +): + outputs: dict[str, Any] = { + "capex_breakdown": None, + "capex_total": None, + "discounted_capex": None, + "economics_metrics": None, + } - self.data.cost_breakdown = breakdown + discounted_capex = None + discounted_opex = None + lcoe_capex = None + lcoe_opex = None + lcoe_total = None + + if not capex_bom.empty: + costs_df = costs_from_bom(capex_bom) + discounted_capex = get_discounted_values( + costs_df, + discount_rate, + ) - if self.data.externalities_opex is None: - discounted_maintenance = discounted_opex_base - else: - opex_breakdown = _get_opex_breakdown( - opex_bom, - self.data.externalities_opex, - discounted_opex_base, - self.data.discount_rate, - ) - self.data.opex_breakdown = opex_breakdown - discounted_maintenance = opex_breakdown["Maintenance"] - discounted_external = opex_breakdown["Externalities"] + outputs["capex_total"] = get_total_cost(capex_bom) + outputs["capex_breakdown"] = get_phase_breakdown(capex_bom) + outputs["discounted_capex"] = discounted_capex.iloc[0] - # LCOE Breakdowns in cent/kWh + if not opex_bom.empty: + opex_by_year = opex_bom.set_index("project_year") + opex_total = opex_by_year.sum() + discounted_opex = get_discounted_values(opex_bom, discount_rate) + + if not energy_record.empty: + energy_by_year = energy_record.set_index("project_year") + energy_total = energy_by_year.sum() + discounted_energy = get_discounted_values(energy_record, discount_rate) + + if discounted_capex is not None: + lcoe_capex = discounted_capex / discounted_energy + lcoe_total = lcoe_capex + + if discounted_opex is not None: + lcoe_opex = discounted_opex / discounted_energy + if lcoe_total is None: + lcoe_total = lcoe_opex + else: + lcoe_total += lcoe_opex + + metrics_table = _get_metrics_table( + opex_total, + discounted_opex, + energy_total, + discounted_energy, + lcoe_capex, + lcoe_opex, + lcoe_total, + ) + + if metrics_table is None: + return - if self.data.capex_breakdown is not None: - capex_lcoe_breakdown = {} + outputs["economics_metrics"] = metrics_table - for k, v in self.data.capex_breakdown.iteritems(): - capex_lcoe_breakdown[k] = round(v / discounted_energy_base, 2) + lcoe_metrics = _get_lcoe(metrics_table, discounted_capex) + if lcoe_metrics is None: + return - self.data.capex_lcoe_breakdown = capex_lcoe_breakdown + self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] + discounted_opex_base = lcoe_metrics["discounted_opex_base"] + discounted_energy_base = lcoe_metrics["discounted_energy_base"] - lcoe_maintenance = round( - discounted_maintenance / discounted_energy_base, 2 - ) + if "lcoe_mode" in lcoe_metrics: + self.data.lcoe_mode = lcoe_metrics["lcoe_mode"] + self.data.lcoe_mode_opex = lcoe_metrics["lcoe_mode_opex"] + self.data.lcoe_mode_energy = lcoe_metrics["lcoe_mode_energy"] + self.data.lcoe_pdf = lcoe_metrics["lcoe_pdf"] - if self.data.externalities_opex is None: - lcoe_external = 0 + if "confidence_density" in lcoe_metrics: + self.data.confidence_density = lcoe_metrics["confidence_density"] + self.data.lcoe_lower = lcoe_metrics["lcoe_lower"] + self.data.lcoe_upper = lcoe_metrics["lcoe_upper"] - else: - lcoe_external = round( - discounted_external / discounted_energy_base, 2 - ) + # Calculate values using most likely OPEX / Energy combination - self.data.opex_lcoe_breakdown = { - "Maintenance": lcoe_maintenance, - "Externalities": lcoe_external, - } + # CAPEX vs OPEX Breakdown and OPEX Breakdown if externalities + breakdown = { + "Discounted CAPEX": discounted_capex, + "Discounted OPEX": discounted_opex_base, + } + + self.data.cost_breakdown = breakdown + + if self.data.externalities_opex is None: + discounted_maintenance = discounted_opex_base + else: + opex_breakdown = _get_opex_breakdown( + opex_bom, + self.data.externalities_opex, + discounted_opex_base, + self.data.discount_rate, + ) + self.data.opex_breakdown = opex_breakdown + discounted_maintenance = opex_breakdown["Maintenance"] + discounted_external = opex_breakdown["Externalities"] - total_capex = sum(capex_lcoe_breakdown.values()) - total_opex = lcoe_maintenance + lcoe_external + # LCOE Breakdowns in cent/kWh - self.data.lcoe_breakdown = {"CAPEX": total_capex, "OPEX": total_opex} + if self.data.capex_breakdown is not None: + capex_lcoe_breakdown = {} - return + for k, v in self.data.capex_breakdown.iteritems(): + capex_lcoe_breakdown[k] = round(v / discounted_energy_base, 2) + self.data.capex_lcoe_breakdown = capex_lcoe_breakdown -def _get_metrics_table( - result: dict[str, Optional[Any]], - opex_bom: pd.DataFrame, - energy_record: pd.DataFrame, -) -> Optional[pd.DataFrame]: - # Build metrics table if possible - n_rows = None + lcoe_maintenance = round(discounted_maintenance / discounted_energy_base, 2) + + if self.data.externalities_opex is None: + lcoe_external = 0 - if not opex_bom.empty: - n_rows = len(opex_bom.columns) - 1 - elif not energy_record.empty: - n_rows = len(energy_record.columns) - 1 else: - return + lcoe_external = round(discounted_external / discounted_energy_base, 2) + + self.data.opex_lcoe_breakdown = { + "Maintenance": lcoe_maintenance, + "Externalities": lcoe_external, + } + + total_capex = sum(capex_lcoe_breakdown.values()) + total_opex = lcoe_maintenance + lcoe_external + + self.data.lcoe_breakdown = {"CAPEX": total_capex, "OPEX": total_opex} + return + + +def _get_metrics_table( + opex_total: Optional[pd.Series], + discounted_opex: Optional[pd.Series], + energy_total: Optional[pd.Series], + discounted_energy: Optional[pd.Series], + lcoe_capex: Optional[pd.Series], + lcoe_opex: Optional[pd.Series], + lcoe_total: Optional[pd.Series], +) -> Optional[pd.DataFrame]: table_cols_and_conversion = [ - ("LCOE", 1e-3), # from Euro/Wh to Euro/kWh - ("LCOE CAPEX", 1e-3), # from Euro/Wh to Euro/kWh - ("LCOE OPEX", 1e-3), # from Euro/Wh to Euro/kWh - ("OPEX", 1), - ("Energy", 1e-6), # from Wh to MWh - ("Discounted OPEX", 1), - ("Discounted Energy", 1e-6), # from Wh to MWh + ("LCOE", lcoe_total, 1e-3), # from Euro/Wh to Euro/kWh + ("LCOE CAPEX", lcoe_capex, 1e-3), # from Euro/Wh to Euro/kWh + ("LCOE OPEX", lcoe_opex, 1e-3), # from Euro/Wh to Euro/kWh + ("OPEX", opex_total, 1), + ("Energy", energy_total, 1e-6), # from Wh to MWh + ("Discounted OPEX", discounted_opex, 1), + ("Discounted Energy", discounted_energy, 1e-6), # from Wh to MWh ] - + missing_cols = [] metrics_dict = {} - for col_name, factor in table_cols_and_conversion: - col_result = result[col_name] - if col_result is not None: - values = col_result.values * factor - else: - values = [None] * n_rows + for col_name, col_result, factor in table_cols_and_conversion: + if col_result is None: + missing_cols.append(col_name) + continue + + metrics_dict[col_name] = col_result.values * factor + + metrics = pd.DataFrame(metrics_dict) + if len(metrics) is None: + return - metrics_dict[col_name] = values + # Set columns with missing data + for col_name in missing_cols: + metrics[missing_cols] = np.nan - return pd.DataFrame(metrics_dict) + return metrics def _get_metric_stats(data: np.ndarray, arg_root: str): From b33bf1e2c620861e6ff14b6c5ffe0d561413f4b5 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Wed, 1 Apr 2026 12:22:21 +0100 Subject: [PATCH 09/40] Some other stuff --- .../src/dtocean_economics/functions.py | 63 ------------------- 1 file changed, 63 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_economics/functions.py b/packages/dtocean-economics/src/dtocean_economics/functions.py index 079a566c..2e704c6f 100644 --- a/packages/dtocean-economics/src/dtocean_economics/functions.py +++ b/packages/dtocean-economics/src/dtocean_economics/functions.py @@ -25,8 +25,6 @@ .. moduleauthor:: Mathew Topper """ -import pandas as pd - def get_combined_lcoe(lcoe_capex=None, lcoe_opex=None): if lcoe_capex is not None and lcoe_opex is not None: @@ -37,64 +35,3 @@ def get_combined_lcoe(lcoe_capex=None, lcoe_opex=None): lcoe = lcoe_opex return lcoe - - -def costs_from_bom(bom): - costs = bom["quantity"] * bom["unitary_cost"] - costs_dict = {"project_year": bom["project_year"].values, "costs": costs} - return pd.DataFrame(costs_dict) - - -def get_discounted_values(values_df: pd.DataFrame, discount_rate): - years = values_df["project_year"] - values_df = values_df.set_index("project_year") - - discounted_values = [] - - for _, value_series in values_df.items(): - present_values = get_present_values(value_series, years, discount_rate) - discounted_value = present_values.sum() - discounted_values.append(discounted_value) - - return pd.Series(discounted_values) - - -def get_lcoe(discounted_cost, discounted_energy): - return discounted_cost.astype(float) / discounted_energy - - -def get_phase_breakdown(bom): - # Check for null phases - null_phases = pd.isnull(bom["phase"]) - - # No breakdown available - if null_phases.all(): - return None - - # Replace any null phase values - bom.loc[pd.isnull(bom["phase"]), "phase"] = "Other" - - phase_groups = bom.groupby("phase") - - phase_breakdown = {} - - for phase_name, phase_bom in phase_groups: - phase_cost = get_total_cost(phase_bom) - phase_breakdown[phase_name] = phase_cost - - return phase_breakdown - - -def get_present_values(value, yr, dr): - """ - Function to calculate present value - It should be applied to a table with costs and year cost occurs, and to - energy output table - Costs could be calculated with the above function. - It can be applied in an item by item basis, or on the sum by year - """ - return value / ((1 + dr) ** yr) - - -def get_total_cost(bom): - return (bom["unitary_cost"] * bom["quantity"]).sum() From 75087ef9affc0185b1979d1fde9d2bf7c5313607 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Wed, 1 Apr 2026 16:43:36 +0100 Subject: [PATCH 10/40] Minor changes --- .../src/dtocean_plugins/themes/economics.py | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 69c22675..560337dd 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -633,6 +633,26 @@ def _get_outputs( if lcoe_metrics is None: return + # Do univariate stats on discounted metrics and optionally LCOE + args_table = {"Discounted Energy": "discounted_energy"} + + if result["Discounted OPEX"] is None: + args_table["LCOE"] = "lcoe" + else: + args_table["Discounted OPEX"] = "discounted_opex" + args_table["OPEX"] = "lifetime_opex" + + for key, arg_root in args_table.items(): + if result[key] is None: + continue + + data = metrics_table[key].values + assert isinstance(data, np.ndarray) + arg_stats = _get_metric_stats(data, arg_root) + + for k, v in arg_stats: + self.data[k] = v + self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] discounted_opex_base = lcoe_metrics["discounted_opex_base"] discounted_energy_base = lcoe_metrics["discounted_energy_base"] @@ -741,7 +761,7 @@ def _get_metrics_table( return metrics -def _get_metric_stats(data: np.ndarray, arg_root: str): +def _get_metric_stats(data: np.ndarray): mean = None mode = None lower = None @@ -772,17 +792,7 @@ def _get_metric_stats(data: np.ndarray, arg_root: str): except np.linalg.LinAlgError: mean = data.mean() - arg_mean = "{}_mean".format(arg_root) - arg_mode = "{}_mode".format(arg_root) - arg_lower = "{}_lower".format(arg_root) - arg_upper = "{}_upper".format(arg_root) - - return { - arg_mean: mean, - arg_mode: mode, - arg_lower: lower, - arg_upper: upper, - } + return {mean, mode, lower, upper} def _get_lcoe_basic(capex, opex, energy): From 655867e7e6f11d949565cb5040c4356d65e68d77 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 2 Apr 2026 12:11:39 +0100 Subject: [PATCH 11/40] Finish interface code reorganisation --- .../src/dtocean_economics/__init__.py | 41 -- .../src/dtocean_economics/functions.py | 37 -- .../src/dtocean_economics/main.py | 167 ------- .../src/dtocean_plugins/themes/economics.py | 464 +++++++++--------- 4 files changed, 244 insertions(+), 465 deletions(-) delete mode 100644 packages/dtocean-economics/src/dtocean_economics/functions.py delete mode 100644 packages/dtocean-economics/src/dtocean_economics/main.py diff --git a/packages/dtocean-economics/src/dtocean_economics/__init__.py b/packages/dtocean-economics/src/dtocean_economics/__init__.py index b5ab3c5f..5e1d2392 100644 --- a/packages/dtocean-economics/src/dtocean_economics/__init__.py +++ b/packages/dtocean-economics/src/dtocean_economics/__init__.py @@ -16,12 +16,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -from typing import Optional import pandas as pd -from .main import main - def costs_from_bom(bom): costs = bom["quantity"] * bom["unitary_cost"] @@ -78,41 +75,3 @@ def get_present_values(value, yr, dr): def get_total_cost(bom): return (bom["unitary_cost"] * bom["quantity"]).sum() - - -def get_metrics_table( - opex_bom: pd.DataFrame, - energy_record: pd.DataFrame, -) -> Optional[pd.DataFrame]: - # Build metrics table if possible - n_rows = None - - if not opex_bom.empty: - n_rows = len(opex_bom.columns) - 1 - elif not energy_record.empty: - n_rows = len(energy_record.columns) - 1 - else: - return - - table_cols_and_conversion = [ - ("LCOE", 1e-3), # from Euro/Wh to Euro/kWh - ("LCOE CAPEX", 1e-3), # from Euro/Wh to Euro/kWh - ("LCOE OPEX", 1e-3), # from Euro/Wh to Euro/kWh - ("OPEX", 1), - ("Energy", 1e-6), # from Wh to MWh - ("Discounted OPEX", 1), - ("Discounted Energy", 1e-6), # from Wh to MWh - ] - - metrics_dict = {} - - for col_name, factor in table_cols_and_conversion: - col_result = result[col_name] - if col_result is not None: - values = col_result.values * factor - else: - values = [None] * n_rows - - metrics_dict[col_name] = values - - return pd.DataFrame(metrics_dict) diff --git a/packages/dtocean-economics/src/dtocean_economics/functions.py b/packages/dtocean-economics/src/dtocean_economics/functions.py deleted file mode 100644 index 2e704c6f..00000000 --- a/packages/dtocean-economics/src/dtocean_economics/functions.py +++ /dev/null @@ -1,37 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright (C) 2016 Marta Silva, Mathew Topper -# Copyright (C) 2017-2026 Mathew Topper -# -# 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 . - -""" -Created on Thu Mar 05 16:16:39 2015 - -Functions to be used within DTOcean tool - -.. moduleauthor:: Marta Silva -.. moduleauthor:: Mathew Topper -""" - - -def get_combined_lcoe(lcoe_capex=None, lcoe_opex=None): - if lcoe_capex is not None and lcoe_opex is not None: - lcoe = lcoe_capex + lcoe_opex - elif lcoe_capex is not None: - lcoe = lcoe_capex - else: - lcoe = lcoe_opex - - return lcoe diff --git a/packages/dtocean-economics/src/dtocean_economics/main.py b/packages/dtocean-economics/src/dtocean_economics/main.py deleted file mode 100644 index 4718c2db..00000000 --- a/packages/dtocean-economics/src/dtocean_economics/main.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright (C) 2016 Marta Silva, Mathew Topper -# Copyright (C) 2017-2026 Mathew Topper -# -# 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 . - -""" -Created on Tue Mar 17 16:06:59 2015 - -Main economic analysis used within DTOcean tool - -.. moduleauthor:: Marta Silva -.. moduleauthor:: Mathew Topper -""" - -from typing import Any, Optional - -import pandas as pd - -from .functions import ( - costs_from_bom, - get_combined_lcoe, - get_discounted_values, - get_lcoe, - get_phase_breakdown, - get_total_cost, -) - - -def main(capex, opex, energy, discount_rate=None): - # Note, nominal units of energy and costs are kWs and Euro - # Year 0 represents costs prior to beginning of operations - if discount_rate is None: - discount_rate = 0.0 - - # Define the results dictionary - result: dict[str, Optional[Any]] = { - "CAPEX": None, - "Discounted CAPEX": None, - "CAPEX breakdown": None, - "OPEX": None, - "Discounted OPEX": None, - "Energy": None, - "Discounted Energy": None, - "LCOE CAPEX": None, - "LCOE OPEX": None, - "LCOE": None, - } - - ### COSTS - - # CAPEX - if not capex.empty: - breakdown = get_phase_breakdown(capex) - total = get_total_cost(capex) - - costs_df = costs_from_bom(capex) - discounted = get_discounted_values(costs_df, discount_rate) - - if breakdown is not None: - result["CAPEX breakdown"] = breakdown - - result["CAPEX"] = total - result["Discounted CAPEX"] = discounted.iloc[0] - - # OPEX - if not opex.empty: - opex_by_year = opex.set_index("project_year") - total = opex_by_year.sum() - discounted = get_discounted_values(opex, discount_rate) - - result["OPEX"] = total - result["Discounted OPEX"] = discounted - - ### ENERGY - - # Can exit if no energy records are provided - if energy.empty: - return result - - energy_by_year = energy.set_index("project_year") - total = energy_by_year.sum() - discounted = get_discounted_values(energy, discount_rate) - - result["Energy"] = total - result["Discounted Energy"] = discounted - - ### LCOE - - if result["Discounted CAPEX"] is not None: - lcoe = get_lcoe(result["Discounted CAPEX"], result["Discounted Energy"]) - - result["LCOE CAPEX"] = lcoe - - if result["Discounted OPEX"] is not None: - lcoe = get_lcoe(result["Discounted OPEX"], result["Discounted Energy"]) - - result["LCOE OPEX"] = lcoe - - # Can exit if no LCOE values were created - if result["LCOE CAPEX"] is None and result["LCOE OPEX"] is None: - return result - - lcoe = get_combined_lcoe(result["LCOE CAPEX"], result["LCOE OPEX"]) - - result["LCOE"] = lcoe - - return result - - -def get_capex(bom: pd.DataFrame, discount_rate=0.0): - if bom.empty: - return - - breakdown = get_phase_breakdown(bom) - total = get_total_cost(bom) - - costs_df = costs_from_bom(bom) - discounted = get_discounted_values(costs_df, discount_rate) - - result = {} - if breakdown is not None: - result["CAPEX breakdown"] = breakdown - - result["CAPEX"] = total - result["Discounted CAPEX"] = discounted.iloc[0] - - return result - - -def get_opex(bom: pd.DataFrame, discount_rate=0.0): - if bom.empty: - return - - opex_by_year = bom.set_index("project_year") - total = opex_by_year.sum() - discounted = get_discounted_values(bom, discount_rate) - - result = {} - result["OPEX"] = total - result["Discounted OPEX"] = discounted - - return result - - -def get_energy(): - if energy.empty: - return result - - energy_by_year = energy.set_index("project_year") - total = energy_by_year.sum() - discounted = get_discounted_values(energy, discount_rate) - - result["Energy"] = total - result["Discounted Energy"] = discounted diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 560337dd..f819206b 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -137,8 +137,6 @@ def declare_outputs(cls): output_list = [ "project.economics_metrics", - "project.lcoe_mode_opex", - "project.lcoe_mode_energy", "project.lcoe_mode", "project.lcoe_interval_lower", "project.lcoe_interval_upper", @@ -148,6 +146,8 @@ def declare_outputs(cls): "project.discounted_capex", "project.lifetime_opex_mean", "project.lifetime_opex_mode", + "project.lifetime_opex_interval_lower", + "project.lifetime_opex_interval_upper", "project.discounted_opex_mode", "project.discounted_opex_mean", "project.discounted_opex_interval_lower", @@ -253,6 +253,8 @@ def declare_id_map(cls): "energy_per_year": "project.energy_per_year", "lifetime_opex_mean": "project.lifetime_opex_mean", "lifetime_opex_mode": "project.lifetime_opex_mode", + "lifetime_opex_lower": "project.lifetime_opex_interval_lower", + "lifetime_opex_upper": "project.lifetime_opex_interval_upper", "network_efficiency": "project.electrical_network_efficiency", "externalities_capex": "project.externalities_capex", "externalities_opex": "project.externalities_opex", @@ -266,8 +268,6 @@ def declare_id_map(cls): "estimate_energy_record": "project.estimate_energy_record", "economics_metrics": "project.economics_metrics", "lcoe_mean": "project.lcoe_mean", - "lcoe_mode_opex": "project.lcoe_mode_opex", - "lcoe_mode_energy": "project.lcoe_mode_energy", "lcoe_mode": "project.lcoe_mode", "lcoe_lower": "project.lcoe_interval_lower", "lcoe_upper": "project.lcoe_interval_upper", @@ -493,74 +493,12 @@ def connect(self, debug_entry=False): opex_bom, energy_record, self.data.discount_rate, + self.data.externalities_capex, + self.data.externalities_opex, ) - discounted_capex = result["Discounted CAPEX"] - assert discounted_capex is not None - - self.data.capex_total = result["CAPEX"] - self.data.discounted_capex = discounted_capex - self.data.capex_breakdown = result["CAPEX breakdown"] - self.data.capex_no_externalities = _get_capex_no_externalities( - self.data.externalities_capex, self.data.capex_total - ) - - metrics_table = _get_metrics_table(result, opex_bom, energy_record) - if metrics_table is None: - return - - self.data.economics_metrics = metrics_table - - # Do univariate stats on discounted metrics and optionally LCOE - args_table = {"Discounted Energy": "discounted_energy"} - - if result["Discounted OPEX"] is None: - args_table["LCOE"] = "lcoe" - else: - args_table["Discounted OPEX"] = "discounted_opex" - args_table["OPEX"] = "lifetime_opex" - - for key, arg_root in args_table.items(): - if result[key] is None: - continue - - data = metrics_table[key].values - assert isinstance(data, np.ndarray) - arg_stats = _get_metric_stats(data, arg_root) - - for k, v in arg_stats: - self.data[k] = v - - self.data.lifetime_cost_mean = _get_lifetime_cost( - result["CAPEX"], self.data.lifetime_opex_mean - ) - self.data.lifetime_cost_mode = _get_lifetime_cost( - result["CAPEX"], self.data.lifetime_opex_mode - ) - self.data.discounted_lifetime_cost_mean = _get_lifetime_cost( - discounted_capex, self.data.discounted_opex_mean - ) - self.data.discounted_lifetime_cost_mode = _get_lifetime_cost( - discounted_capex, self.data.discounted_opex_mode - ) - - if ( - metrics_table["Discounted Energy"].isnull().any() - or metrics_table["Discounted OPEX"].isnull().any() - ): - return - - energy = result["Discounted Energy"] - opex = result["Discounted OPEX"] - - if len(metrics_table["Discounted Energy"]) < 3: - lcoe_basic = _get_lcoe_basic(discounted_capex, opex, energy) - - lcoe_metrics = _get_lcoe(metrics_table, discounted_capex) - if lcoe_metrics is None: - return - - self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] + for k, v in outputs: + self.data[k] = v def _get_outputs( @@ -568,14 +506,47 @@ def _get_outputs( opex_bom: pd.DataFrame, energy_record: pd.DataFrame, discount_rate: float, -): + externalities_capex: Optional[float], + externalities_opex: Optional[float], +) -> dict[str, Any]: outputs: dict[str, Any] = { "capex_breakdown": None, "capex_total": None, "discounted_capex": None, + "capex_no_externalities": None, "economics_metrics": None, + "lifetime_opex_mean": None, + "lifetime_opex_mode": None, + "lifetime_opex_lower": None, + "lifetime_opex_upper": None, + "discounted_opex_mean": None, + "discounted_opex_mode": None, + "discounted_opex_lower": None, + "discounted_opex_upper": None, + "discounted_energy_mean": None, + "discounted_energy_mode": None, + "discounted_energy_lower": None, + "discounted_energy_upper": None, + "lcoe_mean": None, + "lcoe_mode": None, + "lcoe_lower": None, + "lcoe_upper": None, + "lcoe_pdf": None, + "confidence_density": None, + "lifetime_cost_mean": None, + "lifetime_cost_mode": None, + "discounted_lifetime_cost_mean": None, + "discounted_lifetime_cost_mode": None, + "cost_breakdown": None, + "opex_breakdown": None, + "capex_lcoe_breakdown": None, + "opex_lcoe_breakdown": None, + "lcoe_breakdown": None, } + capex_total = 0 + discounted_capex_total = 0 + capex_breakdown = None discounted_capex = None discounted_opex = None lcoe_capex = None @@ -588,10 +559,18 @@ def _get_outputs( costs_df, discount_rate, ) + discounted_capex_total = discounted_capex.iloc[0] + capex_total = get_total_cost(capex_bom) + capex_breakdown = get_phase_breakdown(capex_bom) + + outputs["capex_total"] = capex_total + outputs["capex_breakdown"] = capex_breakdown + outputs["discounted_capex"] = discounted_capex_total - outputs["capex_total"] = get_total_cost(capex_bom) - outputs["capex_breakdown"] = get_phase_breakdown(capex_bom) - outputs["discounted_capex"] = discounted_capex.iloc[0] + if externalities_capex is not None: + outputs["capex_no_externalities"] = ( + capex_total - externalities_capex + ) if not opex_bom.empty: opex_by_year = opex_bom.set_index("project_year") @@ -625,50 +604,163 @@ def _get_outputs( ) if metrics_table is None: - return + return outputs outputs["economics_metrics"] = metrics_table - lcoe_metrics = _get_lcoe(metrics_table, discounted_capex) - if lcoe_metrics is None: - return + if len(metrics_table) < 3: + if opex_total is not None: + outputs["lifetime_opex_mean"] = opex_total.mean() + + if discounted_opex is not None: + outputs["discounted_opex_mean"] = discounted_opex.mean() + + if discounted_energy is not None: + # From W to MW + outputs["discounted_energy_mean"] = discounted_energy.mean() / 1e6 - # Do univariate stats on discounted metrics and optionally LCOE - args_table = {"Discounted Energy": "discounted_energy"} + if lcoe_total is not None: + # From Euro/Wh to Euro/kWh + outputs["lcoe_mean"] = lcoe_total.mean() * 1000 - if result["Discounted OPEX"] is None: - args_table["LCOE"] = "lcoe" else: - args_table["Discounted OPEX"] = "discounted_opex" - args_table["OPEX"] = "lifetime_opex" + if discounted_opex is not None and discounted_energy is not None: + try: + distribution = BiVariateKDE(discounted_opex, discounted_energy) + + mean_coords = distribution.mean() + lcoe_mean = (capex_total + mean_coords[0]) / mean_coords[1] + outputs["lcoe_mean"] = lcoe_mean * 1000 # Euro/Wh to Euro/kWh + outputs["discounted_opex_mean"] = mean_coords[0] + outputs["discounted_energy_mean"] = ( + mean_coords[1] / 1e6 + ) # W to MW + + mode_coords = distribution.mode() + lcoe_mode = (capex_total + mean_coords[0]) / mean_coords[1] + outputs["lcoe_mode"] = lcoe_mode * 1000 # Euro/Wh to Euro/kWh + outputs["discounted_opex_mode"] = mode_coords[0] + outputs["discounted_energy_mode"] = ( + mode_coords[1] / 1e6 + ) # W to MW + + xx, yy, pdf = distribution.pdf() + clevels = pdf_confidence_densities(pdf) + + # LCOE distribution + outputs["lcoe_pdf"] = {"values": pdf, "coords": [xx, yy]} + + if clevels: + outputs["confidence_density"] = clevels[0] + cx, cy = pdf_contour_coords(xx, yy, pdf, clevels[0]) + + outputs["discounted_opex_lower"] = min(cx) + outputs["discounted_energy_lower"] = ( + min(cy) / 1e6 + ) # W to MW + outputs["discounted_opex_upper"] = max(cx) + outputs["discounted_energy_upper"] = ( + max(cy) / 1e6 + ) # W to MW + + lcoes = [ + (capex_total + discounted_opex) / discounted_energy + for discounted_opex, discounted_energy in zip(cx, cy) + ] + + # Euro/Wh to Euro/kWh + outputs["lcoe_lower"] = min(lcoes) * 1000 + outputs["lcoe_upper"] = max(lcoes) * 1000 + + except np.linalg.LinAlgError: + _get_discounted_opex_stats(outputs, discounted_opex) + _get_discounted_energy_stats(outputs, discounted_energy) + + assert lcoe_total is not None + + # Euro/Wh to Euro/kWh + try: + distribution = UniVariateKDE(lcoe_total) + outputs["lcoe_mean"] = distribution.mean() * 1000 + outputs["lcoe_mode"] = distribution.mode() * 1000 + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + outputs["lcoe_lower"] = intervals[0] * 1000 + outputs["lcoe_upper"] = intervals[1] * 1000 + + except np.linalg.LinAlgError: + outputs["lcoe_mean"] = lcoe_total.mean() * 1000 - for key, arg_root in args_table.items(): - if result[key] is None: - continue + if discounted_opex is not None: + _get_discounted_opex_stats(outputs, discounted_opex) - data = metrics_table[key].values - assert isinstance(data, np.ndarray) - arg_stats = _get_metric_stats(data, arg_root) + if discounted_energy is not None: + _get_discounted_energy_stats(outputs, discounted_energy) - for k, v in arg_stats: - self.data[k] = v + if opex_total is not None: + try: + distribution = UniVariateKDE(opex_total) + outputs["lifetime_opex_mean"] = distribution.mean() + outputs["lifetime_opex_mode"] = distribution.mode() + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + outputs["lifetime_opex_lower"] = intervals[0] + outputs["lifetime_opex_upper"] = intervals[1] + + except np.linalg.LinAlgError: + outputs["lifetime_opex_mean"] = opex_total.mean() + + # Calculate total costs + if not capex_bom.empty or outputs["lifetime_opex_mean"] is not None: + lifetime_cost_mean = capex_total + + if outputs["lifetime_opex_mean"] is not None: + lifetime_cost_mean += outputs["lifetime_opex_mean"] + + outputs["lifetime_cost_mean"] = lifetime_cost_mean + + if not capex_bom.empty or outputs["lifetime_opex_mode"] is not None: + lifetime_cost_mode = capex_total + + if outputs["lifetime_opex_mode"] is not None: + lifetime_cost_mode += outputs["lifetime_opex_mode"] + + outputs["lifetime_cost_mode"] = lifetime_cost_mode + + if not capex_bom.empty or outputs["discounted_opex_mean"] is not None: + lifetime_discounted_cost_mean = discounted_capex_total - self.data.lcoe_mean = lcoe_metrics["lcoe_mean"] - discounted_opex_base = lcoe_metrics["discounted_opex_base"] - discounted_energy_base = lcoe_metrics["discounted_energy_base"] + if outputs["discounted_opex_mean"] is not None: + lifetime_discounted_cost_mean += outputs["discounted_opex_mean"] - if "lcoe_mode" in lcoe_metrics: - self.data.lcoe_mode = lcoe_metrics["lcoe_mode"] - self.data.lcoe_mode_opex = lcoe_metrics["lcoe_mode_opex"] - self.data.lcoe_mode_energy = lcoe_metrics["lcoe_mode_energy"] - self.data.lcoe_pdf = lcoe_metrics["lcoe_pdf"] + outputs["discounted_lifetime_cost_mean"] = lifetime_discounted_cost_mean - if "confidence_density" in lcoe_metrics: - self.data.confidence_density = lcoe_metrics["confidence_density"] - self.data.lcoe_lower = lcoe_metrics["lcoe_lower"] - self.data.lcoe_upper = lcoe_metrics["lcoe_upper"] + if not capex_bom.empty or outputs["discounted_opex_mode"] is not None: + lifetime_discounted_cost_mode = discounted_capex_total + + if outputs["discounted_opex_mean"] is not None: + lifetime_discounted_cost_mode += outputs["discounted_opex_mode"] + + outputs["discounted_lifetime_cost_mode"] = lifetime_discounted_cost_mode # Calculate values using most likely OPEX / Energy combination + if outputs["discounted_opex_mode"] is not None: + discounted_opex_base = outputs["discounted_opex_mode"] + else: + discounted_opex_base = outputs["discounted_opex_mean"] + + assert discounted_opex_base is not None + + if outputs["discounted_energy_mode"] is not None: + discounted_energy_base = outputs["discounted_energy_mode"] + else: + discounted_energy_base = outputs["discounted_energy_mean"] + + assert discounted_energy_base is not None # CAPEX vs OPEX Breakdown and OPEX Breakdown if externalities breakdown = { @@ -676,40 +768,42 @@ def _get_outputs( "Discounted OPEX": discounted_opex_base, } - self.data.cost_breakdown = breakdown + outputs["cost_breakdown"] = breakdown - if self.data.externalities_opex is None: + if externalities_opex is None: discounted_maintenance = discounted_opex_base else: opex_breakdown = _get_opex_breakdown( opex_bom, - self.data.externalities_opex, + externalities_opex, discounted_opex_base, - self.data.discount_rate, + discount_rate, ) - self.data.opex_breakdown = opex_breakdown + outputs["opex_breakdown"] = opex_breakdown discounted_maintenance = opex_breakdown["Maintenance"] discounted_external = opex_breakdown["Externalities"] - # LCOE Breakdowns in cent/kWh - - if self.data.capex_breakdown is not None: - capex_lcoe_breakdown = {} - - for k, v in self.data.capex_breakdown.iteritems(): - capex_lcoe_breakdown[k] = round(v / discounted_energy_base, 2) + # LCOE Breakdowns in cent/kWh (i.e. Euro/Wh * 1e5) + factor = 1e5 - self.data.capex_lcoe_breakdown = capex_lcoe_breakdown + if capex_breakdown is not None: + capex_lcoe_breakdown = { + k: round(factor * v / discounted_energy_base, 2) + for k, v in capex_breakdown.items() + } + outputs["capex_lcoe_breakdown"] = capex_lcoe_breakdown - lcoe_maintenance = round(discounted_maintenance / discounted_energy_base, 2) + lcoe_maintenance = round( + factor * discounted_maintenance / discounted_energy_base, 2 + ) - if self.data.externalities_opex is None: + if externalities_opex is None: lcoe_external = 0 - else: - lcoe_external = round(discounted_external / discounted_energy_base, 2) - - self.data.opex_lcoe_breakdown = { + lcoe_external = round( + factor * discounted_external / discounted_energy_base, 2 + ) + outputs["opex_lcoe_breakdown"] = { "Maintenance": lcoe_maintenance, "Externalities": lcoe_external, } @@ -717,9 +811,9 @@ def _get_outputs( total_capex = sum(capex_lcoe_breakdown.values()) total_opex = lcoe_maintenance + lcoe_external - self.data.lcoe_breakdown = {"CAPEX": total_capex, "OPEX": total_opex} + outputs["lcoe_breakdown"] = {"CAPEX": total_capex, "OPEX": total_opex} - return + return outputs def _get_metrics_table( @@ -732,9 +826,9 @@ def _get_metrics_table( lcoe_total: Optional[pd.Series], ) -> Optional[pd.DataFrame]: table_cols_and_conversion = [ - ("LCOE", lcoe_total, 1e-3), # from Euro/Wh to Euro/kWh - ("LCOE CAPEX", lcoe_capex, 1e-3), # from Euro/Wh to Euro/kWh - ("LCOE OPEX", lcoe_opex, 1e-3), # from Euro/Wh to Euro/kWh + ("LCOE", lcoe_total, 1e3), # from Euro/Wh to Euro/kWh + ("LCOE CAPEX", lcoe_capex, 1e3), # from Euro/Wh to Euro/kWh + ("LCOE OPEX", lcoe_opex, 1e3), # from Euro/Wh to Euro/kWh ("OPEX", opex_total, 1), ("Energy", energy_total, 1e-6), # from Wh to MWh ("Discounted OPEX", discounted_opex, 1), @@ -761,90 +855,37 @@ def _get_metrics_table( return metrics -def _get_metric_stats(data: np.ndarray): - mean = None - mode = None - lower = None - upper = None - - # Catch one or two data points - if len(data) == 1: - mean = data[0] - - elif len(data) == 2: - assert isinstance(data, np.ndarray) - mean = data.mean() - - else: - assert isinstance(data, np.ndarray) - - try: - distribution = UniVariateKDE(data) - mean = distribution.mean() - mode = distribution.mode() - - intervals = distribution.confidence_interval(95) - - if intervals is not None: - lower = intervals[0] - upper = intervals[1] - - except np.linalg.LinAlgError: - mean = data.mean() - - return {mean, mode, lower, upper} - - -def _get_lcoe_basic(capex, opex, energy): - mean_lcoe = (capex / 1000.0 + np.mean(opex)) / np.mean(energy) - - result = {} - result["lcoe_mean"] = mean_lcoe - result["discounted_opex_base"] = np.mean(opex) * 1000.0 - result["discounted_energy_base"] = np.mean(energy) * 10.0 - - return result - - -def _get_lcoe_kde(capex, opex, energy): - result = {} - +def _get_discounted_opex_stats(outputs: dict[str, Any], discounted_opex): try: - distribution = BiVariateKDE(opex, energy) - except np.linalg.LinAlgError: - return - - mean_coords = distribution.mean() - result["lcoe_mean"] = (capex / 1000.0 + mean_coords[0]) / mean_coords[1] + distribution = UniVariateKDE(discounted_opex) + outputs["discounted_opex_mean"] = distribution.mean() + outputs["discounted_opex_mode"] = distribution.mode() - mode_coords = distribution.mode() - result["lcoe_mode"] = (capex / 1000.0 + mode_coords[0]) / mode_coords[1] + intervals = distribution.confidence_interval(95) - result["lcoe_mode_opex"] = mode_coords[0] * 1000 - result["lcoe_mode_energy"] = mode_coords[1] + if intervals is not None: + outputs["discounted_opex_lower"] = intervals[0] + outputs["discounted_opex_upper"] = intervals[1] - xx, yy, pdf = distribution.pdf() - clevels = pdf_confidence_densities(pdf) - - if clevels: - cx, cy = pdf_contour_coords(xx, yy, pdf, clevels[0]) + except np.linalg.LinAlgError: + outputs["discounted_opex_mean"] = discounted_opex.mean() - lcoes = [] - for discounted_opex, discounted_energy in zip(cx, cy): - lcoe = (capex / 1000.0 + discounted_opex) / discounted_energy - lcoes.append(lcoe) +def _get_discounted_energy_stats(outputs: dict[str, Any], discounted_energy): + # W to MW + try: + distribution = UniVariateKDE(discounted_energy) + outputs["discounted_energy_mean"] = distribution.mean() / 1e6 + outputs["discounted_energy_mode"] = distribution.mode() / 1e6 - result["confidence_density"] = clevels[0] - result["lcoe_lower"] = min(lcoes) - result["lcoe_upper"] = max(lcoes) + intervals = distribution.confidence_interval(95) - # LCOE distribution - result["lcoe_pdf"] = {"values": pdf, "coords": [xx, yy]} - result["discounted_opex_base"] = mode_coords[0] * 1000.0 - result["discounted_energy_base"] = mode_coords[1] * 10.0 + if intervals is not None: + outputs["discounted_energy_lower"] = intervals[0] / 1e6 + outputs["discounted_energy_upper"] = intervals[1] / 1e6 - return result + except np.linalg.LinAlgError: + outputs["discounted_energy_mean"] = discounted_energy.mean() / 1e6 def _get_opex_breakdown( @@ -866,20 +907,3 @@ def _get_opex_breakdown( "Maintenance": discounted_maintenance, "Externalities": discounted_external, } - - -def _get_capex_no_externalities(externalities_capex, capex_total): - if externalities_capex is None: - return - return capex_total - externalities_capex - - -def _get_lifetime_cost(capex, lifetime_opex): - lifetime_cost = capex - - if lifetime_opex is not None: - if lifetime_cost is None: - lifetime_cost = 0 - lifetime_cost += lifetime_opex - - return lifetime_cost From fab91b5a151bdd8a00abf7fb6676775f7a3df605 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 2 Apr 2026 16:43:38 +0100 Subject: [PATCH 12/40] Fix existing unit tests --- .../tests/dtocean_economics/test_functions.py | 34 +++---- .../tests/dtocean_economics/test_main.py | 89 ------------------- 2 files changed, 11 insertions(+), 112 deletions(-) delete mode 100644 packages/dtocean-economics/tests/dtocean_economics/test_main.py diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py index 730b6787..577c503e 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -17,32 +17,20 @@ import numpy as np import pandas as pd -import pytest -from dtocean_economics.functions import ( +YEAR_ONE = 6 / 5 +YEAR_TWO = 36 / 25 +YEAR_THREE = 216 / 125 + +from dtocean_economics import ( costs_from_bom, - get_combined_lcoe, get_discounted_values, - get_lcoe, get_phase_breakdown, get_present_values, + get_total_cost, ) -@pytest.mark.parametrize( - "capex, opex, expected", - [ - (1, None, 1), - (None, 1, 1), - (1, 1, 2), - ], -) -def test_get_combined_lcoe_capex(capex, opex, expected): - result = get_combined_lcoe(capex, opex) - - assert result == expected - - def test_get_discounted_values(bom): costs_df = costs_from_bom(bom) result = get_discounted_values(costs_df, 1 / 5) @@ -50,11 +38,6 @@ def test_get_discounted_values(bom): assert np.isclose(result.iloc[0], 331) -def test_get_lcoe(): - result = get_lcoe(np.array([1]), np.array([10])) - assert np.isclose(result[0], 0.1) - - def test_get_phase_breakdown(bom): result = get_phase_breakdown(bom) print(result) @@ -82,3 +65,8 @@ def test_get_present_values(): result = get_present_values(value, year, dr) assert np.isclose(result, expected).all() + + +def test_get_total_cost(bom): + expected = 101 + (YEAR_ONE * 110) + (YEAR_TWO * 120) + assert np.isclose(get_total_cost(bom), expected) diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_main.py b/packages/dtocean-economics/tests/dtocean_economics/test_main.py deleted file mode 100644 index 5623e299..00000000 --- a/packages/dtocean-economics/tests/dtocean_economics/test_main.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright (C) 2017-2026 Mathew Topper -# -# 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 . - -import numpy as np - -from dtocean_economics import main - - -def test_main(bom, opex_costs, energy_record): - result = main(bom, opex_costs, energy_record, 1 / 5) - import pprint - - pprint.pprint(result) - assert result["CAPEX"] == 405.8 - - breakdown = result["CAPEX breakdown"] - assert breakdown is not None - assert breakdown["Test"] == 41.8 - assert breakdown["Other"] == 364 - - assert result["Discounted CAPEX"] == 331 - - expected = 1 + 6 / 5 + 36 / 25 + 216 / 125 - - assert result["OPEX"] is not None - assert np.isclose(result["OPEX"], [expected, 10 * expected]).all() - - assert result["Energy"] is not None - assert np.isclose(result["Energy"], [expected, 10 * expected]).all() - - assert result["Discounted OPEX"] is not None - assert np.isclose(result["Discounted OPEX"], [4, 40]).all() - - assert result["Discounted Energy"] is not None - assert np.isclose(result["Discounted Energy"], [4, 40]).all() - - assert result["LCOE CAPEX"] is not None - assert np.isclose(result["LCOE CAPEX"], [331 / 4, 331 / 40]).all() - - assert result["LCOE OPEX"] is not None - assert np.isclose(result["LCOE OPEX"], [1, 1]).all() - - assert result["LCOE"] is not None - assert np.isclose(result["LCOE"], [335 / 4, 371 / 40]).all() - - -def test_main_no_capex(bom, opex_costs, energy_record): - capex_empty = bom.drop(bom.index) - result = main(capex_empty, opex_costs, energy_record) - - assert result["CAPEX breakdown"] is None - assert result["CAPEX"] is None - assert result["Discounted CAPEX"] is None - assert result["LCOE CAPEX"] is None - - -def test_main_no_opex(bom, energy_record): - opex_empty = bom.drop(bom.index) - - result = main(bom, opex_empty, energy_record) - - assert result["OPEX"] is None - assert result["Discounted OPEX"] is None - assert result["LCOE OPEX"] is None - - -def test_main_no_energy(bom, opex_costs, energy_record): - energy_empty = energy_record.drop(energy_record.index) - result = main(bom, opex_costs, energy_empty) - - assert result["Energy"] is None - assert result["Discounted Energy"] is None - assert result["LCOE CAPEX"] is None - assert result["LCOE OPEX"] is None - assert result["LCOE"] is None From 98da4cf54102ad9cc6d7770ab74572ac07fc4fc5 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 2 Apr 2026 16:53:29 +0100 Subject: [PATCH 13/40] Fix ruff --- .../tests/dtocean_economics/test_functions.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py index 577c503e..d917dae9 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -18,10 +18,6 @@ import numpy as np import pandas as pd -YEAR_ONE = 6 / 5 -YEAR_TWO = 36 / 25 -YEAR_THREE = 216 / 125 - from dtocean_economics import ( costs_from_bom, get_discounted_values, @@ -30,6 +26,10 @@ get_total_cost, ) +YEAR_ONE = 6 / 5 +YEAR_TWO = 36 / 25 +YEAR_THREE = 216 / 125 + def test_get_discounted_values(bom): costs_df = costs_from_bom(bom) From 7b2f8fb327e24d2a931d36211a32c901ce45e031 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Fri, 3 Apr 2026 15:32:24 +0100 Subject: [PATCH 14/40] Start testing the actual input data manipulation --- .../src/dtocean_plugins/themes/economics.py | 1 + .../test_data/inputs_economics.py | 8 ++-- .../themes/test_themes_economics.py | 48 +++++++++++++++++-- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index f819206b..7768b2fd 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -431,6 +431,7 @@ def connect(self, debug_entry=False): ignore_index=True, sort=False, ) + capex_bom = capex_bom.convert_dtypes() if self.data.opex_per_year is not None: opex_bom = self.data.opex_per_year.copy() diff --git a/packages/dtocean-economics/test_data/inputs_economics.py b/packages/dtocean-economics/test_data/inputs_economics.py index 321fae1b..5a8d3a23 100644 --- a/packages/dtocean-economics/test_data/inputs_economics.py +++ b/packages/dtocean-economics/test_data/inputs_economics.py @@ -15,15 +15,17 @@ externalities_capex = 1e6 zero_bom_dict = { - "Key Identifier": [0, 1], "Quantity": [5, 10], "Cost": [100, 50], "Year": [0, 0], } zero_bom = pd.DataFrame(zero_bom_dict) -electrical_bom = zero_bom.copy() -moorings_bom = zero_bom.copy() +electrical_bom_dict = {"Key Identifier": [0, 1]} | zero_bom_dict +electrical_bom = pd.DataFrame(electrical_bom_dict) + +moorings_bom_dict = {"Key Identifier": [1, 2]} | zero_bom_dict +moorings_bom = pd.DataFrame(moorings_bom_dict) install_bom_dict = { "Key Identifier": [0, 1], diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index 0409c0f8..cc1b184f 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -1,7 +1,9 @@ import os from copy import deepcopy from pprint import pprint +from unittest.mock import MagicMock +import pandas as pd import pytest from dtocean_core.core import Core from dtocean_core.menu import DataMenu, ProjectMenu, ThemeMenu @@ -102,16 +104,23 @@ def test_get_economics_interface( def test_economics_interface_entry( + mocker, inputs_economics, theme_menu, core, tidal_project, var_tree, ): - theme_name = "Economics" + _get_outputs: MagicMock = mocker.patch( + "dtocean_plugins.themes.economics._get_outputs", + autospec=True, + return_value={}, + ) project_menu = ProjectMenu() project = deepcopy(tidal_project) + + theme_name = "Economics" theme_menu.activate(core, project, theme_name) project_menu.initiate_dataflow(core, project) @@ -129,9 +138,42 @@ def test_economics_interface_entry( connector = _get_connector(project, "themes") interface = connector.get_interface(core, project, theme_name) - interface.connect(debug_entry=True) + interface.connect() + + _get_outputs.assert_called_once() + _get_outputs_args = _get_outputs.call_args[0] + + capex_bom = _get_outputs_args[0] + opex_bom = _get_outputs_args[1] + energy_record = _get_outputs_args[2] + print(capex_bom) + + capex_bom_elec = capex_bom[ + capex_bom["phase"] == "Electrical Sub-Systems" + ].drop("phase", axis=1) + assert len(capex_bom_elec) == 1 + assert capex_bom_elec.iloc[0]["quantity"] == 5 + + expected_bom_mandf_dict = { + "quantity": [5, 10], + "unitary_cost": [100, 50], + "project_year": [0, 0], + } + expected_bom_mandf = pd.DataFrame(expected_bom_mandf_dict).astype( + pd.Int64Dtype + ) - assert True + capex_bom_mandf = ( + capex_bom[capex_bom["phase"] == "Mooring and Foundations"] + .drop("phase", axis=1) + .reset_index(drop=True) + ) + pd.testing.assert_frame_equal(expected_bom_mandf, capex_bom_mandf) + + print(opex_bom) + print(energy_record) + + assert False def test_get_economics_interface_estimate( From 9fbc89f173b6115b0ca1f1fac827a17b7683d054 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Wed, 8 Apr 2026 12:24:51 +0100 Subject: [PATCH 15/40] Finish update of interface entry test --- .../themes/test_themes_economics.py | 65 +++++++++++++++++-- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index cc1b184f..184164e5 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -146,13 +146,16 @@ def test_economics_interface_entry( capex_bom = _get_outputs_args[0] opex_bom = _get_outputs_args[1] energy_record = _get_outputs_args[2] - print(capex_bom) capex_bom_elec = capex_bom[ capex_bom["phase"] == "Electrical Sub-Systems" ].drop("phase", axis=1) assert len(capex_bom_elec) == 1 - assert capex_bom_elec.iloc[0]["quantity"] == 5 + capex_bom_elec_i = capex_bom_elec.iloc[0] + + assert capex_bom_elec_i["quantity"] == 5 + assert capex_bom_elec_i["unitary_cost"] == 100 + assert capex_bom_elec_i["project_year"] == 0 expected_bom_mandf_dict = { "quantity": [5, 10], @@ -170,10 +173,62 @@ def test_economics_interface_entry( ) pd.testing.assert_frame_equal(expected_bom_mandf, capex_bom_mandf) - print(opex_bom) - print(energy_record) + expected_bom_inst_dict = { + "quantity": [1, 1], + "unitary_cost": [1000, 2000], + "project_year": [1, 2], + } + expected_bom_inst = pd.DataFrame(expected_bom_inst_dict).astype( + pd.Int64Dtype + ) + + capex_bom_inst = ( + capex_bom[capex_bom["phase"] == "Installation"] + .drop("phase", axis=1) + .reset_index(drop=True) + ) + pd.testing.assert_frame_equal(expected_bom_inst, capex_bom_inst) + + capex_bom_cond = ( + capex_bom[capex_bom["phase"] == "Condition Monitoring"] + .drop("phase", axis=1) + .reset_index(drop=True) + ) + assert len(capex_bom_cond) == 1 + capex_bom_cond_i = capex_bom_cond.iloc[0] + + assert capex_bom_cond_i["quantity"] == 1 + assert capex_bom_cond_i["unitary_cost"] == 100 + assert capex_bom_cond_i["project_year"] == 0 + + capex_bom_ext = ( + capex_bom[capex_bom["phase"] == "Externalities"] + .drop("phase", axis=1) + .reset_index(drop=True) + ) + assert len(capex_bom_ext) == 1 + capex_bom_ext_i = capex_bom_ext.iloc[0] - assert False + assert capex_bom_ext_i["quantity"] == 1 + assert capex_bom_ext_i["unitary_cost"] == 1e6 + assert capex_bom_ext_i["project_year"] == 0 + + expected_opex_bom_dict = { + "project_year": [3, 4], + "Cost": [1000.0, 2000.0], + } + expected_opex_bom = pd.DataFrame(expected_opex_bom_dict) + pd.testing.assert_frame_equal(expected_opex_bom, opex_bom) + + expected_energy_record_dict = { + "project_year": [3, 4], + "Energy": [10000.0, 20000.0], + } + expected_energy_record = pd.DataFrame(expected_energy_record_dict) + expected_energy_record["Energy"] = ( + expected_energy_record["Energy"] * 0.99 * 1e6 + ) + pd.testing.assert_frame_equal(expected_energy_record, energy_record) def test_get_economics_interface_estimate( From 035252d0052df86af3ab029e39b6e9c26c2d6e2f Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 13 Apr 2026 10:35:58 +0100 Subject: [PATCH 16/40] Test input estimates properly --- .../test_data/inputs_economics_estimate.py | 2 +- .../themes/test_themes_economics.py | 78 ++++++++++++++++++- 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/packages/dtocean-economics/test_data/inputs_economics_estimate.py b/packages/dtocean-economics/test_data/inputs_economics_estimate.py index f54fc72b..d07d8d1f 100644 --- a/packages/dtocean-economics/test_data/inputs_economics_estimate.py +++ b/packages/dtocean-economics/test_data/inputs_economics_estimate.py @@ -18,7 +18,7 @@ "project.installation_cost_estimate": 1e5, "project.opex_estimate": 1e4, "project.annual_repair_cost_estimate": 1e4, - "project.annual_array_mttf_estimate": 10000.0, + "project.annual_array_mttf_estimate": 4383.0, "project.electrical_network_efficiency": 0.95, "project.annual_energy": 10000.0, "project.estimate_energy_record": True, diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index 184164e5..02612820 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -163,7 +163,7 @@ def test_economics_interface_entry( "project_year": [0, 0], } expected_bom_mandf = pd.DataFrame(expected_bom_mandf_dict).astype( - pd.Int64Dtype + pd.Int64Dtype() ) capex_bom_mandf = ( @@ -179,7 +179,7 @@ def test_economics_interface_entry( "project_year": [1, 2], } expected_bom_inst = pd.DataFrame(expected_bom_inst_dict).astype( - pd.Int64Dtype + pd.Int64Dtype() ) capex_bom_inst = ( @@ -263,12 +263,19 @@ def test_get_economics_interface_estimate( def test_economics_interface_entry_estimate( + mocker, inputs_economics_estimate, theme_menu, core, tidal_project, var_tree, ): + _get_outputs: MagicMock = mocker.patch( + "dtocean_plugins.themes.economics._get_outputs", + autospec=True, + return_value={}, + ) + theme_name = "Economics" project_menu = ProjectMenu() @@ -290,6 +297,69 @@ def test_economics_interface_entry_estimate( connector = _get_connector(project, "themes") interface = connector.get_interface(core, project, theme_name) - interface.connect(debug_entry=True) + interface.connect() + + _get_outputs.assert_called_once() + _get_outputs_args = _get_outputs.call_args[0] + + capex_bom = _get_outputs_args[0] + opex_bom = _get_outputs_args[1] + energy_record = _get_outputs_args[2] + + capex_bom_dev = ( + capex_bom[capex_bom["phase"] == "Devices"] + .drop("phase", axis=1) + .reset_index(drop=True) + ).iloc[0] + + assert capex_bom_dev["quantity"] == 5 + assert capex_bom_dev["unitary_cost"] == 1e6 + assert capex_bom_dev["project_year"] == 0 + + capex_bom_elec = ( + capex_bom[capex_bom["phase"] == "Electrical Sub-Systems"] + .drop("phase", axis=1) + .reset_index(drop=True) + ).iloc[0] + + assert capex_bom_elec["quantity"] == 1 + assert capex_bom_elec["unitary_cost"] == 1e5 + assert capex_bom_elec["project_year"] == 0 + + capex_bom_moor = ( + capex_bom[capex_bom["phase"] == "Mooring and Foundations"] + .drop("phase", axis=1) + .reset_index(drop=True) + ).iloc[0] + + assert capex_bom_moor["quantity"] == 1 + assert capex_bom_moor["unitary_cost"] == 1e5 + assert capex_bom_moor["project_year"] == 0 + + capex_bom_inst = ( + capex_bom[capex_bom["phase"] == "Installation"] + .drop("phase", axis=1) + .reset_index(drop=True) + ).iloc[0] + + assert capex_bom_inst["quantity"] == 1 + assert capex_bom_inst["unitary_cost"] == 1e5 + assert capex_bom_inst["project_year"] == 0 + + assert opex_bom["costs"].iloc[0] == 0 + opex_bom_one = opex_bom[opex_bom["project_year"] != 0] + + opex_bom_costs = set(opex_bom_one["costs"]) + assert len(opex_bom_costs) == 1 + + opex_bom_cost = opex_bom_costs.pop() + assert opex_bom_cost == 30000.0 + + assert energy_record["energy"].iloc[0] == 0 + energy_record_one = energy_record[energy_record["project_year"] != 0] + + energy_record_energies = set(energy_record_one["energy"]) + assert len(energy_record_energies) == 1 - assert True + energy_record_energy = energy_record_energies.pop() + assert energy_record_energy == 10000 * 1e6 * 0.95 From 3b2d249cdbb8602df372572affa930f8951344d2 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 13 Apr 2026 17:22:06 +0100 Subject: [PATCH 17/40] Test output conversion for single simulation --- .../src/dtocean_economics/__init__.py | 44 ++- .../src/dtocean_plugins/themes/economics.py | 282 ++++++++++-------- .../tests/dtocean_economics/conftest.py | 60 ---- .../tests/dtocean_economics/test_functions.py | 54 +++- .../themes/test_themes_economics.py | 254 +++++++++++++++- 5 files changed, 488 insertions(+), 206 deletions(-) delete mode 100644 packages/dtocean-economics/tests/dtocean_economics/conftest.py diff --git a/packages/dtocean-economics/src/dtocean_economics/__init__.py b/packages/dtocean-economics/src/dtocean_economics/__init__.py index 5e1d2392..af0d281a 100644 --- a/packages/dtocean-economics/src/dtocean_economics/__init__.py +++ b/packages/dtocean-economics/src/dtocean_economics/__init__.py @@ -17,52 +17,66 @@ # along with this program. If not, see . +import numpy as np import pandas as pd -def costs_from_bom(bom): +def add_costs_to_bom(bom, discount_rate=None): costs = bom["quantity"] * bom["unitary_cost"] - costs_dict = {"project_year": bom["project_year"].values, "costs": costs} - return pd.DataFrame(costs_dict) + bom["costs"] = costs + if discount_rate is None: + return -def get_discounted_values(values_df: pd.DataFrame, discount_rate): + present_values = get_present_values( + costs.to_numpy(), + bom["project_year"].to_numpy(), + discount_rate, + ) + + bom["discounted_costs"] = present_values + + +def get_discounted_values(values_df: pd.DataFrame, discount_rate: float): years = values_df["project_year"] values_df = values_df.set_index("project_year") - discounted_values = [] for _, value_series in values_df.items(): - present_values = get_present_values(value_series, years, discount_rate) + present_values = get_present_values( + value_series.to_numpy(), + years.to_numpy(), + discount_rate, + ) discounted_value = present_values.sum() discounted_values.append(discounted_value) return pd.Series(discounted_values) -def get_phase_breakdown(bom): +def get_phase_breakdown(bom: pd.DataFrame): + if "costs" not in bom.keys(): + return + # Check for null phases null_phases = pd.isnull(bom["phase"]) # No breakdown available if null_phases.all(): - return None + return # Replace any null phase values bom.loc[pd.isnull(bom["phase"]), "phase"] = "Other" - phase_groups = bom.groupby("phase") - phase_breakdown = {} - - for phase_name, phase_bom in phase_groups: - phase_cost = get_total_cost(phase_bom) - phase_breakdown[phase_name] = phase_cost + phase_breakdown = phase_groups.sum() + if "unitary_costs" in phase_breakdown: + phase_breakdown.drop("unitary_costs", axis=1, inplace=True) return phase_breakdown -def get_present_values(value, yr, dr): +def get_present_values(value: np.ndarray, yr: np.ndarray, dr: float): """ Function to calculate present value It should be applied to a table with costs and year cost occurs, and to diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 7768b2fd..075ed9a0 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -34,7 +34,7 @@ import pandas as pd from dtocean_economics import ( - costs_from_bom, + add_costs_to_bom, get_discounted_values, get_phase_breakdown, get_total_cost, @@ -547,7 +547,7 @@ def _get_outputs( capex_total = 0 discounted_capex_total = 0 - capex_breakdown = None + phase_breakdown = None discounted_capex = None discounted_opex = None lcoe_capex = None @@ -555,14 +555,19 @@ def _get_outputs( lcoe_total = None if not capex_bom.empty: - costs_df = costs_from_bom(capex_bom) + add_costs_to_bom(capex_bom, discount_rate) + costs_df = capex_bom[["project_year", "costs"]] + discounted_capex = get_discounted_values( costs_df, discount_rate, ) + discounted_capex_total = discounted_capex.iloc[0] capex_total = get_total_cost(capex_bom) - capex_breakdown = get_phase_breakdown(capex_bom) + phase_breakdown = get_phase_breakdown(capex_bom) + assert phase_breakdown is not None + capex_breakdown = {k: v["costs"] for k, v in phase_breakdown.iterrows()} outputs["capex_total"] = capex_total outputs["capex_breakdown"] = capex_breakdown @@ -585,7 +590,7 @@ def _get_outputs( if discounted_capex is not None: lcoe_capex = discounted_capex / discounted_energy - lcoe_total = lcoe_capex + lcoe_total = lcoe_capex.copy() if discounted_opex is not None: lcoe_opex = discounted_opex / discounted_energy @@ -608,112 +613,16 @@ def _get_outputs( return outputs outputs["economics_metrics"] = metrics_table - - if len(metrics_table) < 3: - if opex_total is not None: - outputs["lifetime_opex_mean"] = opex_total.mean() - - if discounted_opex is not None: - outputs["discounted_opex_mean"] = discounted_opex.mean() - - if discounted_energy is not None: - # From W to MW - outputs["discounted_energy_mean"] = discounted_energy.mean() / 1e6 - - if lcoe_total is not None: - # From Euro/Wh to Euro/kWh - outputs["lcoe_mean"] = lcoe_total.mean() * 1000 - - else: - if discounted_opex is not None and discounted_energy is not None: - try: - distribution = BiVariateKDE(discounted_opex, discounted_energy) - - mean_coords = distribution.mean() - lcoe_mean = (capex_total + mean_coords[0]) / mean_coords[1] - outputs["lcoe_mean"] = lcoe_mean * 1000 # Euro/Wh to Euro/kWh - outputs["discounted_opex_mean"] = mean_coords[0] - outputs["discounted_energy_mean"] = ( - mean_coords[1] / 1e6 - ) # W to MW - - mode_coords = distribution.mode() - lcoe_mode = (capex_total + mean_coords[0]) / mean_coords[1] - outputs["lcoe_mode"] = lcoe_mode * 1000 # Euro/Wh to Euro/kWh - outputs["discounted_opex_mode"] = mode_coords[0] - outputs["discounted_energy_mode"] = ( - mode_coords[1] / 1e6 - ) # W to MW - - xx, yy, pdf = distribution.pdf() - clevels = pdf_confidence_densities(pdf) - - # LCOE distribution - outputs["lcoe_pdf"] = {"values": pdf, "coords": [xx, yy]} - - if clevels: - outputs["confidence_density"] = clevels[0] - cx, cy = pdf_contour_coords(xx, yy, pdf, clevels[0]) - - outputs["discounted_opex_lower"] = min(cx) - outputs["discounted_energy_lower"] = ( - min(cy) / 1e6 - ) # W to MW - outputs["discounted_opex_upper"] = max(cx) - outputs["discounted_energy_upper"] = ( - max(cy) / 1e6 - ) # W to MW - - lcoes = [ - (capex_total + discounted_opex) / discounted_energy - for discounted_opex, discounted_energy in zip(cx, cy) - ] - - # Euro/Wh to Euro/kWh - outputs["lcoe_lower"] = min(lcoes) * 1000 - outputs["lcoe_upper"] = max(lcoes) * 1000 - - except np.linalg.LinAlgError: - _get_discounted_opex_stats(outputs, discounted_opex) - _get_discounted_energy_stats(outputs, discounted_energy) - - assert lcoe_total is not None - - # Euro/Wh to Euro/kWh - try: - distribution = UniVariateKDE(lcoe_total) - outputs["lcoe_mean"] = distribution.mean() * 1000 - outputs["lcoe_mode"] = distribution.mode() * 1000 - - intervals = distribution.confidence_interval(95) - - if intervals is not None: - outputs["lcoe_lower"] = intervals[0] * 1000 - outputs["lcoe_upper"] = intervals[1] * 1000 - - except np.linalg.LinAlgError: - outputs["lcoe_mean"] = lcoe_total.mean() * 1000 - - if discounted_opex is not None: - _get_discounted_opex_stats(outputs, discounted_opex) - - if discounted_energy is not None: - _get_discounted_energy_stats(outputs, discounted_energy) - - if opex_total is not None: - try: - distribution = UniVariateKDE(opex_total) - outputs["lifetime_opex_mean"] = distribution.mean() - outputs["lifetime_opex_mode"] = distribution.mode() - - intervals = distribution.confidence_interval(95) - - if intervals is not None: - outputs["lifetime_opex_lower"] = intervals[0] - outputs["lifetime_opex_upper"] = intervals[1] - - except np.linalg.LinAlgError: - outputs["lifetime_opex_mean"] = opex_total.mean() + outputs.update( + _get_outputs_stats( + metrics_table, + opex_total, + discounted_opex, + discounted_energy, + lcoe_total, + capex_total, + ) + ) # Calculate total costs if not capex_bom.empty or outputs["lifetime_opex_mean"] is not None: @@ -724,7 +633,7 @@ def _get_outputs( outputs["lifetime_cost_mean"] = lifetime_cost_mean - if not capex_bom.empty or outputs["lifetime_opex_mode"] is not None: + if not capex_bom.empty and outputs["lifetime_opex_mode"] is not None: lifetime_cost_mode = capex_total if outputs["lifetime_opex_mode"] is not None: @@ -740,10 +649,10 @@ def _get_outputs( outputs["discounted_lifetime_cost_mean"] = lifetime_discounted_cost_mean - if not capex_bom.empty or outputs["discounted_opex_mode"] is not None: + if not capex_bom.empty and outputs["discounted_opex_mode"] is not None: lifetime_discounted_cost_mode = discounted_capex_total - if outputs["discounted_opex_mean"] is not None: + if outputs["discounted_opex_mode"] is not None: lifetime_discounted_cost_mode += outputs["discounted_opex_mode"] outputs["discounted_lifetime_cost_mode"] = lifetime_discounted_cost_mode @@ -762,10 +671,11 @@ def _get_outputs( discounted_energy_base = outputs["discounted_energy_mean"] assert discounted_energy_base is not None + discounted_energy_base = discounted_energy_base * 1e6 # MW to W # CAPEX vs OPEX Breakdown and OPEX Breakdown if externalities breakdown = { - "Discounted CAPEX": discounted_capex, + "Discounted CAPEX": discounted_capex_total, "Discounted OPEX": discounted_opex_base, } @@ -787,10 +697,10 @@ def _get_outputs( # LCOE Breakdowns in cent/kWh (i.e. Euro/Wh * 1e5) factor = 1e5 - if capex_breakdown is not None: + if phase_breakdown is not None: capex_lcoe_breakdown = { - k: round(factor * v / discounted_energy_base, 2) - for k, v in capex_breakdown.items() + k: round(factor * v["discounted_costs"] / discounted_energy_base, 2) + for k, v in phase_breakdown.iterrows() } outputs["capex_lcoe_breakdown"] = capex_lcoe_breakdown @@ -856,6 +766,139 @@ def _get_metrics_table( return metrics +def _get_outputs_stats( + metrics_table, + opex_total, + discounted_opex, + discounted_energy, + lcoe_total, + capex_total, +): + outputs: dict[str, Any] = { + "lifetime_opex_mean": None, + "lifetime_opex_mode": None, + "lifetime_opex_lower": None, + "lifetime_opex_upper": None, + "discounted_opex_mean": None, + "discounted_opex_mode": None, + "discounted_opex_lower": None, + "discounted_opex_upper": None, + "discounted_energy_mean": None, + "discounted_energy_mode": None, + "discounted_energy_lower": None, + "discounted_energy_upper": None, + "lcoe_mean": None, + "lcoe_mode": None, + "lcoe_lower": None, + "lcoe_upper": None, + "lcoe_pdf": None, + "confidence_density": None, + } + + if len(metrics_table) < 3: + if opex_total is not None: + outputs["lifetime_opex_mean"] = opex_total.mean() + + if discounted_opex is not None: + outputs["discounted_opex_mean"] = discounted_opex.mean() + + if discounted_energy is not None: + # From W to MW + outputs["discounted_energy_mean"] = discounted_energy.mean() / 1e6 + + if lcoe_total is not None: + # From Euro/Wh to Euro/kWh + outputs["lcoe_mean"] = lcoe_total.mean() * 1000 + + return outputs + + if opex_total is not None: + try: + distribution = UniVariateKDE(opex_total) + outputs["lifetime_opex_mean"] = distribution.mean() + outputs["lifetime_opex_mode"] = distribution.mode() + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + outputs["lifetime_opex_lower"] = intervals[0] + outputs["lifetime_opex_upper"] = intervals[1] + + except np.linalg.LinAlgError: + outputs["lifetime_opex_mean"] = opex_total.mean() + + if discounted_opex is not None and discounted_energy is not None: + try: + distribution = BiVariateKDE(discounted_opex, discounted_energy) + + mean_coords = distribution.mean() + lcoe_mean = (capex_total + mean_coords[0]) / mean_coords[1] + outputs["lcoe_mean"] = lcoe_mean * 1000 # Euro/Wh to Euro/kWh + outputs["discounted_opex_mean"] = mean_coords[0] + outputs["discounted_energy_mean"] = mean_coords[1] / 1e6 # W to MW + + mode_coords = distribution.mode() + lcoe_mode = (capex_total + mean_coords[0]) / mean_coords[1] + outputs["lcoe_mode"] = lcoe_mode * 1000 # Euro/Wh to Euro/kWh + outputs["discounted_opex_mode"] = mode_coords[0] + outputs["discounted_energy_mode"] = mode_coords[1] / 1e6 # W to MW + + xx, yy, pdf = distribution.pdf() + clevels = pdf_confidence_densities(pdf) + + # LCOE distribution + outputs["lcoe_pdf"] = {"values": pdf, "coords": [xx, yy]} + + if clevels: + outputs["confidence_density"] = clevels[0] + cx, cy = pdf_contour_coords(xx, yy, pdf, clevels[0]) + + outputs["discounted_opex_lower"] = min(cx) + outputs["discounted_energy_lower"] = min(cy) / 1e6 # W to MW + outputs["discounted_opex_upper"] = max(cx) + outputs["discounted_energy_upper"] = max(cy) / 1e6 # W to MW + + lcoes = [ + (capex_total + discounted_opex) / discounted_energy + for discounted_opex, discounted_energy in zip(cx, cy) + ] + + # Euro/Wh to Euro/kWh + outputs["lcoe_lower"] = min(lcoes) * 1000 + outputs["lcoe_upper"] = max(lcoes) * 1000 + + except np.linalg.LinAlgError: + _get_discounted_opex_stats(outputs, discounted_opex) + _get_discounted_energy_stats(outputs, discounted_energy) + + assert lcoe_total is not None + + # Euro/Wh to Euro/kWh + try: + distribution = UniVariateKDE(lcoe_total) + outputs["lcoe_mean"] = distribution.mean() * 1000 + outputs["lcoe_mode"] = distribution.mode() * 1000 + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + outputs["lcoe_lower"] = intervals[0] * 1000 + outputs["lcoe_upper"] = intervals[1] * 1000 + + except np.linalg.LinAlgError: + outputs["lcoe_mean"] = lcoe_total.mean() * 1000 + + return outputs + + if discounted_opex is not None: + _get_discounted_opex_stats(outputs, discounted_opex) + + if discounted_energy is not None: + _get_discounted_energy_stats(outputs, discounted_energy) + + return outputs + + def _get_discounted_opex_stats(outputs: dict[str, Any], discounted_opex): try: distribution = UniVariateKDE(discounted_opex) @@ -895,12 +938,11 @@ def _get_opex_breakdown( discounted_opex_base, discount_rate, ): - years = range(1, len(opex_bom) + 1) + years = range(len(opex_bom)) discounted_externals = [ externalities_opex / (1 + discount_rate) ** i for i in years ] - discounted_external = np.array(discounted_externals).sum() discounted_maintenance = discounted_opex_base - discounted_external diff --git a/packages/dtocean-economics/tests/dtocean_economics/conftest.py b/packages/dtocean-economics/tests/dtocean_economics/conftest.py deleted file mode 100644 index 50bb8d97..00000000 --- a/packages/dtocean-economics/tests/dtocean_economics/conftest.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Tue Aug 08 12:36:48 2017 - -@author: mtopper -""" - -import pandas as pd -import pytest - -YEAR_ONE = 6 / 5 -YEAR_TWO = 36 / 25 -YEAR_THREE = 216 / 125 - - -@pytest.fixture(scope="module") -def bom(): - bom_dict = { - "phase": [None, None, None, "Test", "Test", "Test"], - "unitary_cost": [ - 100, - YEAR_ONE * 100, - YEAR_TWO * 100, - 1, - YEAR_ONE, - YEAR_TWO, - ], - "project_year": [0, 1, 2, 0, 1, 2], - "quantity": [1, 1, 1, 1, 10, 20], - } - - bom_df = pd.DataFrame(bom_dict) - - return bom_df - - -@pytest.fixture(scope="module") -def energy_record(): - energy_dict = { - "project_year": [0, 1, 2, 3], - "energy 0": [1, YEAR_ONE, YEAR_TWO, YEAR_THREE], - "energy 1": [10, YEAR_ONE * 10, YEAR_TWO * 10, YEAR_THREE * 10], - } - - energy_df = pd.DataFrame(energy_dict) - - return energy_df - - -@pytest.fixture(scope="module") -def opex_costs(): - opex_dict = { - "project_year": [0, 1, 2, 3], - "cost 0": [1, YEAR_ONE, YEAR_TWO, YEAR_THREE], - "cost 1": [10, YEAR_ONE * 10, YEAR_TWO * 10, YEAR_THREE * 10], - } - - opex_df = pd.DataFrame(opex_dict) - - return opex_df diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py index d917dae9..f14796a9 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -17,9 +17,10 @@ import numpy as np import pandas as pd +import pytest from dtocean_economics import ( - costs_from_bom, + add_costs_to_bom, get_discounted_values, get_phase_breakdown, get_present_values, @@ -31,28 +32,65 @@ YEAR_THREE = 216 / 125 +@pytest.fixture() +def bom(): + bom_dict = { + "phase": [None, None, None, "Test", "Test", "Test"], + "unitary_cost": [ + 100, + YEAR_ONE * 100, + YEAR_TWO * 100, + 1, + YEAR_ONE, + YEAR_TWO, + ], + "project_year": [0, 1, 2, 0, 1, 2], + "quantity": [1, 1, 1, 1, 10, 20], + } + + bom_df = pd.DataFrame(bom_dict) + + return bom_df + + +def test_add_costs_to_bom(bom): + add_costs_to_bom(bom) + assert (bom["costs"] == bom["unitary_cost"] * bom["quantity"]).all() + + +def test_add_costs_to_bom_discounted(bom): + add_costs_to_bom(bom, 1 / 5) + assert bom["discounted_costs"].sum() == 3 * 100 + 31 * 1 + + def test_get_discounted_values(bom): - costs_df = costs_from_bom(bom) + add_costs_to_bom(bom) + costs_df = bom[["project_year", "costs"]] result = get_discounted_values(costs_df, 1 / 5) assert np.isclose(result.iloc[0], 331) def test_get_phase_breakdown(bom): + add_costs_to_bom(bom) result = get_phase_breakdown(bom) - print(result) assert result is not None - assert set(result.keys()) == set(["Test", "Other"]) - assert result["Test"] == 41.8 - assert result["Other"] == 364 + assert set(result.index.values) == set(["Test", "Other"]) + + test = result.loc["Test"] + assert isinstance(test, pd.Series) + assert test["costs"] == 41.8 + + other = result.loc["Other"] + assert isinstance(other, pd.Series) + assert other["costs"] == 364 def test_get_phase_breakdown_none(bom): none_bom = bom[pd.isnull(bom["phase"])] - + add_costs_to_bom(none_bom) result = get_phase_breakdown(none_bom) - assert result is None diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index 02612820..b2301144 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -3,12 +3,15 @@ from pprint import pprint from unittest.mock import MagicMock +import numpy as np import pandas as pd import pytest from dtocean_core.core import Core from dtocean_core.menu import DataMenu, ProjectMenu, ThemeMenu from dtocean_core.pipeline import Tree, _get_connector +from dtocean_plugins.themes.economics import _get_outputs + DIR_PATH = os.path.dirname(__file__) @@ -114,7 +117,6 @@ def test_economics_interface_entry( _get_outputs: MagicMock = mocker.patch( "dtocean_plugins.themes.economics._get_outputs", autospec=True, - return_value={}, ) project_menu = ProjectMenu() @@ -273,7 +275,6 @@ def test_economics_interface_entry_estimate( _get_outputs: MagicMock = mocker.patch( "dtocean_plugins.themes.economics._get_outputs", autospec=True, - return_value={}, ) theme_name = "Economics" @@ -353,7 +354,7 @@ def test_economics_interface_entry_estimate( assert len(opex_bom_costs) == 1 opex_bom_cost = opex_bom_costs.pop() - assert opex_bom_cost == 30000.0 + assert opex_bom_cost == 10000.0 + 2 * 10000.0 assert energy_record["energy"].iloc[0] == 0 energy_record_one = energy_record[energy_record["project_year"] != 0] @@ -363,3 +364,250 @@ def test_economics_interface_entry_estimate( energy_record_energy = energy_record_energies.pop() assert energy_record_energy == 10000 * 1e6 * 0.95 + + +# These factors become 1 when used with a 1 / 5 discount rate in the respective +# year +YEAR_ONE = 6 / 5 +YEAR_TWO = 36 / 25 +YEAR_THREE = 216 / 125 + + +@pytest.fixture() +def bom(): + bom_dict = { + "phase": [ + "Devices", + "Electrical Sub-Systems", + "Installation", + "Installation", + "Condition Monitoring", + "Condition Monitoring", + "Externalities", + ], + "unitary_cost": [ + 1e6, + 5e6, + YEAR_ONE * 1e5, + YEAR_TWO * 1e5, + YEAR_ONE * 1e4, + YEAR_TWO * 1e4, + 1e6, + ], + "project_year": [0, 0, 1, 2, 1, 2, 0], + "quantity": [10, 1, 1, 1, 1, 1, 1], + } + + bom_df = pd.DataFrame(bom_dict) + + return bom_df + + +@pytest.fixture() +def opex_costs_0_externalities(): + opex_externalities = 216 + opex_dict = { + "project_year": [0, 1, 2, 3], + "cost 0": [ + 1 + opex_externalities, + YEAR_ONE + opex_externalities, + YEAR_TWO + opex_externalities, + YEAR_THREE + opex_externalities, + ], + } + + opex_df = pd.DataFrame(opex_dict) + + return opex_df + + +@pytest.fixture() +def energy_record_0(): + energy_dict = { + "project_year": [0, 1, 2, 3], + "energy 0": [1e6, YEAR_ONE * 1e6, YEAR_TWO * 1e6, YEAR_THREE * 1e6], + } + + energy_df = pd.DataFrame(energy_dict) + + return energy_df + + +def test_get_outputs_0_externalities( + bom, + opex_costs_0_externalities, + energy_record_0, +): + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + opex_costs_0_externalities, + energy_record_0, + discount_rate, + 1e6, + 216, + ) + + none_outputs = [ + "confidence_density", + "discounted_energy_lower", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_lifetime_cost_mode", + "discounted_opex_lower", + "discounted_opex_mode", + "discounted_opex_upper", + "lcoe_lower", + "lcoe_mode", + "lcoe_pdf", + "lcoe_upper", + "lifetime_cost_mode", + "lifetime_opex_lower", + "lifetime_opex_mode", + "lifetime_opex_upper", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + capex_breakdown = outputs["capex_breakdown"] + + assert capex_breakdown["Devices"] == 10 * 1e6 + assert capex_breakdown["Electrical Sub-Systems"] == 5e6 + assert capex_breakdown["Externalities"] == 1e6 + assert np.isclose( + capex_breakdown["Installation"], + (YEAR_ONE + YEAR_TWO) * 1e5, + ) + assert np.isclose( + capex_breakdown["Condition Monitoring"], + (YEAR_ONE + YEAR_TWO) * 1e4, + ) + + capex_total = outputs["capex_total"] + capex_no_externalities = outputs["capex_no_externalities"] + + expected_capex_no_externalities = ( + 10 * 1e6 + + 5e6 + + (YEAR_ONE + YEAR_TWO) * 1e5 + + (YEAR_ONE + YEAR_TWO) * 1e4 + ) + assert capex_no_externalities == expected_capex_no_externalities + assert capex_total == expected_capex_no_externalities + 1e6 + + discounted_capex = outputs["discounted_capex"] + discounted_capex_expected = 10 * 1e6 + 5e6 + 1e6 + 2 * (1e5 + 1e4) + assert discounted_capex == discounted_capex_expected + + economics_metrics = outputs["economics_metrics"] + economics_metric = economics_metrics.iloc[0] + + opex_metric = economics_metric["OPEX"] + opex_metric_expected = 1 + YEAR_ONE + YEAR_TWO + YEAR_THREE + 4 * 216 + assert np.isclose(opex_metric, opex_metric_expected) + + discounted_opex_metric = economics_metric["Discounted OPEX"] + discounted_opex_metric_expected = 4 + 216 + 180 + 150 + 125 + assert discounted_opex_metric == discounted_opex_metric_expected + + energy_metric = economics_metric["Energy"] + energy_metric_expected = 1 + YEAR_ONE + YEAR_TWO + YEAR_THREE + assert np.isclose(energy_metric, energy_metric_expected) + + discounted_energy_metric = economics_metric["Discounted Energy"] + discounted_energy_metric_expected = 4 + assert discounted_energy_metric == discounted_energy_metric_expected + + lcoe_capex_metric = economics_metric["LCOE CAPEX"] + lcoe_capex_metric_expected = ( + discounted_capex / discounted_energy_metric / 1000 + ) + assert np.isclose(lcoe_capex_metric, lcoe_capex_metric_expected) + + lcoe_opex_metric = economics_metric["LCOE OPEX"] + lcoe_opex_metric_expected = ( + discounted_opex_metric / discounted_energy_metric / 1000 + ) + assert np.isclose(lcoe_opex_metric, lcoe_opex_metric_expected) + + lcoe_metric = economics_metric["LCOE"] + lcoe_metric_expected = ( + lcoe_capex_metric_expected + lcoe_opex_metric_expected + ) + assert np.isclose(lcoe_metric, lcoe_metric_expected) + + assert outputs["lifetime_cost_mean"] == capex_total + opex_metric_expected + assert ( + outputs["discounted_lifetime_cost_mean"] + == discounted_capex_expected + discounted_opex_metric_expected + ) + + assert np.isclose(outputs["lifetime_opex_mean"], opex_metric_expected) + assert outputs["discounted_opex_mean"] == discounted_opex_metric_expected + + assert ( + outputs["discounted_energy_mean"] == discounted_energy_metric_expected + ) + assert outputs["lcoe_mean"] == lcoe_metric_expected + + cost_breakdown = outputs["cost_breakdown"] + assert cost_breakdown["Discounted CAPEX"] == discounted_capex_expected + assert cost_breakdown["Discounted OPEX"] == discounted_opex_metric_expected + + opex_breakdown = outputs["opex_breakdown"] + assert opex_breakdown["Externalities"] == 216 + 180 + 150 + 125 + assert opex_breakdown["Maintenance"] == 4 + + capex_lcoe_breakdown = outputs["capex_lcoe_breakdown"] + + # Factor of 1e-1 to get to cent/kWh from Euro/MWh + assert ( + capex_lcoe_breakdown["Devices"] + == 10 * 1e6 / discounted_energy_metric_expected * 1e-1 + ) + assert ( + capex_lcoe_breakdown["Electrical Sub-Systems"] + == 5e6 / discounted_energy_metric_expected * 1e-1 + ) + assert ( + capex_lcoe_breakdown["Externalities"] + == 1e6 / discounted_energy_metric_expected * 1e-1 + ) + assert ( + capex_lcoe_breakdown["Installation"] + == 2e5 / discounted_energy_metric_expected * 1e-1 + ) + assert ( + capex_lcoe_breakdown["Condition Monitoring"] + == 2e4 / discounted_energy_metric_expected * 1e-1 + ) + + opex_lcoe_breakdown = outputs["opex_lcoe_breakdown"] + + # TODO: fix this rounding error + expected = round( + (216 + 180 + 150 + 125) / discounted_energy_metric_expected * 1e-1, + 2, + ) + assert abs(opex_lcoe_breakdown["Externalities"] - expected) < 0.02 + + expected = round( + 4 / discounted_energy_metric_expected * 1e-1, + 2, + ) + assert opex_lcoe_breakdown["Maintenance"] == expected + + lcoe_breakdown = outputs["lcoe_breakdown"] + assert np.isclose(lcoe_breakdown["CAPEX"], lcoe_capex_metric * 100) + + # TODO: fix this rounding error + expected = round(lcoe_opex_metric * 100, 2) + assert abs(lcoe_breakdown["OPEX"] - expected) < 0.02 From 705b3d5fe490206db4e1b5b25b94256e6475dacb Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Wed, 15 Apr 2026 16:22:37 +0100 Subject: [PATCH 18/40] Test output conversion for 8 simulations --- .../src/dtocean_economics/stats.py | 9 +- .../src/dtocean_plugins/themes/economics.py | 33 +- .../test_data/inputs_economics.py | 2 + .../test_data/inputs_economics_estimate.py | 1 - .../themes/test_themes_economics.py | 450 +++++++++++++++++- 5 files changed, 476 insertions(+), 19 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_economics/stats.py b/packages/dtocean-economics/src/dtocean_economics/stats.py index 0e9c476f..3955e7f4 100644 --- a/packages/dtocean-economics/src/dtocean_economics/stats.py +++ b/packages/dtocean-economics/src/dtocean_economics/stats.py @@ -194,7 +194,7 @@ def pdf(self, x_range=None, y_range=None, npoints=1000): return xx, yy, pdf -def pdf_confidence_densities(pdf, levels=None): +def pdf_confidence_densities(pdf, levels=None, xtol=2e-32): """Determine the required density values to satisfy a list of confidence levels in the given pdf""" @@ -216,9 +216,12 @@ def diff_frac(density, pdf, target_frac, pdf_sum): try: density = optimize.brentq( - diff_frac, pdf.min(), pdf.max(), args=(local_pdf, frac, pdf_sum) + diff_frac, + pdf.min(), + pdf.max(), + args=(local_pdf, frac, pdf_sum), + xtol=xtol, ) - densities.append(density) except ValueError as e: module_logger.debug(e, exc_info=True) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 075ed9a0..30ddbdab 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -510,6 +510,12 @@ def _get_outputs( externalities_capex: Optional[float], externalities_opex: Optional[float], ) -> dict[str, Any]: + series = [opex_bom, energy_record] + series_lengths = [len(x) for x in series if not x.empty] + if len(set(series_lengths)) != 1: + msg = "opex bom and energy record must be the same length if not empty" + raise ValueError(msg) + outputs: dict[str, Any] = { "capex_breakdown": None, "capex_total": None, @@ -589,7 +595,7 @@ def _get_outputs( discounted_energy = get_discounted_values(energy_record, discount_rate) if discounted_capex is not None: - lcoe_capex = discounted_capex / discounted_energy + lcoe_capex = discounted_capex_total / discounted_energy lcoe_total = lcoe_capex.copy() if discounted_opex is not None: @@ -620,7 +626,7 @@ def _get_outputs( discounted_opex, discounted_energy, lcoe_total, - capex_total, + discounted_capex_total, ) ) @@ -772,7 +778,7 @@ def _get_outputs_stats( discounted_opex, discounted_energy, lcoe_total, - capex_total, + discounted_capex_total, ): outputs: dict[str, Any] = { "lifetime_opex_mean": None, @@ -832,16 +838,22 @@ def _get_outputs_stats( distribution = BiVariateKDE(discounted_opex, discounted_energy) mean_coords = distribution.mean() - lcoe_mean = (capex_total + mean_coords[0]) / mean_coords[1] + opex_mean = mean_coords[0] + energy_mean = mean_coords[1] + lcoe_mean = (discounted_capex_total + opex_mean) / energy_mean + outputs["lcoe_mean"] = lcoe_mean * 1000 # Euro/Wh to Euro/kWh - outputs["discounted_opex_mean"] = mean_coords[0] - outputs["discounted_energy_mean"] = mean_coords[1] / 1e6 # W to MW + outputs["discounted_opex_mean"] = opex_mean + outputs["discounted_energy_mean"] = energy_mean / 1e6 # W to MW mode_coords = distribution.mode() - lcoe_mode = (capex_total + mean_coords[0]) / mean_coords[1] + opex_mode = mode_coords[0] + energy_mode = mode_coords[1] + lcoe_mode = (discounted_capex_total + opex_mode) / energy_mode + outputs["lcoe_mode"] = lcoe_mode * 1000 # Euro/Wh to Euro/kWh - outputs["discounted_opex_mode"] = mode_coords[0] - outputs["discounted_energy_mode"] = mode_coords[1] / 1e6 # W to MW + outputs["discounted_opex_mode"] = opex_mode + outputs["discounted_energy_mode"] = energy_mode / 1e6 # W to MW xx, yy, pdf = distribution.pdf() clevels = pdf_confidence_densities(pdf) @@ -859,7 +871,8 @@ def _get_outputs_stats( outputs["discounted_energy_upper"] = max(cy) / 1e6 # W to MW lcoes = [ - (capex_total + discounted_opex) / discounted_energy + (discounted_capex_total + discounted_opex) + / discounted_energy for discounted_opex, discounted_energy in zip(cx, cy) ] diff --git a/packages/dtocean-economics/test_data/inputs_economics.py b/packages/dtocean-economics/test_data/inputs_economics.py index 5a8d3a23..ed3550cb 100644 --- a/packages/dtocean-economics/test_data/inputs_economics.py +++ b/packages/dtocean-economics/test_data/inputs_economics.py @@ -13,6 +13,7 @@ electrical_network_efficiency = 0.99 capex_oandm = 100.0 externalities_capex = 1e6 +externalities_opex = 1e3 zero_bom_dict = { "Quantity": [5, 10], @@ -52,6 +53,7 @@ "project.energy_per_year": energy_record, "project.electrical_network_efficiency": electrical_network_efficiency, "project.externalities_capex": externalities_capex, + "project.externalities_opex": externalities_opex, } if __name__ == "__main__": diff --git a/packages/dtocean-economics/test_data/inputs_economics_estimate.py b/packages/dtocean-economics/test_data/inputs_economics_estimate.py index d07d8d1f..cd4a989d 100644 --- a/packages/dtocean-economics/test_data/inputs_economics_estimate.py +++ b/packages/dtocean-economics/test_data/inputs_economics_estimate.py @@ -19,7 +19,6 @@ "project.opex_estimate": 1e4, "project.annual_repair_cost_estimate": 1e4, "project.annual_array_mttf_estimate": 4383.0, - "project.electrical_network_efficiency": 0.95, "project.annual_energy": 10000.0, "project.estimate_energy_record": True, } diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index b2301144..6edfd4e5 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -9,6 +9,7 @@ from dtocean_core.core import Core from dtocean_core.menu import DataMenu, ProjectMenu, ThemeMenu from dtocean_core.pipeline import Tree, _get_connector +from scipy.integrate import simpson from dtocean_plugins.themes.economics import _get_outputs @@ -148,6 +149,8 @@ def test_economics_interface_entry( capex_bom = _get_outputs_args[0] opex_bom = _get_outputs_args[1] energy_record = _get_outputs_args[2] + externalities_capex = _get_outputs_args[4] + externalities_opex = _get_outputs_args[5] capex_bom_elec = capex_bom[ capex_bom["phase"] == "Electrical Sub-Systems" @@ -215,9 +218,12 @@ def test_economics_interface_entry( assert capex_bom_ext_i["unitary_cost"] == 1e6 assert capex_bom_ext_i["project_year"] == 0 + assert externalities_capex == 1e6 + assert externalities_opex == 1e3 + expected_opex_bom_dict = { "project_year": [3, 4], - "Cost": [1000.0, 2000.0], + "Cost": [1000.0 + externalities_opex, 2000.0 + externalities_opex], } expected_opex_bom = pd.DataFrame(expected_opex_bom_dict) pd.testing.assert_frame_equal(expected_opex_bom, opex_bom) @@ -363,7 +369,7 @@ def test_economics_interface_entry_estimate( assert len(energy_record_energies) == 1 energy_record_energy = energy_record_energies.pop() - assert energy_record_energy == 10000 * 1e6 * 0.95 + assert energy_record_energy == 10000 * 1e6 # These factors become 1 when used with a 1 / 5 discount rate in the respective @@ -457,13 +463,13 @@ def test_get_outputs_0_externalities( "discounted_opex_lower", "discounted_opex_mode", "discounted_opex_upper", - "lcoe_lower", "lcoe_mode", - "lcoe_pdf", + "lcoe_lower", "lcoe_upper", + "lcoe_pdf", "lifetime_cost_mode", - "lifetime_opex_lower", "lifetime_opex_mode", + "lifetime_opex_lower", "lifetime_opex_upper", ] for key in none_outputs: @@ -611,3 +617,437 @@ def test_get_outputs_0_externalities( # TODO: fix this rounding error expected = round(lcoe_opex_metric * 100, 2) assert abs(lcoe_breakdown["OPEX"] - expected) < 0.02 + + +@pytest.fixture() +def opex_costs_8(): + opex_dict = { + "project_year": [0, 1, 2, 3], + "cost 0": [ + 0.5 * 1 * 1e5, + 0.5 * YEAR_ONE * 1e5, + 0.5 * YEAR_TWO * 1e5, + 0.5 * YEAR_THREE * 1e5, + ], + "cost 1": [ + 1 * 1 * 1e5, + 1 * YEAR_ONE * 1e5, + 1 * YEAR_TWO * 1e5, + 1 * YEAR_THREE * 1e5, + ], + "cost 2": [ + 1.5 * 1 * 1e5, + 1.5 * YEAR_ONE * 1e5, + 1.5 * YEAR_TWO * 1e5, + 1.5 * YEAR_THREE * 1e5, + ], + "cost 3": [ + 0.5 * 1 * 1e5, + 0.5 * YEAR_ONE * 1e5, + 0.5 * YEAR_TWO * 1e5, + 0.5 * YEAR_THREE * 1e5, + ], + "cost 4": [ + 1.5 * 1 * 1e5, + 1.5 * YEAR_ONE * 1e5, + 1.5 * YEAR_TWO * 1e5, + 1.5 * YEAR_THREE * 1e5, + ], + "cost 5": [ + 0.75 * 1 * 1e5, + 0.75 * YEAR_ONE * 1e5, + 0.75 * YEAR_TWO * 1e5, + 0.75 * YEAR_THREE * 1e5, + ], + "cost 6": [ + 1 * 1 * 1e5, + 1 * YEAR_ONE * 1e5, + 1 * YEAR_TWO * 1e5, + 1 * YEAR_THREE * 1e5, + ], + "cost 7": [ + 1.25 * 1 * 1e5, + 1.25 * YEAR_ONE * 1e5, + 1.25 * YEAR_TWO * 1e5, + 1.25 * YEAR_THREE * 1e5, + ], + "cost 8": [ + 1 * 1 * 1e5, + 1 * YEAR_ONE * 1e5, + 1 * YEAR_TWO * 1e5, + 1 * YEAR_THREE * 1e5, + ], + } + + opex_df = pd.DataFrame(opex_dict) + + return opex_df + + +@pytest.fixture() +def energy_record_8(): + energy_dict = { + "project_year": [0, 1, 2, 3], + "energy 0": [ + 0.5 * 1 * 1e6, + 0.5 * 1 * YEAR_ONE * 1e6, + 0.5 * 1 * YEAR_TWO * 1e6, + 0.5 * 1 * YEAR_THREE * 1e6, + ], + "energy 1": [ + 1 * 1 * 1e6, + 1 * YEAR_ONE * 1e6, + 1 * YEAR_TWO * 1e6, + 1 * YEAR_THREE * 1e6, + ], + "energy 2": [ + 0.5 * 1 * 1e6, + 0.5 * YEAR_ONE * 1e6, + 0.5 * YEAR_TWO * 1e6, + 0.5 * YEAR_THREE * 1e6, + ], + "energy 3": [ + 1.5 * 1 * 1e6, + 1.5 * YEAR_ONE * 1e6, + 1.5 * YEAR_TWO * 1e6, + 1.5 * YEAR_THREE * 1e6, + ], + "energy 4": [ + 1.5 * 1 * 1e6, + 1.5 * YEAR_ONE * 1e6, + 1.5 * YEAR_TWO * 1e6, + 1.5 * YEAR_THREE * 1e6, + ], + "energy 5": [ + 1 * 1 * 1e6, + 1 * YEAR_ONE * 1e6, + 1 * YEAR_TWO * 1e6, + 1 * YEAR_THREE * 1e6, + ], + "energy 6": [ + 0.75 * 1 * 1e6, + 0.75 * YEAR_ONE * 1e6, + 0.75 * YEAR_TWO * 1e6, + 0.75 * YEAR_THREE * 1e6, + ], + "energy 7": [ + 1 * 1 * 1e6, + 1 * YEAR_ONE * 1e6, + 1 * YEAR_TWO * 1e6, + 1 * YEAR_THREE * 1e6, + ], + "energy 8": [ + 1.25 * 1 * 1e6, + 1.25 * YEAR_ONE * 1e6, + 1.25 * YEAR_TWO * 1e6, + 1.25 * YEAR_THREE * 1e6, + ], + } + + energy_df = pd.DataFrame(energy_dict) + + return energy_df + + +def test_get_outputs_8( + bom, + opex_costs_8, + energy_record_8, +): + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + opex_costs_8, + energy_record_8, + discount_rate, + 1e6, + None, + ) + + none_outputs = ["opex_breakdown", "opex_lcoe_breakdown"] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + lifetime_opex_expected = 1e5 * (1 + YEAR_ONE + YEAR_TWO + YEAR_THREE) + + assert np.isclose(outputs["lifetime_opex_mean"], lifetime_opex_expected) + lifetime_opex_mode_error = ( + abs(outputs["lifetime_opex_mode"] - lifetime_opex_expected) + / lifetime_opex_expected + * 100 + ) + assert lifetime_opex_mode_error < 0.1 + + # TODO: need a more accurate test + assert outputs["lifetime_opex_lower"] < lifetime_opex_expected + assert outputs["lifetime_opex_upper"] > lifetime_opex_expected + + discounted_opex_expected = 4 * 1e5 + assert np.isclose(outputs["discounted_opex_mean"], discounted_opex_expected) + assert np.isclose(outputs["discounted_opex_mode"], discounted_opex_expected) + assert outputs["discounted_opex_lower"] < discounted_opex_expected + assert outputs["discounted_opex_upper"] > discounted_opex_expected + + discounted_energy_expected = 4.0 + assert np.isclose( + outputs["discounted_energy_mean"], discounted_energy_expected + ) + assert np.isclose( + outputs["discounted_energy_mode"], discounted_energy_expected + ) + assert outputs["discounted_energy_lower"] < discounted_energy_expected + assert outputs["discounted_energy_upper"] > discounted_energy_expected + + discounted_capex_expected = 10 * 1e6 + 5e6 + 1e6 + 2 * (1e5 + 1e4) + lcoe_expected = ( + (discounted_capex_expected + discounted_opex_expected) + / discounted_energy_expected + / 1000 + ) + assert np.isclose(outputs["lcoe_mean"], lcoe_expected) + assert np.isclose(outputs["lcoe_mode"], lcoe_expected) + assert outputs["lcoe_lower"] < lcoe_expected + assert outputs["lcoe_upper"] > lcoe_expected + + assert "values" in outputs["lcoe_pdf"] + assert "coords" in outputs["lcoe_pdf"] + + z = outputs["lcoe_pdf"]["values"] + coords = outputs["lcoe_pdf"]["coords"] + x = coords[0] + y = coords[1] + pdf_total = simpson(simpson(z, y), x) + assert np.isclose(pdf_total, 1, rtol=1e-4) + + assert z.min() <= outputs["confidence_density"] <= z.max() + + capex_expected = ( + 10 * 1e6 + + 5e6 + + (YEAR_ONE + YEAR_TWO) * 1e5 + + (YEAR_ONE + YEAR_TWO) * 1e4 + + 1e6 + ) + lifetime_cost_expected = capex_expected + lifetime_opex_expected + lifetime_cost_mode_error = ( + abs(outputs["lifetime_cost_mode"] - lifetime_cost_expected) + / lifetime_cost_expected + * 100 + ) + assert lifetime_cost_mode_error < 0.01 + + discounted_lifetime_cost_expected = ( + discounted_capex_expected + discounted_opex_expected + ) + np.isclose( + outputs["discounted_lifetime_cost_mode"], + discounted_lifetime_cost_expected, + ) + + +def test_get_outputs_8_BiVariateKDE_error( + mocker, + bom, + opex_costs_8, + energy_record_8, +): + mocker.patch( + "dtocean_plugins.themes.economics.BiVariateKDE", + side_effect=np.linalg.LinAlgError(), + ) + + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + opex_costs_8, + energy_record_8, + discount_rate, + 1e6, + None, + ) + + none_outputs = [ + "opex_breakdown", + "opex_lcoe_breakdown", + "confidence_density", + "lcoe_pdf", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + lifetime_opex_expected = 1e5 * (1 + YEAR_ONE + YEAR_TWO + YEAR_THREE) + + assert np.isclose(outputs["lifetime_opex_mean"], lifetime_opex_expected) + lifetime_opex_mode_error = ( + abs(outputs["lifetime_opex_mode"] - lifetime_opex_expected) + / lifetime_opex_expected + * 100 + ) + assert lifetime_opex_mode_error < 0.1 + + # TODO: need a more accurate test + assert outputs["lifetime_opex_lower"] < lifetime_opex_expected + assert outputs["lifetime_opex_upper"] > lifetime_opex_expected + + discounted_opex_expected = 4 * 1e5 + assert np.isclose(outputs["discounted_opex_mean"], discounted_opex_expected) + assert np.isclose( + outputs["discounted_opex_mode"], + discounted_opex_expected, + rtol=1e-3, + ) + assert outputs["discounted_opex_lower"] < discounted_opex_expected + assert outputs["discounted_opex_upper"] > discounted_opex_expected + + discounted_energy_expected = 4.0 + assert np.isclose( + outputs["discounted_energy_mean"], + discounted_energy_expected, + ) + assert np.isclose( + outputs["discounted_energy_mode"], + discounted_energy_expected, + rtol=1e-3, + ) + assert outputs["discounted_energy_lower"] < discounted_energy_expected + assert outputs["discounted_energy_upper"] > discounted_energy_expected + + # TODO: lcoe calculations are way off when using lcoe stats directly + discounted_capex_expected = 10 * 1e6 + 5e6 + 1e6 + 2 * (1e5 + 1e4) + lcoe_expected = ( + (discounted_capex_expected + discounted_opex_expected) + / discounted_energy_expected + / 1000 + ) + lcoe_mean_error = ( + abs(outputs["lcoe_mean"] - lcoe_expected) / lcoe_expected * 100 + ) + assert lcoe_mean_error < 20 + + lcoe_mode_error = ( + abs(outputs["lcoe_mode"] - lcoe_expected) / lcoe_expected * 100 + ) + assert lcoe_mode_error < 20 + + assert outputs["lcoe_lower"] < lcoe_expected + assert outputs["lcoe_upper"] > lcoe_expected + + capex_expected = ( + 10 * 1e6 + + 5e6 + + (YEAR_ONE + YEAR_TWO) * 1e5 + + (YEAR_ONE + YEAR_TWO) * 1e4 + + 1e6 + ) + lifetime_cost_expected = capex_expected + lifetime_opex_expected + lifetime_cost_mode_error = ( + abs(outputs["lifetime_cost_mode"] - lifetime_cost_expected) + / lifetime_cost_expected + * 100 + ) + assert lifetime_cost_mode_error < 0.01 + + discounted_lifetime_cost_expected = ( + discounted_capex_expected + discounted_opex_expected + ) + np.isclose( + outputs["discounted_lifetime_cost_mode"], + discounted_lifetime_cost_expected, + ) + + +def test_get_outputs_8_UniVariateKDE_error( + mocker, + bom, + opex_costs_8, + energy_record_8, +): + mocker.patch( + "dtocean_plugins.themes.economics.BiVariateKDE", + side_effect=np.linalg.LinAlgError(), + ) + mocker.patch( + "dtocean_plugins.themes.economics.UniVariateKDE", + side_effect=np.linalg.LinAlgError(), + ) + + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + opex_costs_8, + energy_record_8, + discount_rate, + 1e6, + None, + ) + + none_outputs = [ + "discounted_lifetime_cost_mode", + "discounted_energy_lower", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_opex_lower", + "discounted_opex_mode", + "discounted_opex_upper", + "lifetime_cost_mode", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + "opex_breakdown", + "opex_lcoe_breakdown", + "lcoe_mode", + "lcoe_lower", + "lcoe_upper", + "confidence_density", + "lcoe_pdf", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + lifetime_opex_expected = 1e5 * (1 + YEAR_ONE + YEAR_TWO + YEAR_THREE) + assert np.isclose(outputs["lifetime_opex_mean"], lifetime_opex_expected) + + discounted_opex_expected = 4 * 1e5 + assert np.isclose(outputs["discounted_opex_mean"], discounted_opex_expected) + + discounted_energy_expected = 4.0 + assert np.isclose( + outputs["discounted_energy_mean"], + discounted_energy_expected, + ) + + # TODO: lcoe stats calculations are way off when using lcoe values directly + discounted_capex_expected = 10 * 1e6 + 5e6 + 1e6 + 2 * (1e5 + 1e4) + lcoe_expected = ( + (discounted_capex_expected + discounted_opex_expected) + / discounted_energy_expected + / 1000 + ) + lcoe_mean_error = ( + abs(outputs["lcoe_mean"] - lcoe_expected) / lcoe_expected * 100 + ) + assert lcoe_mean_error < 20 From b666db96ac1585e07576887177b180e2ff85c64d Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Wed, 15 Apr 2026 17:19:47 +0100 Subject: [PATCH 19/40] Add LCOE PDF plot Requires testing --- .../src/dtocean_plugins/plots/plots_lcoe.py | 140 ++++++++++++++++++ .../tests/dtocean_plugins/plots/conftest.py | 3 + .../dtocean_plugins/plots/test_plots_lcoe.py | 0 3 files changed, 143 insertions(+) create mode 100644 packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py create mode 100644 packages/dtocean-economics/tests/dtocean_plugins/plots/conftest.py create mode 100644 packages/dtocean-economics/tests/dtocean_plugins/plots/test_plots_lcoe.py diff --git a/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py b/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py new file mode 100644 index 00000000..a5b8c448 --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py @@ -0,0 +1,140 @@ +# Copyright (C) 2026 Mathew Topper +# +# 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 . + +import matplotlib.colors as colors +import matplotlib.pyplot as plt +from matplotlib.lines import Line2D + +from dtocean_plugins.plots.base import PlotInterface + + +class LCOEPDFPlot(PlotInterface): + @classmethod + def get_name(cls): + """A class method for the common name of the interface. + + Returns: + str: A unique string + """ + + return "LCOE PDF Plot" + + @classmethod + def declare_inputs(cls): + """A class method to declare all the variables required as inputs by + this interface. + + Returns: + list: List of inputs identifiers + + Example: + The returned value can be None or a list of identifier strings which + appear in the data descriptions. For example:: + + inputs = ["My:first:variable", + "My:second:variable", + ] + """ + + input_list = [ + "project.economics_metrics", + "project.lcoe_pdf", + "project.confidence_density", + ] + + return input_list + + @classmethod + def declare_optional(cls): + return [] + + @classmethod + def declare_id_map(cls): + """Declare the mapping for variable identifiers in the data description + to local names for use in the interface. This helps isolate changes in + the data description or interface from effecting the other. + + Returns: + dict: Mapping of local to data description variable identifiers + + Example: + The returned value must be a dictionary containing all the inputs and + outputs from the data description and a local alias string. For + example:: + + id_map = {"var1": "My:first:variable", + "var2": "My:second:variable", + "var3": "My:third:variable" + } + + """ + + id_map = { + "economics_metrics": "project.economics_metrics", + "confidence_density": "project.confidence_density", + "lcoe_pdf": "project.lcoe_pdf", + } + + return id_map + + def connect(self): + clevels = [self.data.confidence_density] + legend_element = Line2D( + [0], + [0], + color="k", + lw=1, + label="95% Confidence Level", + ) + + xx = self.data.lcoe_pdf.coords["Discounted OPEX"].values + yy = self.data.lcoe_pdf.coords["Discounted Energy"].values + zz = self.data.lcoe_pdf.data.values + + plt.figure() + cf = plt.contourf( + xx, + yy, + zz.T, + 32, + cmap="OrRd", + norm=colors.PowerNorm( + gamma=1, + vmin=0.5 * self.data.confidence_density, + ), + ) + cf.cmap.set_under("w") + plt.contour(xx, yy, zz.T, clevels, colors="k") + + opex = self.data.economics_metrics["Discounted OPEX"] + energy = self.data.economics_metrics["Discounted Energy"] / 1000 + + sp = plt.scatter( + opex, + energy, + marker="x", + s=20, + zorder=10, + color="k", + label="Data Points", + ) + plt.colorbar(cf) + plt.legend( + handles=[legend_element, sp], + scatterpoints=1, + ) + + plt.xlabel("Discounted OPEX [Euro]") + plt.ylabel("Discounted Energy [kWh]") diff --git a/packages/dtocean-economics/tests/dtocean_plugins/plots/conftest.py b/packages/dtocean-economics/tests/dtocean_plugins/plots/conftest.py new file mode 100644 index 00000000..df1e86f6 --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_plugins/plots/conftest.py @@ -0,0 +1,3 @@ +import pytest + +pytest.importorskip("dtocean_core") diff --git a/packages/dtocean-economics/tests/dtocean_plugins/plots/test_plots_lcoe.py b/packages/dtocean-economics/tests/dtocean_plugins/plots/test_plots_lcoe.py new file mode 100644 index 00000000..e69de29b From 3fdf1c00334f62c4ca34bb67bbfb8b03a82915ca Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 16 Apr 2026 13:43:18 +0100 Subject: [PATCH 20/40] Fix bug reading values from _get_outputs --- .../dtocean-economics/src/dtocean_plugins/themes/economics.py | 2 +- .../tests/dtocean_plugins/themes/test_themes_economics.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 30ddbdab..7976e47f 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -498,7 +498,7 @@ def connect(self, debug_entry=False): self.data.externalities_opex, ) - for k, v in outputs: + for k, v in outputs.items(): self.data[k] = v diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index 6edfd4e5..1dae06ac 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -118,6 +118,7 @@ def test_economics_interface_entry( _get_outputs: MagicMock = mocker.patch( "dtocean_plugins.themes.economics._get_outputs", autospec=True, + return_value={"lcoe_mean": 1}, ) project_menu = ProjectMenu() From 1343d56f5eece05a82f3ebe79ae2a154c1068700 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 16 Apr 2026 13:45:01 +0100 Subject: [PATCH 21/40] Add test for LCOEPDFPlot --- .gitattributes | 1 + .../src/dtocean_plugins/plots/plots_lcoe.py | 17 +- .../test_data/lcoe_pdf_plot/eco_metrics.xlsx | 3 + .../test_data/lcoe_pdf_plot/lcoe_pdf.nc | 3 + .../dtocean_plugins/plots/test_plots_lcoe.py | 204 ++++++++++++++++++ 5 files changed, 223 insertions(+), 5 deletions(-) create mode 100644 packages/dtocean-economics/test_data/lcoe_pdf_plot/eco_metrics.xlsx create mode 100644 packages/dtocean-economics/test_data/lcoe_pdf_plot/lcoe_pdf.nc diff --git a/.gitattributes b/.gitattributes index 4f6ef923..8f381a36 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,4 @@ *.xcf filter=lfs diff=lfs merge=lfs -text *.svg filter=lfs diff=lfs merge=lfs -text *.xlsx filter=lfs diff=lfs merge=lfs -text +*.nc filter=lfs diff=lfs merge=lfs -text diff --git a/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py b/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py index a5b8c448..bea42fff 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py +++ b/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py @@ -29,7 +29,7 @@ def get_name(cls): str: A unique string """ - return "LCOE PDF Plot" + return "LCOE PDF Analysis" @classmethod def declare_inputs(cls): @@ -100,8 +100,10 @@ def connect(self): ) xx = self.data.lcoe_pdf.coords["Discounted OPEX"].values - yy = self.data.lcoe_pdf.coords["Discounted Energy"].values - zz = self.data.lcoe_pdf.data.values + yy = ( + self.data.lcoe_pdf.coords["Discounted Energy"].values / 1e6 + ) # Wh to MWh + zz = self.data.lcoe_pdf.data plt.figure() cf = plt.contourf( @@ -119,7 +121,7 @@ def connect(self): plt.contour(xx, yy, zz.T, clevels, colors="k") opex = self.data.economics_metrics["Discounted OPEX"] - energy = self.data.economics_metrics["Discounted Energy"] / 1000 + energy = self.data.economics_metrics["Discounted Energy"] sp = plt.scatter( opex, @@ -137,4 +139,9 @@ def connect(self): ) plt.xlabel("Discounted OPEX [Euro]") - plt.ylabel("Discounted Energy [kWh]") + plt.ylabel("Discounted Energy [MWh]") + + plt.title("LCOE PDF Analysis") + plt.tight_layout() + + self.fig_handle = plt.gcf() diff --git a/packages/dtocean-economics/test_data/lcoe_pdf_plot/eco_metrics.xlsx b/packages/dtocean-economics/test_data/lcoe_pdf_plot/eco_metrics.xlsx new file mode 100644 index 00000000..3b2b366b --- /dev/null +++ b/packages/dtocean-economics/test_data/lcoe_pdf_plot/eco_metrics.xlsx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3f801ea608b2d492169878fb79d35fc935e7976c5e1f6d02a9083a8bca2e32f +size 8203 diff --git a/packages/dtocean-economics/test_data/lcoe_pdf_plot/lcoe_pdf.nc b/packages/dtocean-economics/test_data/lcoe_pdf_plot/lcoe_pdf.nc new file mode 100644 index 00000000..2cd05272 --- /dev/null +++ b/packages/dtocean-economics/test_data/lcoe_pdf_plot/lcoe_pdf.nc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3a3ff7defddd95f58c79a19f41ab7ba23953eb6559e1ce535ea946dbd2546df +size 8023199 diff --git a/packages/dtocean-economics/tests/dtocean_plugins/plots/test_plots_lcoe.py b/packages/dtocean-economics/tests/dtocean_plugins/plots/test_plots_lcoe.py index e69de29b..36ca706a 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/plots/test_plots_lcoe.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/plots/test_plots_lcoe.py @@ -0,0 +1,204 @@ +from pathlib import Path + +import pytest +from dtocean_core.core import Core +from dtocean_core.menu import ModuleMenu, ProjectMenu +from dtocean_core.pipeline import Tree +from matplotlib import pyplot as plt + +from dtocean_plugins.modules.base import ModuleInterface + +DIR_PATH = Path(__file__).parent +ROOT_DIR_PATH = DIR_PATH.parents[2] +TEST_DATA_DIR_PATH = ROOT_DIR_PATH / "test_data" / "lcoe_pdf_plot" + + +class MockModule(ModuleInterface): + @classmethod + def get_name(cls): + return "Mock Module" + + @classmethod + def declare_weight(cls): + return 999 + + @classmethod + def declare_inputs(cls): + input_list = [ + "project.economics_metrics", + "project.lcoe_pdf", + "project.confidence_density", + ] + + return input_list + + @classmethod + def declare_outputs(cls): + return None + + @classmethod + def declare_optional(cls): + return None + + @classmethod + def declare_id_map(cls): + id_map = { + "economics_metrics": "project.economics_metrics", + "confidence_density": "project.confidence_density", + "lcoe_pdf": "project.lcoe_pdf", + } + + return id_map + + def connect(self, debug_entry=False, export_data=True): + pass + + +@pytest.fixture() +def tree(): + """Share a Tree object""" + + new_tree = Tree() + + return new_tree + + +# Using a py.test fixture to reduce boilerplate and test times. +@pytest.fixture() +def core(): + """Share a Core object""" + + new_core = Core() + socket = new_core.control._sequencer.get_socket("ModuleInterface") + socket.add_interface(MockModule) + + return new_core + + +@pytest.fixture() +def project(core, tree): + """Share a Project object""" + project_title = "Test" + project_menu = ProjectMenu() + + new_project = project_menu.new_project(core, project_title) + + options_branch = tree.get_branch(core, new_project, "System Type Selection") + device_type = options_branch.get_input_variable( + core, new_project, "device.system_type" + ) + device_type.set_raw_interface(core, "Tidal Fixed") + device_type.read(core, new_project) + + project_menu.initiate_pipeline(core, new_project) + + return new_project + + +def test_LCOEPDFPlot_available( + core, + project, + tree, +): + module_menu = ModuleMenu() + project_menu = ProjectMenu() + + mod_name = "Mock Module" + module_menu.activate(core, project, mod_name) + project_menu.initiate_dataflow(core, project) + + mod_branch = tree.get_branch(core, project, mod_name) + eco_metrics = mod_branch.get_input_variable( + core, + project, + "project.economics_metrics", + ) + assert eco_metrics is not None + + eco_metrics.set_file_interface( + core, + TEST_DATA_DIR_PATH / "eco_metrics.xlsx", + ) + eco_metrics.read(core, project) + + lcoe_pdf = mod_branch.get_input_variable( + core, + project, + "project.lcoe_pdf", + ) + assert lcoe_pdf is not None + + lcoe_pdf.set_file_interface( + core, + TEST_DATA_DIR_PATH / "lcoe_pdf.nc", + ) + lcoe_pdf.read(core, project) + + confidence_density = mod_branch.get_input_variable( + core, + project, + "project.confidence_density", + ) + assert confidence_density is not None + + confidence_density.set_raw_interface(core, 1.40122390504e-07) + confidence_density.read(core, project) + + result = lcoe_pdf.get_available_plots(core, project) + + assert "LCOE PDF Analysis" in result + + +def test_LCOEPDFPlot( + core, + project, + tree, +): + module_menu = ModuleMenu() + project_menu = ProjectMenu() + + mod_name = "Mock Module" + module_menu.activate(core, project, mod_name) + project_menu.initiate_dataflow(core, project) + + mod_branch = tree.get_branch(core, project, mod_name) + eco_metrics = mod_branch.get_input_variable( + core, + project, + "project.economics_metrics", + ) + assert eco_metrics is not None + + eco_metrics.set_file_interface( + core, + TEST_DATA_DIR_PATH / "eco_metrics.xlsx", + ) + eco_metrics.read(core, project) + + lcoe_pdf = mod_branch.get_input_variable( + core, + project, + "project.lcoe_pdf", + ) + assert lcoe_pdf is not None + + lcoe_pdf.set_file_interface( + core, + TEST_DATA_DIR_PATH / "lcoe_pdf.nc", + ) + lcoe_pdf.read(core, project) + + confidence_density = mod_branch.get_input_variable( + core, + project, + "project.confidence_density", + ) + assert confidence_density is not None + + confidence_density.set_raw_interface(core, 1.40122390504e-07) + confidence_density.read(core, project) + + lcoe_pdf.plot(core, project, "LCOE PDF Analysis") + + assert len(plt.get_fignums()) == 1 + plt.close("all") From 5a584fdfcabff69b8d908686908e3fbd6738c8ad Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 16 Apr 2026 17:17:59 +0100 Subject: [PATCH 22/40] Add semantic release config and test publish --- .github/workflows/release-economics.yml | 106 ++++++++++++++++++++++ packages/dtocean-economics/pyproject.toml | 35 +++++++ packages/dtocean/pyproject.toml | 1 + pyproject.toml | 4 + 4 files changed, 146 insertions(+) create mode 100644 .github/workflows/release-economics.yml diff --git a/.github/workflows/release-economics.yml b/.github/workflows/release-economics.yml new file mode 100644 index 00000000..50954cd4 --- /dev/null +++ b/.github/workflows/release-economics.yml @@ -0,0 +1,106 @@ +name: Continuous delivery + +on: + push: + branches: + - dtocean_economics + +permissions: + contents: read + +env: + DTOCEAN_ECONOMICS_DIR: packages/dtocean-economics + RELEASING_REPO: H0R5E/dtocean + +jobs: + release: + runs-on: ubuntu-latest + concurrency: + group: ${{ github.workflow }}-release-${{ github.ref_name }} + cancel-in-progress: false + permissions: + contents: write + outputs: + dtocean-economics-released: ${{ steps.release-dtocean-economics.outputs.released }} + dtocean-economics-commit_sha: ${{ steps.release-dtocean-economics.outputs.commit_sha }} + + steps: + - name: Wait for all test jobs + uses: lewagon/wait-on-check-action@v1.5.0 + with: + ref: ${{ github.sha }} + check-regexp: "(?i)^.*(test|audit).*$" + repo-token: ${{ secrets.GITHUB_TOKEN }} + fail-on-no-checks: false + + # Note: We checkout the repository at the branch that triggered the workflow. + # Python Semantic Release will automatically convert shallow clones to full clones + # if needed to ensure proper history evaluation. However, we forcefully reset the + # branch to the workflow sha because it is possible that the branch was updated + # while the workflow was running, which prevents accidentally releasing un-evaluated + # changes. + - name: Checkout repository on release branch + uses: actions/checkout@v6 + with: + ref: ${{ github.ref_name }} + fetch-depth: 0 + + - name: Force release branch to be at workflow sha + run: | + git reset --hard ${{ github.sha }} + + - name: Release dtocean-economics + id: release-dtocean-economics + uses: python-semantic-release/python-semantic-release@v10.5.3 + with: + commit: ${{ github.repository == env.RELEASING_REPO }} + directory: ${{ env.DTOCEAN_ECONOMICS_DIR }} + github_token: ${{ secrets.GITHUB_TOKEN }} + push: ${{ github.repository == env.RELEASING_REPO }} + vcs_release: false + + publish-dtocean-economics: + runs-on: ubuntu-latest + needs: release + if: needs.release.outputs.dtocean-economics-released == 'true' + permissions: + id-token: write + defaults: + run: + working-directory: ${{ env.DTOCEAN_ECONOMICS_DIR }} + environment: + name: testpypi + url: https://test.pypi.org/project/dtocean-economics/ + steps: + - name: Setup | Checkout repository on commit sha + uses: actions/checkout@v6 + with: + lfs: true + ref: ${{ needs.release.outputs.dtocean-economics-commit_sha }} + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.13" + + - name: Install poetry + uses: abatilo/actions-poetry@v2 + + - name: Install poetry-monoranger-plugin + shell: bash + run: | + poetry self add git+https://github.com/H0R5E/poetry-monoranger-plugin.git#include_groups + + - name: Update Poetry configuration + run: poetry config virtualenvs.create false + + - name: Package project + run: poetry build + + - name: Publish package distributions to PyPI + if: ${{ github.repository == env.RELEASING_REPO }} + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: ${{ env.DTOCEAN_ECONOMICS_DIR }}/dist + verbose: true + repository-url: https://test.pypi.org/legacy/ diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index d7d06b88..063f9f24 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -17,6 +17,10 @@ classifiers = [ "Operating System :: Microsoft :: Windows", "Operating System :: POSIX :: Linux", ] +packages = [ + { include = "dtocean_economics", from = "src" }, + { include = "dtocean_plugins", from = "src" }, +] [tool.poetry.urls] "Bug Tracker" = "https://github.com/DTOcean/dtocean/issues" @@ -74,6 +78,37 @@ typeCheckingMode = "basic" [tool.ruff] line-length = 80 +[tool.semantic_release] +commit_parser = "../../scripts/dtocean_commit_parser.py:DTOceanCommitParser" +commit_message = """\ +chore(release): dtocean-economics@{version} + +Automatically generated by python-semantic-release +""" +tag_format = "dtocean-economics-v{version}" +version_toml = ["pyproject.toml:tool.poetry.version"] + +[tool.semantic_release.branches.main] +match = "(main)" + +[tool.semantic_release.changelog] +# Recommended patterns for conventional commits parser that is scope aware +exclude_commit_patterns = [ + '''chore(?:\([^)]*?\))?: .+''', + '''ci(?:\([^)]*?\))?: .+''', + '''refactor(?:\([^)]*?\))?: .+''', + '''style(?:\([^)]*?\))?: .+''', + '''test(?:\([^)]*?\))?: .+''', + '''build\((?!deps\): .+)''', + '''Initial [Cc]ommit.*''', +] + +[tool.semantic_release.commit_parser_options] +scope_prefix = "dtocean-economics" + +[tool.semantic_release.commit_parser_options.path_filters.main] +paths = ["."] + [tool.tox] requires = ["tox>=4.19"] env_list = ["3.14", "3.13", "3.12", "audit"] diff --git a/packages/dtocean/pyproject.toml b/packages/dtocean/pyproject.toml index 5a609b76..5724dbdf 100644 --- a/packages/dtocean/pyproject.toml +++ b/packages/dtocean/pyproject.toml @@ -31,6 +31,7 @@ include-groups = ["dtocean"] [tool.poetry.group.dtocean.dependencies] dtocean-app = { path = "../dtocean-app", develop = true } +dtocean-economics = { path = "../dtocean-economics", develop = true } dtocean-docs = { path = "../dtocean-docs", develop = true } dtocean-hydrodynamics = { path = "../dtocean-hydrodynamics", develop = true } diff --git a/pyproject.toml b/pyproject.toml index 0b606433..8da6b470 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -137,6 +137,10 @@ paths = ["packages/dtocean"] paths = ["packages/dtocean-app"] trigger_bump_level = 4 +[tool.semantic_release.commit_parser_options.path_filters.dtocean-economics] +paths = ["packages/dtocean-economics"] +trigger_bump_level = 4 + [tool.semantic_release.commit_parser_options.path_filters.dtocean-hydrodynamics] paths = ["packages/dtocean-hydrodynamics"] trigger_bump_level = 4 From 450d692cf8be9051dc31dd8a907fb3bdeab5b406 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 16 Apr 2026 17:20:37 +0100 Subject: [PATCH 23/40] fix: add dtocean_economics to release branches --- packages/dtocean-economics/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index 063f9f24..cdaa1fcf 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -89,7 +89,7 @@ tag_format = "dtocean-economics-v{version}" version_toml = ["pyproject.toml:tool.poetry.version"] [tool.semantic_release.branches.main] -match = "(main)" +match = "(main|dtocean_economics)" [tool.semantic_release.changelog] # Recommended patterns for conventional commits parser that is scope aware From 6f08b864aaae6595aedfba0a46a3af1b939f1675 Mon Sep 17 00:00:00 2001 From: semantic-release Date: Thu, 16 Apr 2026 16:21:46 +0000 Subject: [PATCH 24/40] chore(release): dtocean-economics@2.0.1 Automatically generated by python-semantic-release --- packages/dtocean-economics/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index cdaa1fcf..16c41d2e 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "dtocean-economics" -version = "2.0.0" +version = "2.0.1" description = "Economic assessment module for the DTOcean tools" authors = ["The DTOcean Developers"] maintainers = ["Mathew Topper "] From dff6681eab9c996415943774efb7eccaaa7ab108 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 16 Apr 2026 17:23:47 +0100 Subject: [PATCH 25/40] fix(dtocean-economics): try again From c8b3fcf5642aba31476569bc805911b235a08521 Mon Sep 17 00:00:00 2001 From: semantic-release Date: Thu, 16 Apr 2026 16:25:42 +0000 Subject: [PATCH 26/40] chore(release): dtocean-economics@2.0.2 Automatically generated by python-semantic-release --- packages/dtocean-economics/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index 16c41d2e..e6e07a14 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "dtocean-economics" -version = "2.0.1" +version = "2.0.2" description = "Economic assessment module for the DTOcean tools" authors = ["The DTOcean Developers"] maintainers = ["Mathew Topper "] From c6671d6017997b02dba6aa84f8745b8d3e71ee0e Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Thu, 16 Apr 2026 17:37:45 +0100 Subject: [PATCH 27/40] Add test release steps to main release workflow Delete test release workflow --- .github/workflows/release-economics.yml | 106 ---------------------- .github/workflows/release.yml | 68 +++++++++++++- packages/dtocean-economics/pyproject.toml | 2 +- 3 files changed, 64 insertions(+), 112 deletions(-) delete mode 100644 .github/workflows/release-economics.yml diff --git a/.github/workflows/release-economics.yml b/.github/workflows/release-economics.yml deleted file mode 100644 index 50954cd4..00000000 --- a/.github/workflows/release-economics.yml +++ /dev/null @@ -1,106 +0,0 @@ -name: Continuous delivery - -on: - push: - branches: - - dtocean_economics - -permissions: - contents: read - -env: - DTOCEAN_ECONOMICS_DIR: packages/dtocean-economics - RELEASING_REPO: H0R5E/dtocean - -jobs: - release: - runs-on: ubuntu-latest - concurrency: - group: ${{ github.workflow }}-release-${{ github.ref_name }} - cancel-in-progress: false - permissions: - contents: write - outputs: - dtocean-economics-released: ${{ steps.release-dtocean-economics.outputs.released }} - dtocean-economics-commit_sha: ${{ steps.release-dtocean-economics.outputs.commit_sha }} - - steps: - - name: Wait for all test jobs - uses: lewagon/wait-on-check-action@v1.5.0 - with: - ref: ${{ github.sha }} - check-regexp: "(?i)^.*(test|audit).*$" - repo-token: ${{ secrets.GITHUB_TOKEN }} - fail-on-no-checks: false - - # Note: We checkout the repository at the branch that triggered the workflow. - # Python Semantic Release will automatically convert shallow clones to full clones - # if needed to ensure proper history evaluation. However, we forcefully reset the - # branch to the workflow sha because it is possible that the branch was updated - # while the workflow was running, which prevents accidentally releasing un-evaluated - # changes. - - name: Checkout repository on release branch - uses: actions/checkout@v6 - with: - ref: ${{ github.ref_name }} - fetch-depth: 0 - - - name: Force release branch to be at workflow sha - run: | - git reset --hard ${{ github.sha }} - - - name: Release dtocean-economics - id: release-dtocean-economics - uses: python-semantic-release/python-semantic-release@v10.5.3 - with: - commit: ${{ github.repository == env.RELEASING_REPO }} - directory: ${{ env.DTOCEAN_ECONOMICS_DIR }} - github_token: ${{ secrets.GITHUB_TOKEN }} - push: ${{ github.repository == env.RELEASING_REPO }} - vcs_release: false - - publish-dtocean-economics: - runs-on: ubuntu-latest - needs: release - if: needs.release.outputs.dtocean-economics-released == 'true' - permissions: - id-token: write - defaults: - run: - working-directory: ${{ env.DTOCEAN_ECONOMICS_DIR }} - environment: - name: testpypi - url: https://test.pypi.org/project/dtocean-economics/ - steps: - - name: Setup | Checkout repository on commit sha - uses: actions/checkout@v6 - with: - lfs: true - ref: ${{ needs.release.outputs.dtocean-economics-commit_sha }} - - - name: Set up Python - uses: actions/setup-python@v6 - with: - python-version: "3.13" - - - name: Install poetry - uses: abatilo/actions-poetry@v2 - - - name: Install poetry-monoranger-plugin - shell: bash - run: | - poetry self add git+https://github.com/H0R5E/poetry-monoranger-plugin.git#include_groups - - - name: Update Poetry configuration - run: poetry config virtualenvs.create false - - - name: Package project - run: poetry build - - - name: Publish package distributions to PyPI - if: ${{ github.repository == env.RELEASING_REPO }} - uses: pypa/gh-action-pypi-publish@release/v1 - with: - packages-dir: ${{ env.DTOCEAN_ECONOMICS_DIR }}/dist - verbose: true - repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f56cafec..f69dbebd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,14 +9,15 @@ permissions: contents: read env: - DTOCEAN_CORE_DIR: packages/dtocean-core - DTOCEAN_QT_DIR: packages/dtocean-qt + DTOCEAN_DIR: packages/dtocean DTOCEAN_APP_DIR: packages/dtocean-app - DTOCEAN_HYDRODYNAMICS_DIR: packages/dtocean-hydrodynamics + DTOCEAN_CORE_DIR: packages/dtocean-core DTOCEAN_DOCS_DIR: packages/dtocean-docs - DTOCEAN_DIR: packages/dtocean - POLITE_CONFIG_DIR: packages/polite-config + DTOCEAN_ECONOMICS_DIR: packages/dtocean-economics + DTOCEAN_HYDRODYNAMICS_DIR: packages/dtocean-hydrodynamics + DTOCEAN_QT_DIR: packages/dtocean-qt MDO_ENGINE_DIR: packages/mdo-engine + POLITE_CONFIG_DIR: packages/polite-config RELEASING_REPO: DTOcean/dtocean jobs: @@ -40,6 +41,8 @@ jobs: dtocean-app-commit_sha: ${{ steps.release-dtocean-app.outputs.commit_sha }} dtocean-hydrodynamics-released: ${{ steps.release-dtocean-hydrodynamics.outputs.released }} dtocean-hydrodynamics-commit_sha: ${{ steps.release-dtocean-hydrodynamics.outputs.commit_sha }} + dtocean-economics-released: ${{ steps.release-dtocean-economics.outputs.released }} + dtocean-economics-commit_sha: ${{ steps.release-dtocean-economics.outputs.commit_sha }} root-released: ${{ steps.release-root.outputs.released }} root-commit_sha: ${{ steps.release-root.outputs.commit_sha }} root-tag: ${{ steps.release-root.outputs.tag }} @@ -131,6 +134,16 @@ jobs: push: ${{ github.repository == env.RELEASING_REPO }} vcs_release: false + - name: Release dtocean-economics + id: release-dtocean-economics + uses: python-semantic-release/python-semantic-release@v10.5.3 + with: + commit: ${{ github.repository == env.RELEASING_REPO }} + directory: ${{ env.DTOCEAN_ECONOMICS_DIR }} + github_token: ${{ secrets.GITHUB_TOKEN }} + push: ${{ github.repository == env.RELEASING_REPO }} + vcs_release: false + - name: Release root id: release-root uses: ./.github/actions/semantic-release-calver @@ -587,6 +600,51 @@ jobs: packages-dir: ${{ env.DTOCEAN_HYDRODYNAMICS_DIR }}/dist verbose: true + publish-dtocean-economics: + runs-on: ubuntu-latest + needs: release + if: needs.release.outputs.dtocean-economics-released == 'true' + permissions: + id-token: write + defaults: + run: + working-directory: ${{ env.DTOCEAN_ECONOMICS_DIR }} + environment: + name: pypi + url: https://pypi.org/project/dtocean-economics/ + steps: + - name: Setup | Checkout repository on commit sha + uses: actions/checkout@v6 + with: + lfs: true + ref: ${{ needs.release.outputs.dtocean-economics-commit_sha }} + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.13" + + - name: Install poetry + uses: abatilo/actions-poetry@v2 + + - name: Install poetry-monoranger-plugin + shell: bash + run: | + poetry self add git+https://github.com/H0R5E/poetry-monoranger-plugin.git#include_groups + + - name: Update Poetry configuration + run: poetry config virtualenvs.create false + + - name: Package project + run: poetry build + + - name: Publish package distributions to PyPI + if: ${{ github.repository == env.RELEASING_REPO }} + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: ${{ env.DTOCEAN_ECONOMICS_DIR }}/dist + verbose: true + publish-docs: needs: release if: needs.release.outputs.root-released == 'true' diff --git a/packages/dtocean-economics/pyproject.toml b/packages/dtocean-economics/pyproject.toml index e6e07a14..191314db 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -89,7 +89,7 @@ tag_format = "dtocean-economics-v{version}" version_toml = ["pyproject.toml:tool.poetry.version"] [tool.semantic_release.branches.main] -match = "(main|dtocean_economics)" +match = "(main)" [tool.semantic_release.changelog] # Recommended patterns for conventional commits parser that is scope aware From 82a18cee2d60a842f3d68d7013c9eb727e2af898 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Fri, 17 Apr 2026 13:00:23 +0100 Subject: [PATCH 28/40] Update package level READMEs --- packages/dtocean-economics/CHANGELOG.md | 2 + packages/dtocean-economics/README.md | 217 ++++++++++++++++++ .../src/dtocean_economics/__init__.py | 4 - .../src/dtocean_plugins/themes/economics.py | 21 +- .../tests/dtocean_economics/test_functions.py | 6 - packages/dtocean-economics/tests/test_docs.py | 10 + 6 files changed, 237 insertions(+), 23 deletions(-) create mode 100644 packages/dtocean-economics/tests/test_docs.py diff --git a/packages/dtocean-economics/CHANGELOG.md b/packages/dtocean-economics/CHANGELOG.md index 6c852b59..87a5714a 100644 --- a/packages/dtocean-economics/CHANGELOG.md +++ b/packages/dtocean-economics/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). + + ## [2.0.0] - 2019-03-07 ### Added diff --git a/packages/dtocean-economics/README.md b/packages/dtocean-economics/README.md index e339b736..15f57d87 100644 --- a/packages/dtocean-economics/README.md +++ b/packages/dtocean-economics/README.md @@ -1 +1,218 @@ +[![dtocean-economics actions](https://github.com/DTOcean/dtocean/actions/workflows/test-dtocean-economics.yml/badge.svg?branch=main)](https://github.com/DTOcean/dtocean/actions/workflows/test-dtocean-economics.yml) +[![codecov](https://img.shields.io/codecov/c/gh/DTOcean/dtocean?token=Y3GR22fUJ8&flag=dtocean-economics)](https://app.codecov.io/gh/DTOcean/dtocean?flags%5B0%5D=dtocean-economics) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/dtocean-economics) + # dtocean-economics + +The DTOcean Economics Module provides functions to assess and compare the +economic performance of arrays designed by DTOcean. It generates metrics such +as the levelised cost of energy (LCOE). The module can accept multiple +operational expenditure and energy production records to generate statistical +analysis + +Part of the [DTOcean](https://github.com/DTOcean/dtocean) suite of tools. + +## Installation + +```sh +pip install dtocean-economics +``` + +## Usage + +An example of calculating the LCOE from a bill of materials, and two different +operational expenditure (OPEX) and energy histories. + +Create the bill of materials first (in Euro): + +```python +>>> import pandas as pd + +>>> bom_dict = {'phase': ["One", "One", "One", "Two", "Two", "Two"], +... 'unitary_cost': [0.0, 100000.0, 100000.0, 1, 1, 1], +... 'project_year': [0, 1, 2, 0, 1, 2], +... 'quantity': [1, 1, 1, 1, 10, 20]} +>>> bom_df = pd.DataFrame(bom_dict, columns=["phase", +... "project_year", +... "quantity", +... "unitary_cost"]) +>>> bom_df + phase project_year quantity unitary_cost +0 One 0 1 0.0 +1 One 1 1 100000.0 +2 One 2 1 100000.0 +3 Two 0 1 1.0 +4 Two 1 10 1.0 +5 Two 2 20 1.0 + +``` + +Now build two independent OPEX records (in Euro): + +```python +>>> opex_dict = {'project_year': [0, 1, 2, 3, 4, 5], +... 'cost 0': [0.0, 100000.0, 100000.0, 1, 1, 1], +... 'cost 1': [0.0, 100000.0, 0, 1, 1, 100000.0]} +>>> opex_df = pd.DataFrame(opex_dict, columns=["project_year", +... "cost 0", +... "cost 1"]) +>>> opex_df + project_year cost 0 cost 1 +0 0 0.0 0.0 +1 1 100000.0 100000.0 +2 2 100000.0 0.0 +3 3 1.0 1.0 +4 4 1.0 1.0 +5 5 1.0 100000.0 + +``` + +And the related energy production records (in Wh): + +```python +>>> energy_dict = {'project_year': [0, 1, 2, 3, 4, 5], +... 'energy 0': [0, 1e6, 2e6, 0, 10e6, 20e6], +... 'energy 1': [0, 1e6, 32e6, 0, 0, 20e6]} +>>> energy_df = pd.DataFrame(energy_dict, columns=["project_year", +... "energy 0", +... "energy 1"]) +>>> energy_df + project_year energy 0 energy 1 +0 0 0.0 0.0 +1 1 1000000.0 1000000.0 +2 2 2000000.0 32000000.0 +3 3 0.0 0.0 +4 4 10000000.0 0.0 +5 5 20000000.0 20000000.0 + +``` + +Process the inputs to calculate the discounted values: + +```python +>>> from dtocean_economics import add_costs_to_bom, get_discounted_values +>>> discount_rate = 1 / 5 +>>> add_costs_to_bom(bom_df, discount_rate) +>>> bom_df + phase project_year quantity unitary_cost costs discounted_costs +0 One 0 1 0.0 0.0 0.000000 +1 One 1 1 100000.0 100000.0 83333.333333 +2 One 2 1 100000.0 100000.0 69444.444444 +3 Two 0 1 1.0 1.0 1.000000 +4 Two 1 10 1.0 10.0 8.333333 +5 Two 2 20 1.0 20.0 13.888889 + +>>> discounted_opex = get_discounted_values(opex_df, discount_rate) +>>> discounted_opex +0 152779.240612 +1 123522.151492 +dtype: float64 + +>>> discounted_energy = get_discounted_values(energy_df, discount_rate) +>>> discounted_energy +0 1.508230e+07 +1 3.109311e+07 +dtype: float64 + +``` + +Now calculate the mean of the LCOE (in Euro/kWh): + +```python +>>> discounted_capex = bom_df['discounted_costs'].sum() +>>> discounted_costs = discounted_opex + discounted_capex +>>> lcoe = discounted_costs / discounted_energy * 1000 +>>> lcoe +0 20.260845 +1 8.886958 +dtype: float64 + +>>> float(lcoe.mean()) +14.573901960338254 + +``` + +## Development + +Development of dtocean-economics uses the [Poetry](https://python-poetry.org/) +dependency manager. Poetry must be installed and available on the command line. + +To install: + +```sh +poetry install +``` + +## Tests + +A test suite is provided with the source code that uses [pytest](https://docs.pytest.org). + +Install the testing dependencies: + +```sh +poetry install --with test +``` + +Additional tests are available for the plugins to [dtocean-core]. Enable these +tests by installing the `test-extras` group: + +```sh +poetry install --with test --with test-extras +``` + +Run the tests: + +```sh +poetry run pytest +``` + +Code quality can also be audited using the [ruff](https://docs.astral.sh/ruff/) +and [pyright](https://github.com/microsoft/pyright) tools. Install the +dependencies: + +```sh +poetry install --with audit +``` + +Run the audit: + +```sh +poetry run ruff +poetry run pyright src +``` + +The above tests can be run across all compatible Python versions using +[tox](https://tox.wiki/) and [tox-uv](https://github.com/tox-dev/tox-uv). To +install: + +```sh +poetry install --with test --with test-extras --with audit --with tox +``` + +To run the tests: + +```sh +poetry run tox +``` + +## Contributing + +Please see the [dtocean](https://github.com/DTOcean/dtocean) GitHub repository +for contributing guidelines. + +[dtocean-core]: https://pypi.org/project/dtocean-core/ + +## Credits + +This package was initially created as part of the [EU DTOcean project]( +https://cordis.europa.eu/project/id/608597) by: + ++ Mathew Topper at [TECNALIA](https://www.tecnalia.com) ++ Marta Silva at [WavEC](https://www.wavec.org/) + +It is now maintained by Mathew Topper at [Data Only Greater]( +https://www.dataonlygreater.com/). + +## License + +[GPL-3.0](https://choosealicense.com/licenses/gpl-3.0/) diff --git a/packages/dtocean-economics/src/dtocean_economics/__init__.py b/packages/dtocean-economics/src/dtocean_economics/__init__.py index af0d281a..65d41039 100644 --- a/packages/dtocean-economics/src/dtocean_economics/__init__.py +++ b/packages/dtocean-economics/src/dtocean_economics/__init__.py @@ -85,7 +85,3 @@ def get_present_values(value: np.ndarray, yr: np.ndarray, dr: float): It can be applied in an item by item basis, or on the sum by year """ return value / ((1 + dr) ** yr) - - -def get_total_cost(bom): - return (bom["unitary_cost"] * bom["quantity"]).sum() diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 7976e47f..ca68642d 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -37,7 +37,6 @@ add_costs_to_bom, get_discounted_values, get_phase_breakdown, - get_total_cost, ) from dtocean_economics.preprocessing import ( estimate_cost_per_power, @@ -554,7 +553,6 @@ def _get_outputs( capex_total = 0 discounted_capex_total = 0 phase_breakdown = None - discounted_capex = None discounted_opex = None lcoe_capex = None lcoe_opex = None @@ -564,21 +562,18 @@ def _get_outputs( add_costs_to_bom(capex_bom, discount_rate) costs_df = capex_bom[["project_year", "costs"]] - discounted_capex = get_discounted_values( - costs_df, - discount_rate, - ) - - discounted_capex_total = discounted_capex.iloc[0] - capex_total = get_total_cost(capex_bom) + capex_total = costs_df["costs"].sum() + discounted_capex_total = costs_df["discounted_costs"].sum() phase_breakdown = get_phase_breakdown(capex_bom) - assert phase_breakdown is not None - capex_breakdown = {k: v["costs"] for k, v in phase_breakdown.iterrows()} outputs["capex_total"] = capex_total - outputs["capex_breakdown"] = capex_breakdown outputs["discounted_capex"] = discounted_capex_total + if phase_breakdown is not None: + outputs["capex_breakdown"] = { + k: v["costs"] for k, v in phase_breakdown.iterrows() + } + if externalities_capex is not None: outputs["capex_no_externalities"] = ( capex_total - externalities_capex @@ -594,7 +589,7 @@ def _get_outputs( energy_total = energy_by_year.sum() discounted_energy = get_discounted_values(energy_record, discount_rate) - if discounted_capex is not None: + if discounted_capex_total > 0: lcoe_capex = discounted_capex_total / discounted_energy lcoe_total = lcoe_capex.copy() diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py index f14796a9..8cad8278 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -24,7 +24,6 @@ get_discounted_values, get_phase_breakdown, get_present_values, - get_total_cost, ) YEAR_ONE = 6 / 5 @@ -103,8 +102,3 @@ def test_get_present_values(): result = get_present_values(value, year, dr) assert np.isclose(result, expected).all() - - -def test_get_total_cost(bom): - expected = 101 + (YEAR_ONE * 110) + (YEAR_TWO * 120) - assert np.isclose(get_total_cost(bom), expected) diff --git a/packages/dtocean-economics/tests/test_docs.py b/packages/dtocean-economics/tests/test_docs.py new file mode 100644 index 00000000..a7114498 --- /dev/null +++ b/packages/dtocean-economics/tests/test_docs.py @@ -0,0 +1,10 @@ +import doctest +from pathlib import Path + +PACKAGE_DIR = Path(__file__).parents[1] + + +def test_README(): + readme_path = PACKAGE_DIR / "README.md" + doctest_results = doctest.testfile(str(readme_path)) + assert doctest_results.failed == 0 From 8c9960ab0ee911a77b51470c7a38082b2bc51627 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Fri, 17 Apr 2026 13:08:01 +0100 Subject: [PATCH 29/40] Fix silly bug --- .../src/dtocean_plugins/themes/economics.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index ca68642d..22e060ec 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -560,10 +560,8 @@ def _get_outputs( if not capex_bom.empty: add_costs_to_bom(capex_bom, discount_rate) - costs_df = capex_bom[["project_year", "costs"]] - - capex_total = costs_df["costs"].sum() - discounted_capex_total = costs_df["discounted_costs"].sum() + capex_total = capex_bom["costs"].sum() + discounted_capex_total = capex_bom["discounted_costs"].sum() phase_breakdown = get_phase_breakdown(capex_bom) outputs["capex_total"] = capex_total From 2930c13f8524e388998c7b95b52d40ab6081c480 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Sat, 18 Apr 2026 14:28:55 +0100 Subject: [PATCH 30/40] Update top level README and docs --- README.md | 14 +++++++------- docs/index.rst | 4 ++-- packages/dtocean-economics/README.md | 8 ++++---- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index b9daa713..0e7e1653 100644 --- a/README.md +++ b/README.md @@ -22,16 +22,16 @@ marine renewable energy arrays.** DTOcean can calculate: - Optimal ocean energy converter (OEC) positioning -- Energy export infrastructure -- Station keeping requirements based on OEC performance and site conditions -- Installation planning with weather effects -- Maintenance planning, simulating OEC downtime -- Environmental impact assessment (experimental) +- Energy export infrastructure +- Station keeping requirements based on OEC performance and site conditions +- Installation planning with weather effects +- Maintenance planning, simulating OEC downtime +- Environmental impact assessment (experimental) And features include: -- A unique statistical approach to calculating levelized cost of energy (LCOE) -- OEC reliability influenced at component level +- A unique statistical approach to calculating levelized cost of energy (LCOE) +- OEC reliability influenced at component level - Graphical user interface - Persistent database diff --git a/docs/index.rst b/docs/index.rst index 5751bd7a..4fdfe902 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -45,7 +45,7 @@ - Station keeping designed for device and site conditions [#f2]_ - Installation planning with weather effects [#f2]_ - Maintenance needs and OEC downtime [#f2]_ - - A unique statistical approach to LCOE [#f2]_ + - A unique statistical approach to LCOE - Influence reliability at component level [#f2]_ - Environmental impact assessment [#f1]_ [#f2]_ - Graphical user interface @@ -55,7 +55,7 @@ .. only:: html - Loved and maintained by `Mathew Topper `_ + Loved and maintained by `Mathew Topper `_ \@ `Data Only Greater `_ .. rubric:: Footnotes diff --git a/packages/dtocean-economics/README.md b/packages/dtocean-economics/README.md index 15f57d87..0c71390b 100644 --- a/packages/dtocean-economics/README.md +++ b/packages/dtocean-economics/README.md @@ -4,11 +4,11 @@ # dtocean-economics -The DTOcean Economics Module provides functions to assess and compare the -economic performance of arrays designed by DTOcean. It generates metrics such -as the levelised cost of energy (LCOE). The module can accept multiple +The DTOcean Economics Module provides functions to assess and compare the +economic performance of arrays designed by DTOcean. It generates metrics such +as the levelised cost of energy (LCOE). The module can accept multiple operational expenditure and energy production records to generate statistical -analysis +analysis. Part of the [DTOcean](https://github.com/DTOcean/dtocean) suite of tools. From 2199fee716d5e93d1e1bc3da47353c967f6ddd80 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Sat, 18 Apr 2026 14:50:49 +0100 Subject: [PATCH 31/40] Run prettier on README --- packages/dtocean-economics/.vscode/settings.json | 3 +++ packages/dtocean-economics/README.md | 10 ++++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/dtocean-economics/.vscode/settings.json b/packages/dtocean-economics/.vscode/settings.json index 8820374f..4be4f53f 100644 --- a/packages/dtocean-economics/.vscode/settings.json +++ b/packages/dtocean-economics/.vscode/settings.json @@ -1,4 +1,7 @@ { + "[markdown]": { + "editor.formatOnSave": true, + }, "[python]": { "editor.formatOnSave": true, "editor.codeActionsOnSave": { diff --git a/packages/dtocean-economics/README.md b/packages/dtocean-economics/README.md index 0c71390b..ac3f67d0 100644 --- a/packages/dtocean-economics/README.md +++ b/packages/dtocean-economics/README.md @@ -204,14 +204,12 @@ for contributing guidelines. ## Credits -This package was initially created as part of the [EU DTOcean project]( -https://cordis.europa.eu/project/id/608597) by: +This package was initially created as part of the [EU DTOcean project](https://cordis.europa.eu/project/id/608597) by: -+ Mathew Topper at [TECNALIA](https://www.tecnalia.com) -+ Marta Silva at [WavEC](https://www.wavec.org/) +- Mathew Topper at [TECNALIA](https://www.tecnalia.com) +- Marta Silva at [WavEC](https://www.wavec.org/) -It is now maintained by Mathew Topper at [Data Only Greater]( -https://www.dataonlygreater.com/). +It is now maintained by Mathew Topper at [Data Only Greater](https://www.dataonlygreater.com/). ## License From 339c87d0c8d3542d395886dd18fb41d97624669f Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Sat, 18 Apr 2026 17:32:35 +0100 Subject: [PATCH 32/40] Estimate opex_bom if externalities given --- .../src/dtocean_plugins/themes/economics.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 22e060ec..2efec4c9 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -453,10 +453,17 @@ def connect(self, debug_entry=False): ) # Add OPEX externalities - if not opex_bom.empty and self.data.externalities_opex is not None: - opex_bom = opex_bom.set_index("project_year") - opex_bom += self.data.externalities_opex - opex_bom = opex_bom.reset_index() + if self.data.externalities_opex is not None: + if opex_bom.empty: + opex_bom = estimate_opex( + self.data.lifetime, + 1, + self.data.externalities_opex, + ) + else: + opex_bom = opex_bom.set_index("project_year") + opex_bom += self.data.externalities_opex + opex_bom = opex_bom.reset_index() # Prepare energy if self.data.network_efficiency is not None: From c525674d72a752490b642e87a39cc93c754ae41a Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Sat, 18 Apr 2026 17:42:17 +0100 Subject: [PATCH 33/40] Test when only partial inputs are available Also set all opex in year 0 to 0. Euro in test setups. --- .../src/dtocean_plugins/themes/economics.py | 117 +++-- .../themes/test_themes_economics.py | 446 +++++++++++++++++- 2 files changed, 490 insertions(+), 73 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 2efec4c9..4e482d80 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -518,7 +518,7 @@ def _get_outputs( ) -> dict[str, Any]: series = [opex_bom, energy_record] series_lengths = [len(x) for x in series if not x.empty] - if len(set(series_lengths)) != 1: + if len(series_lengths) == 2 and len(set(series_lengths)) != 1: msg = "opex bom and energy record must be the same length if not empty" raise ValueError(msg) @@ -560,7 +560,10 @@ def _get_outputs( capex_total = 0 discounted_capex_total = 0 phase_breakdown = None + opex_total = None discounted_opex = None + energy_total = None + discounted_energy = None lcoe_capex = None lcoe_opex = None lcoe_total = None @@ -586,6 +589,11 @@ def _get_outputs( if not opex_bom.empty: opex_by_year = opex_bom.set_index("project_year") + opex_year_zero = opex_by_year.loc[0] + assert isinstance(opex_year_zero, pd.Series) + if opex_year_zero.sum() > 0.0: + raise ValueError("OPEX must be zero for year 0") + opex_total = opex_by_year.sum() discounted_opex = get_discounted_values(opex_bom, discount_rate) @@ -663,23 +671,30 @@ def _get_outputs( outputs["discounted_lifetime_cost_mode"] = lifetime_discounted_cost_mode - # Calculate values using most likely OPEX / Energy combination - if outputs["discounted_opex_mode"] is not None: - discounted_opex_base = outputs["discounted_opex_mode"] - else: - discounted_opex_base = outputs["discounted_opex_mean"] - - assert discounted_opex_base is not None + if not opex_bom.empty: + # Calculate values using most likely OPEX / Energy combination + if outputs["discounted_opex_mode"] is not None: + discounted_opex_base = outputs["discounted_opex_mode"] + else: + discounted_opex_base = outputs["discounted_opex_mean"] - if outputs["discounted_energy_mode"] is not None: - discounted_energy_base = outputs["discounted_energy_mode"] + # OPEX Breakdown if externalities + if externalities_opex is None: + discounted_maintenance = discounted_opex_base + else: + opex_breakdown = _get_opex_breakdown( + opex_bom, + externalities_opex, + discounted_opex_base, + discount_rate, + ) + outputs["opex_breakdown"] = opex_breakdown + discounted_maintenance = opex_breakdown["Maintenance"] + discounted_external = opex_breakdown["Externalities"] else: - discounted_energy_base = outputs["discounted_energy_mean"] + discounted_opex_base = 0.0 - assert discounted_energy_base is not None - discounted_energy_base = discounted_energy_base * 1e6 # MW to W - - # CAPEX vs OPEX Breakdown and OPEX Breakdown if externalities + # CAPEX vs OPEX Breakdown breakdown = { "Discounted CAPEX": discounted_capex_total, "Discounted OPEX": discounted_opex_base, @@ -687,20 +702,16 @@ def _get_outputs( outputs["cost_breakdown"] = breakdown - if externalities_opex is None: - discounted_maintenance = discounted_opex_base + if energy_record.empty: + return outputs + + if outputs["discounted_energy_mode"] is not None: + discounted_energy_base = outputs["discounted_energy_mode"] else: - opex_breakdown = _get_opex_breakdown( - opex_bom, - externalities_opex, - discounted_opex_base, - discount_rate, - ) - outputs["opex_breakdown"] = opex_breakdown - discounted_maintenance = opex_breakdown["Maintenance"] - discounted_external = opex_breakdown["Externalities"] + discounted_energy_base = outputs["discounted_energy_mean"] # LCOE Breakdowns in cent/kWh (i.e. Euro/Wh * 1e5) + discounted_energy_base = discounted_energy_base * 1e6 # MW to W factor = 1e5 if phase_breakdown is not None: @@ -709,26 +720,32 @@ def _get_outputs( for k, v in phase_breakdown.iterrows() } outputs["capex_lcoe_breakdown"] = capex_lcoe_breakdown - - lcoe_maintenance = round( - factor * discounted_maintenance / discounted_energy_base, 2 - ) - - if externalities_opex is None: - lcoe_external = 0 + total_capex = sum(capex_lcoe_breakdown.values()) else: - lcoe_external = round( - factor * discounted_external / discounted_energy_base, 2 + total_capex = 0.0 + + if not opex_bom.empty: + lcoe_maintenance = round( + factor * discounted_maintenance / discounted_energy_base, 2 ) - outputs["opex_lcoe_breakdown"] = { - "Maintenance": lcoe_maintenance, - "Externalities": lcoe_external, - } - total_capex = sum(capex_lcoe_breakdown.values()) - total_opex = lcoe_maintenance + lcoe_external + if externalities_opex is None: + lcoe_external = 0 + else: + lcoe_external = round( + factor * discounted_external / discounted_energy_base, 2 + ) + outputs["opex_lcoe_breakdown"] = { + "Maintenance": lcoe_maintenance, + "Externalities": lcoe_external, + } + + total_opex = lcoe_maintenance + lcoe_external + else: + total_opex = 0.0 - outputs["lcoe_breakdown"] = {"CAPEX": total_capex, "OPEX": total_opex} + if total_capex > 0.0 or total_opex > 0.0: + outputs["lcoe_breakdown"] = {"CAPEX": total_capex, "OPEX": total_opex} return outputs @@ -762,7 +779,7 @@ def _get_metrics_table( metrics_dict[col_name] = col_result.values * factor metrics = pd.DataFrame(metrics_dict) - if len(metrics) is None: + if len(metrics) == 0: return # Set columns with missing data @@ -773,12 +790,12 @@ def _get_metrics_table( def _get_outputs_stats( - metrics_table, - opex_total, - discounted_opex, - discounted_energy, - lcoe_total, - discounted_capex_total, + metrics_table: pd.DataFrame, + opex_total: Optional[pd.Series], + discounted_opex: Optional[pd.Series], + discounted_energy: Optional[pd.Series], + lcoe_total: Optional[pd.Series], + discounted_capex_total: float, ): outputs: dict[str, Any] = { "lifetime_opex_mean": None, @@ -951,7 +968,7 @@ def _get_opex_breakdown( discounted_opex_base, discount_rate, ): - years = range(len(opex_bom)) + years = range(1, len(opex_bom)) discounted_externals = [ externalities_opex / (1 + discount_rate) ** i for i in years diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index 1dae06ac..68b021af 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -282,6 +282,7 @@ def test_economics_interface_entry_estimate( _get_outputs: MagicMock = mocker.patch( "dtocean_plugins.themes.economics._get_outputs", autospec=True, + return_value={"lcoe_mean": 1}, ) theme_name = "Economics" @@ -416,7 +417,7 @@ def opex_costs_0_externalities(): opex_dict = { "project_year": [0, 1, 2, 3], "cost 0": [ - 1 + opex_externalities, + 0.0, YEAR_ONE + opex_externalities, YEAR_TWO + opex_externalities, YEAR_THREE + opex_externalities, @@ -518,11 +519,11 @@ def test_get_outputs_0_externalities( economics_metric = economics_metrics.iloc[0] opex_metric = economics_metric["OPEX"] - opex_metric_expected = 1 + YEAR_ONE + YEAR_TWO + YEAR_THREE + 4 * 216 + opex_metric_expected = YEAR_ONE + YEAR_TWO + YEAR_THREE + 3 * 216 assert np.isclose(opex_metric, opex_metric_expected) discounted_opex_metric = economics_metric["Discounted OPEX"] - discounted_opex_metric_expected = 4 + 216 + 180 + 150 + 125 + discounted_opex_metric_expected = 3 + 180 + 150 + 125 assert discounted_opex_metric == discounted_opex_metric_expected energy_metric = economics_metric["Energy"] @@ -563,15 +564,15 @@ def test_get_outputs_0_externalities( assert ( outputs["discounted_energy_mean"] == discounted_energy_metric_expected ) - assert outputs["lcoe_mean"] == lcoe_metric_expected + assert np.isclose(outputs["lcoe_mean"], lcoe_metric_expected) cost_breakdown = outputs["cost_breakdown"] assert cost_breakdown["Discounted CAPEX"] == discounted_capex_expected assert cost_breakdown["Discounted OPEX"] == discounted_opex_metric_expected opex_breakdown = outputs["opex_breakdown"] - assert opex_breakdown["Externalities"] == 216 + 180 + 150 + 125 - assert opex_breakdown["Maintenance"] == 4 + assert opex_breakdown["Externalities"] == 180 + 150 + 125 + assert opex_breakdown["Maintenance"] == 3 capex_lcoe_breakdown = outputs["capex_lcoe_breakdown"] @@ -601,13 +602,13 @@ def test_get_outputs_0_externalities( # TODO: fix this rounding error expected = round( - (216 + 180 + 150 + 125) / discounted_energy_metric_expected * 1e-1, + (180 + 150 + 125) / discounted_energy_metric_expected * 1e-1, 2, ) assert abs(opex_lcoe_breakdown["Externalities"] - expected) < 0.02 expected = round( - 4 / discounted_energy_metric_expected * 1e-1, + 3 / discounted_energy_metric_expected * 1e-1, 2, ) assert opex_lcoe_breakdown["Maintenance"] == expected @@ -620,60 +621,459 @@ def test_get_outputs_0_externalities( assert abs(lcoe_breakdown["OPEX"] - expected) < 0.02 +def test_get_outputs_0_no_capex( + opex_costs_0_externalities, + energy_record_0, +): + discount_rate = 1 / 5 + outputs = _get_outputs( + pd.DataFrame(), + opex_costs_0_externalities, + energy_record_0, + discount_rate, + None, + 216, + ) + none_outputs = [ + "capex_breakdown", + "capex_lcoe_breakdown", + "capex_no_externalities", + "capex_total", + "confidence_density", + "discounted_capex", + "discounted_energy_lower", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_lifetime_cost_mode", + "discounted_opex_lower", + "discounted_opex_mode", + "discounted_opex_upper", + "lcoe_mode", + "lcoe_lower", + "lcoe_upper", + "lcoe_pdf", + "lifetime_cost_mode", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + economics_metric = outputs["economics_metrics"] + + lcoe_capex_metric = economics_metric["LCOE CAPEX"] + assert np.isnan(lcoe_capex_metric).all() + + discounted_opex_expected = 3 + 180 + 150 + 125 + discounted_energy_metric_expected = 4 + lcoe_metric_expected = ( + discounted_opex_expected / discounted_energy_metric_expected / 1000 + ) + lcoe_metric = economics_metric["LCOE"] + assert np.isclose(lcoe_metric, lcoe_metric_expected) + + cost_breakdown = outputs["cost_breakdown"] + assert cost_breakdown["Discounted CAPEX"] == 0.0 + assert cost_breakdown["Discounted OPEX"] == discounted_opex_expected + + lcoe_breakdown = outputs["lcoe_breakdown"] + assert lcoe_breakdown["CAPEX"] == 0.0 + + # TODO: fix this rounding error + expected = round(lcoe_metric_expected * 100, 2) + assert abs(lcoe_breakdown["OPEX"] - expected) < 0.02 + + +def test_get_outputs_0_no_opex( + bom, + energy_record_0, +): + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + pd.DataFrame(), + energy_record_0, + discount_rate, + 1e6, + None, + ) + + none_outputs = [ + "confidence_density", + "discounted_energy_lower", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_lifetime_cost_mode", + "discounted_opex_lower", + "discounted_opex_mean", + "discounted_opex_mode", + "discounted_opex_upper", + "lcoe_mode", + "lcoe_lower", + "lcoe_upper", + "lcoe_pdf", + "lifetime_cost_mode", + "lifetime_opex_mean", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + "opex_breakdown", + "opex_lcoe_breakdown", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + economics_metric = outputs["economics_metrics"] + + opex_metric = economics_metric["OPEX"] + assert np.isnan(opex_metric).all() + + discounted_opex_metric = economics_metric["Discounted OPEX"] + assert np.isnan(discounted_opex_metric).all() + + lcoe_opex_metric = economics_metric["LCOE OPEX"] + assert np.isnan(lcoe_opex_metric).all() + + discounted_capex_expected = 10 * 1e6 + 5e6 + 1e6 + 2 * (1e5 + 1e4) + discounted_energy_metric_expected = 4 + lcoe_metric_expected = ( + discounted_capex_expected / discounted_energy_metric_expected / 1000 + ) + lcoe_metric = economics_metric["LCOE"] + assert np.isclose(lcoe_metric, lcoe_metric_expected) + + cost_breakdown = outputs["cost_breakdown"] + assert cost_breakdown["Discounted CAPEX"] == discounted_capex_expected + assert cost_breakdown["Discounted OPEX"] == 0.0 + + lcoe_breakdown = outputs["lcoe_breakdown"] + assert np.isclose(lcoe_breakdown["CAPEX"], lcoe_metric * 100) + assert lcoe_breakdown["OPEX"] == 0.0 + + +def test_get_outputs_0_no_energy( + bom, + opex_costs_0_externalities, +): + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + opex_costs_0_externalities, + pd.DataFrame(), + discount_rate, + 1e6, + 216, + ) + + none_outputs = [ + "confidence_density", + "discounted_energy_lower", + "discounted_energy_mean", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_lifetime_cost_mode", + "discounted_opex_lower", + "discounted_opex_mode", + "discounted_opex_upper", + "lcoe_mode", + "lcoe_mean", + "lcoe_lower", + "lcoe_upper", + "lcoe_pdf", + "lifetime_cost_mode", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + "capex_lcoe_breakdown", + "opex_lcoe_breakdown", + "lcoe_breakdown", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + economics_metric = outputs["economics_metrics"] + + energy_metric = economics_metric["Energy"] + assert np.isnan(energy_metric).all() + + discounted_energy_metric = economics_metric["Discounted Energy"] + assert np.isnan(discounted_energy_metric).all() + + lcoe_capex_metric = economics_metric["LCOE CAPEX"] + assert np.isnan(lcoe_capex_metric).all() + + lcoe_opex_metric = economics_metric["LCOE OPEX"] + assert np.isnan(lcoe_opex_metric).all() + + lcoe_metric = economics_metric["LCOE"] + assert np.isnan(lcoe_metric).all() + + +def test_get_outputs_0_capex_only(bom): + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + pd.DataFrame(), + pd.DataFrame(), + discount_rate, + 1e6, + None, + ) + + none_outputs = [ + "cost_breakdown", + "confidence_density", + "discounted_energy_lower", + "discounted_energy_mean", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_lifetime_cost_mode", + "discounted_lifetime_cost_mean", + "discounted_opex_lower", + "discounted_opex_mean", + "discounted_opex_mode", + "discounted_opex_upper", + "economics_metrics", + "lcoe_mode", + "lcoe_mean", + "lcoe_lower", + "lcoe_upper", + "lcoe_pdf", + "lifetime_cost_mode", + "lifetime_cost_mean", + "lifetime_opex_mean", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + "opex_breakdown", + "capex_lcoe_breakdown", + "opex_lcoe_breakdown", + "lcoe_breakdown", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + +def test_get_outputs_0_opex_only(opex_costs_0_externalities): + discount_rate = 1 / 5 + outputs = _get_outputs( + pd.DataFrame(), + opex_costs_0_externalities, + pd.DataFrame(), + discount_rate, + None, + 216, + ) + + none_outputs = [ + "capex_breakdown", + "capex_no_externalities", + "capex_total", + "confidence_density", + "discounted_capex", + "discounted_energy_lower", + "discounted_energy_mean", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_lifetime_cost_mode", + "discounted_opex_lower", + "discounted_opex_mode", + "discounted_opex_upper", + "lcoe_mode", + "lcoe_mean", + "lcoe_lower", + "lcoe_upper", + "lcoe_pdf", + "lifetime_cost_mode", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + "capex_lcoe_breakdown", + "opex_lcoe_breakdown", + "lcoe_breakdown", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + +def test_get_outputs_0_energy_only(energy_record_0): + discount_rate = 1 / 5 + outputs = _get_outputs( + pd.DataFrame(), + pd.DataFrame(), + energy_record_0, + discount_rate, + None, + None, + ) + + none_outputs = [ + "capex_breakdown", + "capex_no_externalities", + "capex_total", + "confidence_density", + "discounted_capex", + "discounted_energy_lower", + "discounted_energy_mode", + "discounted_energy_upper", + "discounted_lifetime_cost_mode", + "discounted_lifetime_cost_mean", + "discounted_opex_lower", + "discounted_opex_mean", + "discounted_opex_mode", + "discounted_opex_upper", + "lcoe_mode", + "lcoe_mean", + "lcoe_lower", + "lcoe_upper", + "lcoe_pdf", + "lifetime_cost_mean", + "lifetime_cost_mode", + "lifetime_opex_mean", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + "opex_breakdown", + "capex_lcoe_breakdown", + "opex_lcoe_breakdown", + "lcoe_breakdown", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + +@pytest.fixture() +def opex_costs_0_non_zero_year_0(): + opex_dict = { + "project_year": [0, 1, 2, 3], + "cost 0": [ + 1.0, + YEAR_ONE, + YEAR_TWO, + YEAR_THREE, + ], + } + opex_df = pd.DataFrame(opex_dict) + return opex_df + + +def test_get_outputs_0_opex_non_zero_year_0(opex_costs_0_non_zero_year_0): + discount_rate = 1 / 5 + with pytest.raises(ValueError) as exc: + _get_outputs( + pd.DataFrame(), + opex_costs_0_non_zero_year_0, + pd.DataFrame(), + discount_rate, + None, + None, + ) + assert "OPEX must be zero for year 0" in str(exc) + + @pytest.fixture() def opex_costs_8(): opex_dict = { "project_year": [0, 1, 2, 3], "cost 0": [ - 0.5 * 1 * 1e5, + 0.0, 0.5 * YEAR_ONE * 1e5, 0.5 * YEAR_TWO * 1e5, 0.5 * YEAR_THREE * 1e5, ], "cost 1": [ - 1 * 1 * 1e5, + 0.0, 1 * YEAR_ONE * 1e5, 1 * YEAR_TWO * 1e5, 1 * YEAR_THREE * 1e5, ], "cost 2": [ - 1.5 * 1 * 1e5, + 0.0, 1.5 * YEAR_ONE * 1e5, 1.5 * YEAR_TWO * 1e5, 1.5 * YEAR_THREE * 1e5, ], "cost 3": [ - 0.5 * 1 * 1e5, + 0.0, 0.5 * YEAR_ONE * 1e5, 0.5 * YEAR_TWO * 1e5, 0.5 * YEAR_THREE * 1e5, ], "cost 4": [ - 1.5 * 1 * 1e5, + 0.0, 1.5 * YEAR_ONE * 1e5, 1.5 * YEAR_TWO * 1e5, 1.5 * YEAR_THREE * 1e5, ], "cost 5": [ - 0.75 * 1 * 1e5, + 0.0, 0.75 * YEAR_ONE * 1e5, 0.75 * YEAR_TWO * 1e5, 0.75 * YEAR_THREE * 1e5, ], "cost 6": [ - 1 * 1 * 1e5, + 0.0, 1 * YEAR_ONE * 1e5, 1 * YEAR_TWO * 1e5, 1 * YEAR_THREE * 1e5, ], "cost 7": [ - 1.25 * 1 * 1e5, + 0.0, 1.25 * YEAR_ONE * 1e5, 1.25 * YEAR_TWO * 1e5, 1.25 * YEAR_THREE * 1e5, ], "cost 8": [ - 1 * 1 * 1e5, + 0.0, 1 * YEAR_ONE * 1e5, 1 * YEAR_TWO * 1e5, 1 * YEAR_THREE * 1e5, @@ -777,7 +1177,7 @@ def test_get_outputs_8( print(key) assert outputs[key] is not None - lifetime_opex_expected = 1e5 * (1 + YEAR_ONE + YEAR_TWO + YEAR_THREE) + lifetime_opex_expected = 1e5 * (YEAR_ONE + YEAR_TWO + YEAR_THREE) assert np.isclose(outputs["lifetime_opex_mean"], lifetime_opex_expected) lifetime_opex_mode_error = ( @@ -791,7 +1191,7 @@ def test_get_outputs_8( assert outputs["lifetime_opex_lower"] < lifetime_opex_expected assert outputs["lifetime_opex_upper"] > lifetime_opex_expected - discounted_opex_expected = 4 * 1e5 + discounted_opex_expected = 3 * 1e5 assert np.isclose(outputs["discounted_opex_mean"], discounted_opex_expected) assert np.isclose(outputs["discounted_opex_mode"], discounted_opex_expected) assert outputs["discounted_opex_lower"] < discounted_opex_expected @@ -892,7 +1292,7 @@ def test_get_outputs_8_BiVariateKDE_error( print(key) assert outputs[key] is not None - lifetime_opex_expected = 1e5 * (1 + YEAR_ONE + YEAR_TWO + YEAR_THREE) + lifetime_opex_expected = 1e5 * (YEAR_ONE + YEAR_TWO + YEAR_THREE) assert np.isclose(outputs["lifetime_opex_mean"], lifetime_opex_expected) lifetime_opex_mode_error = ( @@ -906,7 +1306,7 @@ def test_get_outputs_8_BiVariateKDE_error( assert outputs["lifetime_opex_lower"] < lifetime_opex_expected assert outputs["lifetime_opex_upper"] > lifetime_opex_expected - discounted_opex_expected = 4 * 1e5 + discounted_opex_expected = 3 * 1e5 assert np.isclose(outputs["discounted_opex_mean"], discounted_opex_expected) assert np.isclose( outputs["discounted_opex_mode"], @@ -1029,10 +1429,10 @@ def test_get_outputs_8_UniVariateKDE_error( print(key) assert outputs[key] is not None - lifetime_opex_expected = 1e5 * (1 + YEAR_ONE + YEAR_TWO + YEAR_THREE) + lifetime_opex_expected = 1e5 * (YEAR_ONE + YEAR_TWO + YEAR_THREE) assert np.isclose(outputs["lifetime_opex_mean"], lifetime_opex_expected) - discounted_opex_expected = 4 * 1e5 + discounted_opex_expected = 3 * 1e5 assert np.isclose(outputs["discounted_opex_mean"], discounted_opex_expected) discounted_energy_expected = 4.0 From 6d0ea9f215155bcac009b622e9b55e9399c12574 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 20 Apr 2026 13:40:27 +0100 Subject: [PATCH 34/40] Reduce LFS downloads for tests --- .github/workflows/test-dtocean-economics.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-dtocean-economics.yml b/.github/workflows/test-dtocean-economics.yml index 8fad9f6b..6ba2b349 100644 --- a/.github/workflows/test-dtocean-economics.yml +++ b/.github/workflows/test-dtocean-economics.yml @@ -34,7 +34,6 @@ jobs: steps: - uses: actions/checkout@v6 with: - lfs: true persist-credentials: false - name: Install package uses: ./.github/actions/poetry-install @@ -58,8 +57,9 @@ jobs: steps: - uses: actions/checkout@v6 with: - lfs: true persist-credentials: false + - name: Git LFS Pull + run: git lfs pull -I packages/dtocean-economics - name: Install package uses: ./.github/actions/poetry-install with: From 6db54361d24987401b3dda553a026f2e6e30cc36 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 20 Apr 2026 13:41:10 +0100 Subject: [PATCH 35/40] Also remove LFS for audit test --- .github/workflows/test-dtocean-economics.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/test-dtocean-economics.yml b/.github/workflows/test-dtocean-economics.yml index 6ba2b349..240b67a2 100644 --- a/.github/workflows/test-dtocean-economics.yml +++ b/.github/workflows/test-dtocean-economics.yml @@ -81,7 +81,6 @@ jobs: steps: - uses: actions/checkout@v6 with: - lfs: true persist-credentials: false - name: Install package uses: ./.github/actions/poetry-install From 3a58120d948dd48ddcdda7900bee23e493c59606 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 20 Apr 2026 13:56:24 +0100 Subject: [PATCH 36/40] Use relative path for doctest.testfile --- packages/dtocean-economics/tests/test_docs.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/dtocean-economics/tests/test_docs.py b/packages/dtocean-economics/tests/test_docs.py index a7114498..7aa270c4 100644 --- a/packages/dtocean-economics/tests/test_docs.py +++ b/packages/dtocean-economics/tests/test_docs.py @@ -1,10 +1,11 @@ import doctest from pathlib import Path -PACKAGE_DIR = Path(__file__).parents[1] +THIS_DIR = Path(__file__).parent def test_README(): - readme_path = PACKAGE_DIR / "README.md" - doctest_results = doctest.testfile(str(readme_path)) + readme_path = THIS_DIR.parent / "README.md" + relative_readme_path = readme_path.relative_to(THIS_DIR, walk_up=True) + doctest_results = doctest.testfile(str(relative_readme_path)) assert doctest_results.failed == 0 From 3d1deb6c37dc017cb419f5a1fb48bb0dd386fa8a Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Mon, 20 Apr 2026 15:18:18 +0100 Subject: [PATCH 37/40] Test estimated opex with just externalities --- .../src/dtocean_plugins/themes/economics.py | 2 +- .../themes/test_themes_economics.py | 81 +++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 4e482d80..7fda904a 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -454,7 +454,7 @@ def connect(self, debug_entry=False): # Add OPEX externalities if self.data.externalities_opex is not None: - if opex_bom.empty: + if opex_bom.empty and self.data.lifetime is not None: opex_bom = estimate_opex( self.data.lifetime, 1, diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index 68b021af..f4979c0f 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -374,6 +374,87 @@ def test_economics_interface_entry_estimate( assert energy_record_energy == 10000 * 1e6 +def test_economics_interface_entry_estimate_externalities_opex( + mocker, + inputs_economics_estimate, + theme_menu, + core, + tidal_project, + var_tree, +): + _get_outputs: MagicMock = mocker.patch( + "dtocean_plugins.themes.economics._get_outputs", + autospec=True, + return_value={"lcoe_mean": 1}, + ) + + theme_name = "Economics" + + project_menu = ProjectMenu() + project = deepcopy(tidal_project) + theme_menu.activate(core, project, theme_name) + project_menu.initiate_dataflow(core, project) + + economics_branch = var_tree.get_branch(core, project, theme_name) + economics_branch.read_test_data(core, project, inputs_economics_estimate) + economics_branch.read_auto(core, project) + + opex_estimate = economics_branch.get_input_variable( + core, + project, + "project.opex_estimate", + ) + assert opex_estimate is not None + + opex_estimate.set_raw_interface(core, None) + opex_estimate.read(core, project) + + assert not opex_estimate.has_value(core, project) + + annual_repair_cost_estimate = economics_branch.get_input_variable( + core, + project, + "project.annual_repair_cost_estimate", + ) + assert annual_repair_cost_estimate is not None + + annual_repair_cost_estimate.set_raw_interface(core, None) + annual_repair_cost_estimate.read(core, project) + + assert not annual_repair_cost_estimate.has_value(core, project) + + externalities_opex = economics_branch.get_input_variable( + core, project, "project.externalities_opex" + ) + assert externalities_opex is not None + + expected_opex_costs = 1e3 + externalities_opex.set_raw_interface(core, expected_opex_costs) + externalities_opex.read(core, project) + + can_execute = theme_menu.is_executable(core, project, theme_name) + + if not can_execute: + inputs = economics_branch.get_input_status(core, project) + pprint(inputs) + assert can_execute + + connector = _get_connector(project, "themes") + interface = connector.get_interface(core, project, theme_name) + + interface.connect() + + _get_outputs.assert_called_once() + _get_outputs_args = _get_outputs.call_args[0] + opex_bom = _get_outputs_args[1] + + opex_bom_not_zero = opex_bom[opex_bom["project_year"] != 0] + unique_opex_costs = opex_bom_not_zero["costs"].unique() + + assert len(unique_opex_costs) == 1 + assert unique_opex_costs[0] == expected_opex_costs + + # These factors become 1 when used with a 1 / 5 discount rate in the respective # year YEAR_ONE = 6 / 5 From a952c0aba9fb0d9339f2b9ccbad01623cb1228f1 Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Tue, 21 Apr 2026 12:28:51 +0100 Subject: [PATCH 38/40] Add final tests --- .../src/dtocean_economics/__init__.py | 4 +- .../src/dtocean_economics/preprocessing.py | 11 +-- .../src/dtocean_plugins/themes/economics.py | 40 ++++---- .../tests/dtocean_economics/test_functions.py | 7 ++ .../themes/test_themes_economics.py | 99 +++++++++++++++++++ 5 files changed, 132 insertions(+), 29 deletions(-) diff --git a/packages/dtocean-economics/src/dtocean_economics/__init__.py b/packages/dtocean-economics/src/dtocean_economics/__init__.py index 65d41039..a7aeca19 100644 --- a/packages/dtocean-economics/src/dtocean_economics/__init__.py +++ b/packages/dtocean-economics/src/dtocean_economics/__init__.py @@ -70,8 +70,8 @@ def get_phase_breakdown(bom: pd.DataFrame): phase_groups = bom.groupby("phase") phase_breakdown = phase_groups.sum() - if "unitary_costs" in phase_breakdown: - phase_breakdown.drop("unitary_costs", axis=1, inplace=True) + if "unitary_cost" in phase_breakdown: + phase_breakdown.drop("unitary_cost", axis=1, inplace=True) return phase_breakdown diff --git a/packages/dtocean-economics/src/dtocean_economics/preprocessing.py b/packages/dtocean-economics/src/dtocean_economics/preprocessing.py index 1b42fecd..c279153e 100644 --- a/packages/dtocean-economics/src/dtocean_economics/preprocessing.py +++ b/packages/dtocean-economics/src/dtocean_economics/preprocessing.py @@ -27,21 +27,14 @@ def estimate_cost_per_power(total_rated_power, unit_cost, phase=None): cost = total_rated_power * unit_cost cost_bom = make_phase_bom([1], [cost], [0], phase) - return cost_bom -def estimate_energy(lifetime, year_energy, network_efficiency=None): - if network_efficiency is not None: - net_coeff = network_efficiency - else: - net_coeff = 1.0 - - energy = [0] + [year_energy * net_coeff] * lifetime +def estimate_energy(lifetime, year_energy, network_efficiency=1.0): + energy = [0] + [year_energy * network_efficiency] * lifetime energy_year = range(lifetime + 1) raw_energy = {"energy": energy, "project_year": energy_year} - energy_record = pd.DataFrame(raw_energy) return energy_record diff --git a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py index 7fda904a..8fb645d5 100644 --- a/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -517,7 +517,7 @@ def _get_outputs( externalities_opex: Optional[float], ) -> dict[str, Any]: series = [opex_bom, energy_record] - series_lengths = [len(x) for x in series if not x.empty] + series_lengths = [len(x.columns) for x in series if not x.empty] if len(series_lengths) == 2 and len(set(series_lengths)) != 1: msg = "opex bom and energy record must be the same length if not empty" raise ValueError(msg) @@ -900,23 +900,7 @@ def _get_outputs_stats( except np.linalg.LinAlgError: _get_discounted_opex_stats(outputs, discounted_opex) _get_discounted_energy_stats(outputs, discounted_energy) - - assert lcoe_total is not None - - # Euro/Wh to Euro/kWh - try: - distribution = UniVariateKDE(lcoe_total) - outputs["lcoe_mean"] = distribution.mean() * 1000 - outputs["lcoe_mode"] = distribution.mode() * 1000 - - intervals = distribution.confidence_interval(95) - - if intervals is not None: - outputs["lcoe_lower"] = intervals[0] * 1000 - outputs["lcoe_upper"] = intervals[1] * 1000 - - except np.linalg.LinAlgError: - outputs["lcoe_mean"] = lcoe_total.mean() * 1000 + _get_lcoe_stats(outputs, lcoe_total) return outputs @@ -926,6 +910,9 @@ def _get_outputs_stats( if discounted_energy is not None: _get_discounted_energy_stats(outputs, discounted_energy) + if lcoe_total is not None: + _get_lcoe_stats(outputs, lcoe_total) + return outputs @@ -962,6 +949,23 @@ def _get_discounted_energy_stats(outputs: dict[str, Any], discounted_energy): outputs["discounted_energy_mean"] = discounted_energy.mean() / 1e6 +def _get_lcoe_stats(outputs: dict[str, Any], lcoe_total): + # Euro/Wh to Euro/kWh + try: + distribution = UniVariateKDE(lcoe_total) + outputs["lcoe_mean"] = distribution.mean() * 1000 + outputs["lcoe_mode"] = distribution.mode() * 1000 + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + outputs["lcoe_lower"] = intervals[0] * 1000 + outputs["lcoe_upper"] = intervals[1] * 1000 + + except np.linalg.LinAlgError: + outputs["lcoe_mean"] = lcoe_total.mean() * 1000 + + def _get_opex_breakdown( opex_bom, externalities_opex, diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py index 8cad8278..98e5da96 100644 --- a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -85,6 +85,8 @@ def test_get_phase_breakdown(bom): assert isinstance(other, pd.Series) assert other["costs"] == 364 + assert "unitary_cost" not in result + def test_get_phase_breakdown_none(bom): none_bom = bom[pd.isnull(bom["phase"])] @@ -93,6 +95,11 @@ def test_get_phase_breakdown_none(bom): assert result is None +def test_get_phase_breakdown_no_costs(): + result = get_phase_breakdown(pd.DataFrame()) + assert result is None + + def test_get_present_values(): value = np.array([1, 6 / 5, 36 / 25, 216 / 125]) year = np.array([0, 1, 2, 3]) diff --git a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py index f4979c0f..423dc3b7 100644 --- a/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -1533,3 +1533,102 @@ def test_get_outputs_8_UniVariateKDE_error( abs(outputs["lcoe_mean"] - lcoe_expected) / lcoe_expected * 100 ) assert lcoe_mean_error < 20 + + +def test_get_outputs_8_no_opex( + bom, + energy_record_8, +): + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + pd.DataFrame(), + energy_record_8, + discount_rate, + 1e6, + None, + ) + + none_outputs = [ + "discounted_opex_lower", + "discounted_opex_mean", + "discounted_opex_mode", + "discounted_opex_upper", + "lifetime_cost_mode", + "discounted_lifetime_cost_mode", + "lifetime_opex_mean", + "lifetime_opex_mode", + "lifetime_opex_lower", + "lifetime_opex_upper", + "confidence_density", + "lcoe_pdf", + "opex_breakdown", + "opex_lcoe_breakdown", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + +def test_get_outputs_8_no_energy( + bom, + opex_costs_8, +): + discount_rate = 1 / 5 + outputs = _get_outputs( + bom, + opex_costs_8, + pd.DataFrame(), + discount_rate, + 1e6, + None, + ) + + none_outputs = [ + "opex_breakdown", + "discounted_energy_lower", + "discounted_energy_mean", + "discounted_energy_mode", + "discounted_energy_upper", + "lcoe_mean", + "lcoe_mode", + "lcoe_lower", + "lcoe_upper", + "confidence_density", + "lcoe_pdf", + "lcoe_breakdown", + "opex_lcoe_breakdown", + "capex_lcoe_breakdown", + ] + for key in none_outputs: + if outputs[key] is not None: + print(key) + assert outputs[key] is None + + non_none_outputs = set(outputs.keys()) - set(none_outputs) + for key in non_none_outputs: + if outputs[key] is None: + print(key) + assert outputs[key] is not None + + +def test_get_outputs_non_matching(bom, opex_costs_8, energy_record_0): + with pytest.raises(ValueError) as exc: + discount_rate = 1 / 5 + _get_outputs( + bom, + opex_costs_8, + energy_record_0, + discount_rate, + 1e6, + None, + ) + + assert "must be the same length" in str(exc) From 8ebd20edcb19a964d7051dee53dd2b5df082f1cf Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Tue, 21 Apr 2026 14:19:09 +0100 Subject: [PATCH 39/40] Undo dtocean-core pyproject change --- packages/dtocean-core/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/dtocean-core/pyproject.toml b/packages/dtocean-core/pyproject.toml index a9f2976b..fd2f4763 100644 --- a/packages/dtocean-core/pyproject.toml +++ b/packages/dtocean-core/pyproject.toml @@ -52,6 +52,7 @@ python-dateutil = "^2.9.0.post0" pyyaml = "^6.0.2" ruamel-yaml-clib = "^0.2.12" ruamel-yaml = "^0.19.1" +scipy = "^1.17.0" shapely = "^2.0.6" utm = "^0.8.1" xarray = "~2026.2.0" @@ -60,7 +61,6 @@ pywin32 = { version = ">=308", platform = "win32" } cmocean = "^4.0.3" packaging = ">=24.0" cartopy = "^0.25.0" -scipy = "^1.17.0" [tool.poetry.group.test] optional = true From f269b4fe67427198c014b2dec932c18fd449daed Mon Sep 17 00:00:00 2001 From: Mathew Topper Date: Tue, 21 Apr 2026 15:14:32 +0100 Subject: [PATCH 40/40] Update lock file --- poetry.lock | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/poetry.lock b/poetry.lock index 20a960ae..7787a51a 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 2.3.4 and should not be changed by hand. +# This file is automatically @generated by Poetry 2.3.2 and should not be changed by hand. [[package]] name = "alabaster" @@ -752,6 +752,7 @@ develop = true [package.dependencies] dtocean-app = {path = "../dtocean-app", develop = true} dtocean-docs = {path = "../dtocean-docs", develop = true} +dtocean-economics = {path = "../dtocean-economics", develop = true} dtocean-hydrodynamics = {path = "../dtocean-hydrodynamics", develop = true} [package.source] @@ -870,13 +871,14 @@ url = "packages/dtocean-dummy-module" [[package]] name = "dtocean-economics" -version = "2.0.0" +version = "2.0.2" description = "Economic assessment module for the DTOcean tools" optional = false python-versions = ">=3.12,<3.15" -groups = ["dtocean-economics"] +groups = ["dtocean", "dtocean-economics"] files = [] develop = true +markers = {dtocean = "python_version < \"3.14\""} [package.dependencies] contourpy = "^1.3.1"