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/.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/.github/workflows/test-dtocean-economics.yml b/.github/workflows/test-dtocean-economics.yml new file mode 100644 index 00000000..240b67a2 --- /dev/null +++ b/.github/workflows/test-dtocean-economics.yml @@ -0,0 +1,95 @@ +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: + 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: + persist-credentials: false + - name: Git LFS Pull + run: git lfs pull -I packages/dtocean-economics + - 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: + 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 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/.vscode/settings.json b/packages/dtocean-economics/.vscode/settings.json new file mode 100644 index 00000000..4be4f53f --- /dev/null +++ b/packages/dtocean-economics/.vscode/settings.json @@ -0,0 +1,17 @@ +{ + "[markdown]": { + "editor.formatOnSave": true, + }, + "[python]": { + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll": "explicit", + "source.organizeImports": "explicit" + }, + "editor.defaultFormatter": "charliermarsh.ruff" + }, + "[toml]": { + "editor.formatOnSave": true, + }, + "ruff.configuration": "pyproject.toml", +} diff --git a/packages/dtocean-economics/CHANGELOG.md b/packages/dtocean-economics/CHANGELOG.md new file mode 100644 index 00000000..87a5714a --- /dev/null +++ b/packages/dtocean-economics/CHANGELOG.md @@ -0,0 +1,31 @@ +# 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/README.md b/packages/dtocean-economics/README.md index e339b736..ac3f67d0 100644 --- a/packages/dtocean-economics/README.md +++ b/packages/dtocean-economics/README.md @@ -1 +1,216 @@ +[![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/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..191314db 100644 --- a/packages/dtocean-economics/pyproject.toml +++ b/packages/dtocean-economics/pyproject.toml @@ -1,12 +1,166 @@ [tool.poetry] name = "dtocean-economics" -version = "2.0.0" +version = "2.0.2" 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", +] +packages = [ + { include = "dtocean_economics", from = "src" }, + { include = "dtocean_plugins", from = "src" }, +] + +[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] +contourpy = "^1.3.1" +pandas = "^3.0.1" +scipy = "^1.17.0" + +[tool.poetry.group.test] +optional = true + +[tool.poetry.group.test.dependencies] +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 + +[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.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"] + +[tool.tox.env_run_base] +description = "Run test under {base_python}" +skip_install = true +allowlist_externals = ["poetry"] +commands_pre = [ + [ + "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-core", + "--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..a7aeca19 --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/__init__.py @@ -0,0 +1,87 @@ +# -*- 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 . + + +import numpy as np +import pandas as pd + + +def add_costs_to_bom(bom, discount_rate=None): + costs = bom["quantity"] * bom["unitary_cost"] + bom["costs"] = costs + + if discount_rate is None: + return + + 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.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: 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 + + # Replace any null phase values + bom.loc[pd.isnull(bom["phase"]), "phase"] = "Other" + phase_groups = bom.groupby("phase") + + phase_breakdown = phase_groups.sum() + if "unitary_cost" in phase_breakdown: + phase_breakdown.drop("unitary_cost", axis=1, inplace=True) + + return phase_breakdown + + +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 + 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) 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..c279153e --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/preprocessing.py @@ -0,0 +1,96 @@ +# -*- 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=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 + + +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/src/dtocean_economics/stats.py b/packages/dtocean-economics/src/dtocean_economics/stats.py new file mode 100644 index 00000000..3955e7f4 --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_economics/stats.py @@ -0,0 +1,284 @@ +# -*- 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, xtol=2e-32): + """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), + xtol=xtol, + ) + 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/plots/plots_lcoe.py b/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py new file mode 100644 index 00000000..bea42fff --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_plugins/plots/plots_lcoe.py @@ -0,0 +1,147 @@ +# 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 Analysis" + + @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 / 1e6 + ) # Wh to MWh + zz = self.data.lcoe_pdf.data + + 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"] + + 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 [MWh]") + + plt.title("LCOE PDF Analysis") + plt.tight_layout() + + self.fig_handle = plt.gcf() 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..8fb645d5 --- /dev/null +++ b/packages/dtocean-economics/src/dtocean_plugins/themes/economics.py @@ -0,0 +1,986 @@ +# -*- 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 +""" + +from typing import Any, Optional + +import numpy as np +import pandas as pd + +from dtocean_economics import ( + add_costs_to_bom, + get_discounted_values, + get_phase_breakdown, +) +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", + "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.lifetime_opex_interval_lower", + "project.lifetime_opex_interval_upper", + "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", + "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", + "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": "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, + ) + capex_bom = capex_bom.convert_dtypes() + + 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 self.data.externalities_opex is not None: + if opex_bom.empty and self.data.lifetime is not None: + 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: + net_coeff = self.data.network_efficiency + else: + net_coeff = 1 + + # 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() + + elif ( + self.data.estimate_energy_record + 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, + annual_energy, + net_coeff, + ) + + if debug_entry: + return + + outputs = _get_outputs( + capex_bom, + opex_bom, + energy_record, + self.data.discount_rate, + self.data.externalities_capex, + self.data.externalities_opex, + ) + + for k, v in outputs.items(): + self.data[k] = v + + +def _get_outputs( + capex_bom: pd.DataFrame, + opex_bom: pd.DataFrame, + energy_record: pd.DataFrame, + discount_rate: float, + externalities_capex: Optional[float], + externalities_opex: Optional[float], +) -> dict[str, Any]: + series = [opex_bom, energy_record] + 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) + + 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 + phase_breakdown = None + opex_total = None + discounted_opex = None + energy_total = None + discounted_energy = None + lcoe_capex = None + lcoe_opex = None + lcoe_total = None + + if not capex_bom.empty: + add_costs_to_bom(capex_bom, discount_rate) + 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 + 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 + ) + + 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) + + 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_total > 0: + lcoe_capex = discounted_capex_total / discounted_energy + lcoe_total = lcoe_capex.copy() + + 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 outputs + + outputs["economics_metrics"] = metrics_table + outputs.update( + _get_outputs_stats( + metrics_table, + opex_total, + discounted_opex, + discounted_energy, + lcoe_total, + discounted_capex_total, + ) + ) + + # 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 and 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 + + if outputs["discounted_opex_mean"] is not None: + lifetime_discounted_cost_mean += outputs["discounted_opex_mean"] + + outputs["discounted_lifetime_cost_mean"] = lifetime_discounted_cost_mean + + if not capex_bom.empty and outputs["discounted_opex_mode"] is not None: + lifetime_discounted_cost_mode = discounted_capex_total + + 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 + + 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"] + + # 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_opex_base = 0.0 + + # CAPEX vs OPEX Breakdown + breakdown = { + "Discounted CAPEX": discounted_capex_total, + "Discounted OPEX": discounted_opex_base, + } + + outputs["cost_breakdown"] = breakdown + + if energy_record.empty: + return outputs + + if outputs["discounted_energy_mode"] is not None: + discounted_energy_base = outputs["discounted_energy_mode"] + else: + 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: + capex_lcoe_breakdown = { + k: round(factor * v["discounted_costs"] / discounted_energy_base, 2) + for k, v in phase_breakdown.iterrows() + } + outputs["capex_lcoe_breakdown"] = capex_lcoe_breakdown + total_capex = sum(capex_lcoe_breakdown.values()) + else: + total_capex = 0.0 + + if not opex_bom.empty: + lcoe_maintenance = round( + factor * discounted_maintenance / discounted_energy_base, 2 + ) + + 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 + + if total_capex > 0.0 or total_opex > 0.0: + outputs["lcoe_breakdown"] = {"CAPEX": total_capex, "OPEX": total_opex} + + return outputs + + +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", 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), + ("Discounted Energy", discounted_energy, 1e-6), # from Wh to MWh + ] + missing_cols = [] + metrics_dict = {} + + 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) == 0: + return + + # Set columns with missing data + for col_name in missing_cols: + metrics[missing_cols] = np.nan + + return metrics + + +def _get_outputs_stats( + 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, + "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() + 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"] = opex_mean + outputs["discounted_energy_mean"] = energy_mean / 1e6 # W to MW + + mode_coords = distribution.mode() + 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"] = opex_mode + outputs["discounted_energy_mode"] = energy_mode / 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 = [ + (discounted_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) + _get_lcoe_stats(outputs, lcoe_total) + + 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) + + if lcoe_total is not None: + _get_lcoe_stats(outputs, lcoe_total) + + return outputs + + +def _get_discounted_opex_stats(outputs: dict[str, Any], discounted_opex): + try: + distribution = UniVariateKDE(discounted_opex) + outputs["discounted_opex_mean"] = distribution.mean() + outputs["discounted_opex_mode"] = distribution.mode() + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + outputs["discounted_opex_lower"] = intervals[0] + outputs["discounted_opex_upper"] = intervals[1] + + except np.linalg.LinAlgError: + outputs["discounted_opex_mean"] = discounted_opex.mean() + + +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 + + intervals = distribution.confidence_interval(95) + + if intervals is not None: + outputs["discounted_energy_lower"] = intervals[0] / 1e6 + outputs["discounted_energy_upper"] = intervals[1] / 1e6 + + except np.linalg.LinAlgError: + 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, + discounted_opex_base, + discount_rate, +): + years = range(1, 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 + + return { + "Maintenance": discounted_maintenance, + "Externalities": discounted_external, + } 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..ed3550cb --- /dev/null +++ b/packages/dtocean-economics/test_data/inputs_economics.py @@ -0,0 +1,65 @@ +# -*- 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 +externalities_opex = 1e3 + +zero_bom_dict = { + "Quantity": [5, 10], + "Cost": [100, 50], + "Year": [0, 0], +} +zero_bom = pd.DataFrame(zero_bom_dict) + +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], + "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, + "project.externalities_opex": externalities_opex, +} + +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..cd4a989d --- /dev/null +++ b/packages/dtocean-economics/test_data/inputs_economics_estimate.py @@ -0,0 +1,32 @@ +# -*- 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": 4383.0, + "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/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/__init__.py b/packages/dtocean-economics/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_functions.py b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py new file mode 100644 index 00000000..98e5da96 --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_economics/test_functions.py @@ -0,0 +1,111 @@ +# -*- 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 import ( + add_costs_to_bom, + get_discounted_values, + get_phase_breakdown, + get_present_values, +) + +YEAR_ONE = 6 / 5 +YEAR_TWO = 36 / 25 +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): + 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) + + assert result is not None + 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 + + assert "unitary_cost" not in result + + +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 + + +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]) + dr = 1 / 5 + expected = np.array([1, 1, 1, 1]) + + result = get_present_values(value, year, dr) + + assert np.isclose(result, expected).all() diff --git a/packages/dtocean-economics/tests/dtocean_economics/test_preprocessing.py b/packages/dtocean-economics/tests/dtocean_economics/test_preprocessing.py new file mode 100644 index 00000000..d3e8327c --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_economics/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/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..89ad6daf --- /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_economics.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/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/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..36ca706a --- /dev/null +++ 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") 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..423dc3b7 --- /dev/null +++ b/packages/dtocean-economics/tests/dtocean_plugins/themes/test_themes_economics.py @@ -0,0 +1,1634 @@ +import os +from copy import deepcopy +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 scipy.integrate import simpson + +from dtocean_plugins.themes.economics import _get_outputs + +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( + inputs_economics, + 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, inputs_economics) + 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( + mocker, + inputs_economics, + 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}, + ) + + project_menu = ProjectMenu() + project = deepcopy(tidal_project) + + theme_name = "Economics" + 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) + 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() + + _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] + externalities_capex = _get_outputs_args[4] + externalities_opex = _get_outputs_args[5] + + capex_bom_elec = capex_bom[ + capex_bom["phase"] == "Electrical Sub-Systems" + ].drop("phase", axis=1) + assert len(capex_bom_elec) == 1 + 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], + "unitary_cost": [100, 50], + "project_year": [0, 0], + } + expected_bom_mandf = pd.DataFrame(expected_bom_mandf_dict).astype( + pd.Int64Dtype() + ) + + 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) + + 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 capex_bom_ext_i["quantity"] == 1 + 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 + 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) + + 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( + inputs_economics_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, inputs_economics_estimate) + 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( + 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) + + 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] + + 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 == 10000.0 + 2 * 10000.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 + + energy_record_energy = energy_record_energies.pop() + 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 +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": [ + 0.0, + 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_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 + + 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 = 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 = 3 + 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 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"] == 180 + 150 + 125 + assert opex_breakdown["Maintenance"] == 3 + + 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( + (180 + 150 + 125) / discounted_energy_metric_expected * 1e-1, + 2, + ) + assert abs(opex_lcoe_breakdown["Externalities"] - expected) < 0.02 + + expected = round( + 3 / 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 + + +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.0, + 0.5 * YEAR_ONE * 1e5, + 0.5 * YEAR_TWO * 1e5, + 0.5 * YEAR_THREE * 1e5, + ], + "cost 1": [ + 0.0, + 1 * YEAR_ONE * 1e5, + 1 * YEAR_TWO * 1e5, + 1 * YEAR_THREE * 1e5, + ], + "cost 2": [ + 0.0, + 1.5 * YEAR_ONE * 1e5, + 1.5 * YEAR_TWO * 1e5, + 1.5 * YEAR_THREE * 1e5, + ], + "cost 3": [ + 0.0, + 0.5 * YEAR_ONE * 1e5, + 0.5 * YEAR_TWO * 1e5, + 0.5 * YEAR_THREE * 1e5, + ], + "cost 4": [ + 0.0, + 1.5 * YEAR_ONE * 1e5, + 1.5 * YEAR_TWO * 1e5, + 1.5 * YEAR_THREE * 1e5, + ], + "cost 5": [ + 0.0, + 0.75 * YEAR_ONE * 1e5, + 0.75 * YEAR_TWO * 1e5, + 0.75 * YEAR_THREE * 1e5, + ], + "cost 6": [ + 0.0, + 1 * YEAR_ONE * 1e5, + 1 * YEAR_TWO * 1e5, + 1 * YEAR_THREE * 1e5, + ], + "cost 7": [ + 0.0, + 1.25 * YEAR_ONE * 1e5, + 1.25 * YEAR_TWO * 1e5, + 1.25 * YEAR_THREE * 1e5, + ], + "cost 8": [ + 0.0, + 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 * (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 = 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 + 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 * (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 = 3 * 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 * (YEAR_ONE + YEAR_TWO + YEAR_THREE) + assert np.isclose(outputs["lifetime_opex_mean"], lifetime_opex_expected) + + discounted_opex_expected = 3 * 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 + + +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) diff --git a/packages/dtocean-economics/tests/test_docs.py b/packages/dtocean-economics/tests/test_docs.py new file mode 100644 index 00000000..7aa270c4 --- /dev/null +++ b/packages/dtocean-economics/tests/test_docs.py @@ -0,0 +1,11 @@ +import doctest +from pathlib import Path + +THIS_DIR = Path(__file__).parent + + +def test_README(): + 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 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/poetry.lock b/poetry.lock index c8fdd1f9..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" @@ -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"}, @@ -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] @@ -868,6 +869,26 @@ xlwt = "^1.3.0" type = "directory" url = "packages/dtocean-dummy-module" +[[package]] +name = "dtocean-economics" +version = "2.0.2" +description = "Economic assessment module for the DTOcean tools" +optional = false +python-versions = ">=3.12,<3.15" +groups = ["dtocean", "dtocean-economics"] +files = [] +develop = true +markers = {dtocean = "python_version < \"3.14\""} + +[package.dependencies] +contourpy = "^1.3.1" +pandas = "^3.0.1" +scipy = "^1.17.0" + +[package.source] +type = "directory" +url = "packages/dtocean-economics" + [[package]] name = "dtocean-hydrodynamics" version = "4.0.3" @@ -1766,7 +1787,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 +1901,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 +2867,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"}, @@ -3345,7 +3366,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-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"}, @@ -3528,7 +3549,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 +4026,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 +4471,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..8da6b470 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 } @@ -134,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